I need some help with how to iterate through every pixel in a UIImage. I am finding the red, green, blue, and alpha color values in every pixel then comparing them to see if a certain color exists in the photo.
I have an extension that returns these color values of a pixel:
extension UIImage { func getPixelColor(pos: CGPoint) -> UIColor {
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
I am able to find the color value of a specific pixel in the image and check it to see if it matches a specific color value:
let specificPoint = CGPoint(x: 25, y: 25)
let findColorValue = displayImage.image?.getPixelColor(pos: specificPoint)
var redval: CGFloat = 0
var greenval: CGFloat = 0
var blueval: CGFloat = 0
var alphaval: CGFloat = 0
resultLabel.text = "r: \(redval) g: \(greenval) b: \(blueval) a: \(alphaval)"
findColorValue?.getRed(&redval, green: &greenval, blue: &blueval, alpha: &alphaval)
if resultLabel.text == "r: 1.0 g: 0.792156862745098 b: 0.474509803921569 a: 0.0156862745098039" {
resultLabel.text = "YES"
} else {
resultLabel.text = "NO"
}
I need help creating a for loop to loop through all the pixels in the image and being able to test them for the specific color value.
I'm also not sure if how I get the color values of a pixel is 100% right so feel free to tell me if I'm doing something wrong.
Thanks
Use a nested for loop:
for yCo in 0 ..< Int(image.size.height) {
for xCo in 0 ..< Int(image.size.width) {
if image.getPixelColor(pos: CGPoint(x: xCo, y: yCo)) == UIColor(red: 1, green: 1, blue: 1, alpha: 1) {
//Next step
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With