ios - 你如何在 iOS 上的图像中找到特定颜色的区域?

标签 ios objective-c image-processing

我正在做一个图像处理 iOS 应用程序,我们有一个大图像(例如:大小为 2000x2000)。假设图像是全黑的,除了图像的一部分是不同的颜色(假设该区域的大小为 200x200)。

SI 想要计算不同颜色区域的开始和结束位置。我怎样才能做到这一点?

最佳答案

下面是一种允许 CPU 从 UIImage 获取像素值的简单方法。步骤是

  • 为像素分配缓冲区
  • 使用缓冲区作为后备存储创建位图内存上下文
  • 将图像绘制到上下文中(将像素写入缓冲区)
  • 检查缓冲区中的像素
  • 释放缓冲区和相关资源

- (void)processImage:(UIImage *)input
{
    int width  = input.size.width;
    int height = input.size.height;

    // allocate the pixel buffer
    uint32_t *pixelBuffer = calloc( width * height, sizeof(uint32_t) );

    // create a context with RGBA pixels
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate( pixelBuffer, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast );

    // invert the y-axis, so that increasing y is down
    CGContextScaleCTM( context, 1.0, -1.0 );
    CGContextTranslateCTM( context, 0, -height );

    // draw the image into the pixel buffer
    UIGraphicsPushContext( context );
    [input drawAtPoint:CGPointZero];
    UIGraphicsPopContext();

    // scan the image
    int x, y;
    uint8_t r, g, b, a;
    uint8_t *pixel = (uint8_t *)pixelBuffer;

    for ( y = 0; y < height; y++ )
        for ( x = 0; x < height; x++ )
        {
            r = pixel[0];
            g = pixel[1];
            b = pixel[2];
            a = pixel[3];

            // do something with the pixel value here

            pixel += 4;
        }

    // release the resources
    CGContextRelease( context );
    CGColorSpaceRelease( colorSpace );
    free( pixelBuffer );
}

关于ios - 你如何在 iOS 上的图像中找到特定颜色的区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23357347/

相关文章:

ios - 在单元格之间的 UICollectionView 中设置/覆盖填充

objective-c - iOS 和 OS X 开发的内置框架中是否有任何非前缀类?

objective-c - 设置 NSDatePicker 委托(delegate)

iphone - UITextAttributeTextShadowOffset 已弃用

algorithm - 如何生成强度在[0.5 1.5]范围内缓慢变化的圆圈?

ios - Xcode 6 : how to set a custom bundle identifier?

iOS 结合视频数据和照片的捕获输出

objective-c - 由于objectID在临时对象和永久对象之间变化,如何有效地处理Core Data中的临时对象?

swift - 为什么具有透明背景的 NSImage 得到的 RGB 值为 (0,0,0)?

python - 从噪声数据中插入连续曲线