0

I have a UIImageView in my Xcode project. I am trying to find a way that I can detect CERTAIN colors (e.g. Some shade of red) in an image. I can't seem to find any way to do this. Does anyone know how this could be achieved?

I have seen different ways how to find the "average color" in the photo. I am wondering if there is a way to specifically "detect" a certain color that may be in an image.

For example in this image is there a way I can detect that there is that color of red in the photo. Blue and Red Rectangles

Thanks

Pickle2113
  • 61
  • 6
  • You really haven't given enough detail. For instance, what code have you tried? More, what *specifically* do you need? Are you asking to "scrape" an image and get the "average" color? Or over a certain CGRect? Or should I be asking "what is red"? I don't (yet) see a reason to flag this a "too vague", but @Pickle2113, can **you** see how poorly (so far) you've asked your question? –  Feb 23 '17 at 04:48
  • You will need to go through each pixel in the image and compare it against the color that you are looking for. There isn't an easy way to do this with UIImage but try here http://stackoverflow.com/questions/40158320/swift-3-get-color-of-pixel-in-uiimage-better-uiimageview – Kawin P. Feb 23 '17 at 05:13
  • Does that make at least a little more sense? If not tell me and I'll try to add more information again. Sorry. I'm definitely new here and I'm just looking for some help. – Pickle2113 Feb 23 '17 at 05:13
  • And thanks. I'll try that. – Pickle2113 Feb 23 '17 at 05:13

1 Answers1

0

Try this

extension UIImage { func getPixelColor(pos: CGPoint) -> UIColor {

      let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage))
      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)
  }  

}

Amit Singh
  • 172
  • 1
  • 12