2012-01-21 111 views
0

我有一张图片!自从我完成了像素检测后,我记得你必须以某种方式将像素转换为数组,然后找到图像的宽度,以了解像素何时到达一行的末尾并转到下一个像素和啊,很多复杂的东西哈哈!无论如何,我现在不知道如何做到这一点了,但我需要检测我的图像名为“image1”的y坐标的最左边最暗的像素的x & ...任何好的起始位置?检测图像上的大部分黑色像素 - objective-c iOS

回答

2

转到您的书店,找到Erica Sadun编写的名为“iOS Developer's Cookbook”的书。转到第378页,并且在那里有用于像素检测的方法。你可以看看这个RGB值的数组,并运行一个for循环来排序并找到具有最小R,G和B值之和(这将是0-255)的像素,这将给你最接近黑色的像素。 如果需要,我也可以发布代码。但这本书是最好的资料来源,因为它提供了方法和解释。

这些是我的一些变化。方法名称保持不变。我改变的是基本上来自图像选择器的图像。

-(UInt8 *) createBitmap{ 
if (!self.imageCaptured) { 
     NSLog(@"Error: There has not been an image captured."); 
     return nil; 
    } 
    //create bitmap for the image 
    UIImage *myImage = self.imageCaptured;//image name for test pic 
    CGContextRef context = CreateARGBBitmapContext(myImage.size); 
    if(context == NULL) return NULL; 
    CGRect rect = CGRectMake(0.0f/*start width*/, 0.0f/*start*/, myImage.size.width /*width bound*/, myImage.size.height /*height bound*/); //original 
// CGRect rect = CGRectMake(myImage.size.width/2.0 - 25.0 /*start width*/, myImage.size.height/2.0 - 25.0 /*start*/, myImage.size.width/2.0 + 24.0 /*width bound*/, myImage.size.height/2.0 + 24.0 /*height bound*/); //test rectangle 

    CGContextDrawImage(context, rect, myImage.CGImage); 
    UInt8 *data = CGBitmapContextGetData(context); 
    CGContextRelease(context);  
    return data; 
} 
CGContextRef CreateARGBBitmapContext (CGSize size){ 

    //Create new color space 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    if (colorSpace == NULL) { 
     fprintf(stderr, "Error allocating color space\n"); 
     return NULL; 
    } 
    //Allocate memory for bitmap data 
    void *bitmapData = malloc(size.width*size.height*4); 
    if(bitmapData == NULL){ 
     fprintf(stderr, "Error: memory not allocated\n"); 
     CGColorSpaceRelease(colorSpace); 
     return NULL; 
    } 
    //Build an 8-bit per channel context 
    CGContextRef context = CGBitmapContextCreate(bitmapData, size.width, size.height, 8, size.width*4, colorSpace, kCGImageAlphaPremultipliedFirst); 
    CGColorSpaceRelease(colorSpace); 
    if (context == NULL) { 
     fprintf(stderr, "Error: Context not created!"); 
     free(bitmapData); 
     return NULL; 
    } 
    return context; 

} 
NSUInteger blueOffset(NSUInteger x, NSUInteger y, NSUInteger w){ 
    return y*w*4 + (x*4+3); 
} 
NSUInteger redOffset(NSUInteger x, NSUInteger y, NSUInteger w){ 
    return y*w*4 + (x*4+1); 
} 

底部,redOffset的方法,将让你在ARGB(阿尔法 - 红 - 绿 - 蓝)规模的红色值。要更改ARGB中查看的通道,请将添加到redOffset函数中x变量的值更改为0以查找alpha,将其保持为1以找到红色,将其保持为1以找到绿色,将其保留为2以找到蓝色。这是可行的,因为它只是查看上述方法中创建的数组,以及对x索引值的补充。本质上,使用三种颜色(红色,绿色和蓝色)的方法,并找出每个像素的总和。无论哪个像素最低的红色,绿色和蓝色都是最黑的。

+0

啊!祝你好运!我有Erica的书“iPhone Developer's Cookbook”,但不是“iOS Developer's Cookbook”啊! :(哈哈!介意分享一些像素检测方法的名称? –

+0

这太棒了!但是如何检测MOST黑色值?如果我没有一个绝对黑色的像素,我该如何检测下一个最接近黑色的颜色? –

+0

我发现了一种非常不同的方法,它适用于我...但这确实回答了问题! –