【发布时间】:2017-02-24 07:05:32
【问题描述】:
我正在尝试实现一种迭代图像的字节数组的图像算法。
(我正在尝试在 Swift 中复制它...https://rosettacode.org/wiki/Percentage_difference_between_images#JavaScript)
但是,我需要忽略 alpha 字节。
我试图聪明一点,但到了无法再从字节数组中删除第 4 项的地步。
有没有简单的方法?
func compareImages(image1: UIImage, image2: UIImage) -> Double {
// get data from images
guard let data1 = UIImageJPEGRepresentation(image1, 1),
let data2 = UIImageJPEGRepresentation(image2, 1) else {
return -1
}
// zip up byte arrays
return zip([UInt8](data1), [UInt8](data2))
// sum the difference of the bytes divided by 255
.reduce(0.0) { $0 + Double(abs(Int32($1.0) - Int32($1.1))) / 255.0 }
// divide by the number of rbg bytes
/ Double(image1.size.width * image1.size.height * 3)
}
如果我能够从每个数组中删除/忽略第 4 个字节,这将完全满足我的需要?
另一种选择是像在链接到的 Javascript 示例中那样一次跨越 4 个数组,但我觉得我更喜欢这种方法。 :)
【问题讨论】:
-
我建议不要在失败的情况下使用 -1 的哨兵返回 - 您应该使用可选的并返回
nil。 -
@Hamish 是的,我同意。会更新,谢谢:D
-
仅供参考 -
UIImageJPEGRepresentation不会返回简单的 RGB 值流。它包含各种元数据和压缩的有损格式的图像数据。 -
@rmaddy 啊,好的。届时将不得不考虑另一种方法。谢谢 :D 好的,我想以后需要再运行一次。哈哈! :D