1

我有这张图片,其中包含几个不同颜色的对象。图像背景为白色。

我需要找到左上点和右下点来裁剪图像,对象反弹。

下图只显示了我需要裁剪的一个灰色对象(不包括小点和标签),但首先我需要获取这些极值点。

在此处输入图像描述

4

1 回答 1

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

将图像转换为数据数组时可能发生的一件事是像素不会顶部-> 底部和左侧-> 右侧。通常图像在转换为 CGImage 时可以旋转。在这种情况下,您将有不同的 pixelIndex、pixelX 和 pixelY 公式。

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

于 2013-10-05T18:32:44.267 回答