I'm trying to implement an image algorithm that iterates the byte array of the image.
(I'm trying to replicate this in Swift... https://rosettacode.org/wiki/Percentage_difference_between_images#JavaScript)
However, I need to ignore the alpha byte.
I was trying to be clever about it but got to the point where I can no longer remove the 4th items from the arrays of bytes.
Is there an easy way of doing that?
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)
}
This would do exactly what I needed if I was able to remove/ignore the 4th bytes from each array?
The other option is to stride the arrays 4 at a time like it does in the Javascript example linked to but I felt I preferred this method. :)