0

我目前正在尝试找到一种从 iOS 中的 UIImageview 中找到一些 rgba 值的方法。例如,我想0-0-0在白色背景上找到所有黑色像素1-1-1并输出它们的坐标。

我当前的代码(改编自另一个stackoverflow帖子):

 UIImage *myPicture = [UIImage imageNamed:@"somePicture.png"];

CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(myPicture.CGImage));

myWidth = CGImageGetWidth(myPicture.CGImage);
myHeight = CGImageGetHeight(myPicture.CGImage);

const UInt8 *pixels = CFDataGetBytePtr(pixelData);
UInt8 blackThreshold = 10; 
int bytesPerPixel_ = 4;
for( x = 0; x < myWidth; x++)
    for( y = 0; y < myHeight; y++) 

    {
        {
        int pixelStartIndex = (x + (y * myWidth)) * bytesPerPixel_;
        UInt8 redVal = pixels[pixelStartIndex + 1];
        UInt8 greenVal = pixels[pixelStartIndex + 2];
        UInt8 blueVal = pixels[pixelStartIndex + 3];
        if(redVal < blackThreshold && blueVal < blackThreshold && greenVal < blackThreshold) {
            NSLog(@"x coordinate = %@", x);
            NSLog(@"y coordinate = %@", y);

        }
    }
}                

}

有人可以查看代码并就可能的解决方案提供一些反馈吗?

4

1 回答 1

2

经过一点调试,我解决了这个问题。

这是我的较暗像素坐标的代码:

 CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
    int myWidth = CGImageGetWidth(image.CGImage);
    int myHeight = CGImageGetHeight(image.CGImage);
    const UInt8 *pixels = CFDataGetBytePtr(pixelData);
    UInt8 blackThreshold = 10 ;
    //UInt8 alphaThreshold = 100;
    int bytesPerPixel_ = 4;
    for(int x = 0; x < myWidth; x++)
    {
        for(int y = 0; y < myHeight; y++)
        {
            int pixelStartIndex = (x + (y * myWidth)) * bytesPerPixel_;
            UInt8 alphaVal = pixels[pixelStartIndex];
            UInt8 redVal = pixels[pixelStartIndex + 1];
            UInt8 greenVal = pixels[pixelStartIndex + 2];
            UInt8 blueVal = pixels[pixelStartIndex + 3];

            if(redVal < blackThreshold || blueVal < blackThreshold || greenVal < blackThreshold || alphaVal < blackThreshold)
            {
                NSLog(@"x %d, y = %d", x, y);
            }
        }
    }

谢谢你们的帮助。

于 2013-01-14T13:34:31.177 回答