1
我有這張圖像,其中包含幾個不同顏色的物體。圖像的背景是白色的。如何從UIImage獲得極端分數
我需要找到左上角的點和右下角的點來裁剪圖像與對象反彈。
下面的圖片只顯示了一個我需要裁剪的灰色物體(不包括小圓點和標籤),但起初我需要獲得這些極端點。
我有這張圖像,其中包含幾個不同顏色的物體。圖像的背景是白色的。如何從UIImage獲得極端分數
我需要找到左上角的點和右下角的點來裁剪圖像與對象反彈。
下面的圖片只顯示了一個我需要裁剪的灰色物體(不包括小圓點和標籤),但起初我需要獲得這些極端點。
// 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,y最小和y爲適當的值的每個對象
@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)