Hello I am very new to swift. I am trying to create a program that takes a UIImage and loops through it checking each pixel's RGB values to see if they are equal to a certain range of colors. I have a little experience in Java, but not much in swift. I have already made the program in Java. I have tried to replicate it in swift playground below. There are some comments to try to explain what my pseudo code intends.
//: Playground - noun: a place where people can play
import UIKit
// create constant that is the image
let profilePicture = UIImage(named: "meal1.jpg")
//loop through every pixel of that image and pass the specific pixel value into the function getPixelColor
for yCo in 0 ..< Int(profilePicture.size.height) {
for xCo in 0 ..< Int(profilePicture.size.width) {
profilePicture.getPixelColor(pos: CGPoint(x: xCo, y: yCo))
}
}
//This function takes a specific pixel, gets the pixels red, green, and blue value and then checks to see if these value fall within a certain range of colors. The function itself I found on another stackoverflow question. I inserted the if statement at the end of it.
func getPixelColor(pos: CGPoint) -> UIColor {
int allPixelCounter = 0
int specificPixelColorsCounter = 0
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
var red = CGFloat(data[pixelInfo]) / CGFloat(255.0)
var green = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
var blue = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
//let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
if red <= 130 && green >= 110 && blue <= 120 {
specificPixelColorsCounter = specificPixelColorsCounter + 1
//code to set this pixel to be white
} else {
allPixelCounter = allPixelCounter +1
//code to set this pixel to be black
}
}
//Function to display the image again with the pixels all either black or white now that for loop has finished to see what pixels were changed.
I would really appreciate anyone who could help me make this code workable. Any edits and advice is appreciated. Thank you very much!