循环遍历所有像素的程序并检查其RGB值Swift

时间:2017-09-05 06:56:27

标签: ios swift uiimage

你好我对swift很新。我正在尝试创建一个程序,该程序采用UIImage并循环检查每个像素的RGB值,以查看它们是否等于某一范围的颜色。我在Java方面有一点经验,但并不是很快。我已经用Java编写了程序。我试图在下面的快速操场上复制它。有一些注释试图解释我的伪代码的意图。

//: 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
    }

}

//使用黑色或白色像素再次显示图像的功能,因为for循环已完成以查看更改的像素。

我真的很感激能帮助我使这段代码可行的任何人。任何编辑和建议表示赞赏。非常感谢你!

0 个答案:

没有答案
相关问题