【问题标题】:Getting into pixel data of NSImage进入 NSImage 的像素数据
【发布时间】:2010-07-20 11:20:15
【问题描述】:

我正在编写对黑白图像进行操作的应用程序。我通过将 NSImage 对象传递到我的方法中,然后从 NSImage 生成 NSBitmapImageRep 来做到这一点。一切正常,但速度很慢。这是我的代码:

- (NSImage *)skeletonization: (NSImage *)image
{
    int x = 0, y = 0;
    NSUInteger pixelVariable = 0;

    NSBitmapImageRep *bitmapImageRep = [[NSBitmapImageRep alloc] initWithData:[image TIFFRepresentation]];

    [myHelpText setIntValue:[bitmapImageRep pixelsWide]];
    [myHelpText2 setIntValue:[bitmapImageRep pixelsHigh]];

    NSColor *black = [NSColor blackColor];
    NSColor *white = [NSColor whiteColor];
    [myColor set];
    [myColor2 set];

    for (x=0; x<=[bitmapImageRep pixelsWide]; x++) {
        for (y=0; y<=[bitmapImageRep pixelsHigh]; y++) {
            // This is only to see if it's working
            [bitmapImageRep setColor:myColor atX:x y:y];
        }
    }

    [myColor release];
    [myColor2 release];

    NSImage *producedImage = [[NSImage alloc] init];
    [producedImage addRepresentation:bitmapImageRep];
    [bitmapImageRep release];

    return [producedImage autorelease];
}

所以我尝试使用 CIImage,但我不知道如何通过 (x,y) 坐标进入每个像素。这真的很重要。

【问题讨论】:

  • 为什么要设置颜色?这是完全没有意义的,因为没有锁定焦点,而且你也没有用这些颜色绘制任何东西。并不是说删除它会加速你的代码,我只是想让你知道。
  • 您访问每个像素的方式并不理想,我也不确定您究竟想在这里做什么;您所做的只是将图像中每个像素的颜色更改为某种颜色(不知道这是从哪里来的),但是您说此代码只是为了查看它是否有效。如果您希望我发布更好的解决方案,我需要更多信息,例如什么样的图像是命名的源图像,什么样的图像是生成的图像。我想我当然可以大大加快你的代码速度,但如果我不知道它应该做什么,那就不行了。

标签: cocoa cgimage nsimage nsbitmapimagerep


【解决方案1】:

使用 NSImage 中的 representations 数组属性来获取您的 NSBitmapImageRep。它应该比将图像序列化为 TIFF 然后再返回更快。

使用NSBitmapImageRepbitmapData 属性直接访问图像字节。

例如

unsigned char black = 0;
unsigned char white = 255;

NSBitmapImageRep* bitmapImageRep = [[image representations] firstObject];
// you will need to do checks here to determine the pixelformat of your bitmap data
unsigned char* imageData = [bitmapImageRep bitmapData];

int rowBytes = [bitmapImageRep bytesPerRow];
int bpp = [bitmapImageRep bitsPerPixel] / 8;

for (x=0; x<[bitmapImageRep pixelsWide]; x++) {  // don't use <= 
    for (y=0; y<[bitmapImageRep pixelsHigh]; y++) {

       *(imageData + y * rowBytes + x * bpp ) = black; // Red
       *(imageData + y * rowBytes + x * bpp +1) = black;  // Green
       *(imageData + y * rowBytes + x * bpp +2) = black;  // Blue
       *(imageData + y * rowBytes + x * bpp +3) = 255;  // Alpha
    }
}

您需要知道您在图像中使用的像素格式,然后才能使用其数据,查看 NSBitmapImageRep 的 bitsPerPixel 属性以帮助确定您的图像是否为 RGBA 格式。

您可以使用灰度图像、RGB 图像或 CMYK 图像。或者先将图像转换为您想要的图像。或者以不同的方式处理循环中的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多