【问题标题】:Detecting specific RGB values in a UIImageview/bitmap in iOS在 iOS 的 UIImageview/位图中检测特定的 RGB 值
【发布时间】:2013-11-05 17:40:07
【问题描述】:

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

我当前的代码(改编自另一个 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);

        }
    }
}                

}

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

【问题讨论】:

  • 你能显示一些代码和你得到的输出结果或错误吗?
  • 我没有收到任何错误,我只是想找到解决问题的方法。如果您有兴趣,代码在我发布的链接上。
  • 为什么不起作用?出了什么问题?你试过什么?
  • 一方面,上面的代码与您最初链接的示例不匹配。您永远不会像他们在示例中那样创建位图上下文、绘制到该上下文中或从该上下文中读取数据。您正在尝试将 CGImageRef 直接传递给采用 CFDataRef 的函数,但这是行不通的。您必须遵循该示例的字母,或查看此处的示例:stackoverflow.com/questions/3284185/get-pixel-color-of-uiimage。作为警告,那里投票率最高的答案假定了特定的像素格式,而您的图像中可能不是这种情况。
  • @TonyHematite - 对,但您仍在尝试将 CGImage 传递给采用 CFData 的函数。它们是完全不同类型的对象,这就是失败的原因。您需要首先从您的 CGImage 中提取 CFData,方法是将 CGImage 重新绘制到位图上下文中(最安全的方式),或者在您链接的问题中使用 CGDataProviderCopyData() 行。

标签: ios image uiimageview rgb pixel


【解决方案1】:

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

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

 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);
            }
        }
    }

感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多