如何从UIImage获得极限点

时间:2013-10-02 19:11:30

标签: ios uiimage

我的图像包含很少的不同颜色的对象。图像的背景是白色。

我需要找到左上角和右下角的点来裁剪物体,然后跳起来。

下图显示了我需要裁剪的一个灰色物体(不包括小点和标签),但首先我需要获得这些极端点。

enter image description here

1 个答案:

答案 0 :(得分:1)

// Extract the bitmap data from the image
unsigned char* imageData= [self extractImageDataForImage:self.image];

// Iterate through the matrix and compare pixel colors

for (int i=0; i< height; i++){
    for(int j=0; j<width*4; j+=4){ // assuming we extracted the RGBA image, therefore the 4 pixels, one per component
         int pixelIndex= (i*width*4) + j;
         MyColorImpl* pixelColor= [self colorForPixelAtIndex:pixelIndex imageData:imageData];
         if( [self isColorWhite:pixelColor] ){
              // we're not interested in white pixels
         }else{
             // The reason not to use UI color a few lines above is so you can compare colors in the way you want. 
             // You can say that two colors are equal if the difference for each component is not larger than x. 
             // That way you can locate pixels with equal color even if they are almost the same color.

             // Let's say current color is yellow

             // Get the object that contains the info for the yellow drawable

             MyColoredObjectInformation* info= [self.coloredObjectDictionary objectForKey:pixelColor.description];

             if(!info){
                 //it doesn't exist. So lets create it and map it to the yellow color

                 info= [MyColoredObjectInformation new];
                 [self.coloredObjectDictionary setObject:info forKey:pixelColor.description];
             }
             // get x and y for the current pixel

             float pixelX= pixelIndex % (width*4);
             float pixelY= i;

             if(pixelX < info.xMin)
                  info.xMin= pixelX;

             if(pixelX > info.xMax)
                  info.xMax= pixelX;

             if(pixelY > info.yMax)
                  info.yMax= pixelY;

             if(pixelY < info.yMin)
                  info.yMin= pixelY;
         }
    }
}

// don't forget to free the array (since it's been allocated dynamically in extractImageForDataForImage:]
free(imageData];

不要忘记将xMin,xMax,yMin和yMax设置为每个对象的适当值

@implementation MyColoredObjectInformation

-(id)init{
    if( self= [super init]){
         self.xMin= -1;
         self.xMax= INT_MAX;
         self.yMin= -1;
         self.yMax= INT_MAX;
    }
 return self;
 }

将图像转换为数据阵列时可能发生的一件事是像素不会出现顶部&gt;底部&amp;左&GT;对。通常,当您将图像转换为CGImage时,可以旋转图像。在这种情况下,您将只有pixelIndex,pixelX和pixelY的不同公式。

最后,只需遍历self.coloredObjectDictionary的值,对于每种颜色,您将有两个点代表对象p1周围的矩形(xMin,yMin)和p2(xMax,yMax)