首先是对图片进行处理:
//1.缩小图片尺寸 func scaletoSize(img: UIImage,size: CGSize) -> UIImage { UIGraphicsBeginImageContext(size) img.draw(in: CGRect(x: 0,y: 0,wIDth: size.wIDth,height: size.height)) let scaledImage = UIGraphicsGetimageFromCurrentimageContext() UIGraphicsEndImageContext() return scaledImage! }
//2.简化色彩 将图片转换成灰度图片 func getGrayImage(sourceImage: UIImage) -> UIImage { let imageRef: CGImage = sourceImage.cgImage! let wIDth: Int = imageRef.wIDth let height: Int = imageRef.height let colorSpace = CGcolorSpaceCreateDeviceGray() let bitmAPInfo = CGBitmAPInfo(rawValue: CGImageAlphaInfo.none.rawValue) let context: CGContext = CGContext(data: nil,wIDth: wIDth,height: height,bitsPerComponent: 8,bytesPerRow: 0,space: colorSpace,bitmAPInfo: bitmAPInfo.rawValue)! let rect: CGRect = CGRect.init(x: 0,height: height) context.draw(imageRef,in: rect) let outPutimage: CGImage = context.makeImage()! let newImage: UIImage = UIImage.init(cgImage: outPutimage) return newImage }
//3. 计算平均值,比较像素的灰度 func pHashValueWithImage(image: UIImage) -> Nsstring { let pHashString = NSMutableString() let imageRef = image.cgImage! let wIDth = imageRef.wIDth let height = imageRef.height let pixelData = imageRef.dataProvIDer!.data let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) var sum: Int = 0 for i in 0..<wIDth * height { if data[i] != 0 { sum = sum + Int(data[i]) } } let avr = sum / (wIDth * height) for i in 0..<wIDth * height { if Int(data[i]) >= avr { pHashString.append("1") } else { pHashString.append("0") } } return pHashString }
//4.计算哈希值 如果不相同的数据位不超过5,就说明两张图片很相似;如果大于10,就说明这是两张不同的图片。 func getDifferentValueCountWithString(str1: Nsstring,str2: Nsstring) -> NSInteger { var diff: NSInteger = 0 let s1 = str1.utf8String! let s2 = str2.utf8String! for i in 0..<str1.length { if s1[i] != s2[i] { diff += 1 } } return diff }
写个共用方法来比较两个图片是否相同
/// 比较两个图片是否相同,这里比较尺寸为20*20 /// /// - Parameters: /// - imageOne: 图片1 /// - imageTwo: 图片2 /// - Returns: 是否相同的布尔值 func isEqualimage(imageOne: UIImage,imageTwo: UIImage) -> Bool { var equalResult = false let mImageOne = self.getGrayImage(sourceImage: self.scaletoSize(img: imageOne,size: CGSize(wIDth: 20,height: 20))) let mImageTwo = self.getGrayImage(sourceImage: self.scaletoSize(img: imageTwo,height: 20))) let diff = self.getDifferentValueCountWithString(str1: self.pHashValueWithImage(image: mImageOne),str2: self.pHashValueWithImage(image: mImageTwo)) print(diff) if diff > 10 { equalResult = false } else { equalResult = true } return equalResult }
通过调用上面的共用方法,传入两个待比较的UIImage对象,得到返回的Bool,根据该布尔值进行相应的 *** 作
总结以上是内存溢出为你收集整理的swift 判断/比较两张图片是否相同 - 感知哈希算法全部内容,希望文章能够帮你解决swift 判断/比较两张图片是否相同 - 感知哈希算法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)