gpt4 book ai didi

ios - 如何从 UIImage 获取极值点

转载 作者:行者123 更新时间:2023-11-29 13:03:46 26 4
gpt4 key购买 nike

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

我需要找到左上角点和右下角点来裁剪带有物体反弹的图像。

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

enter image description here

最佳答案

// 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, y最大)

关于ios - 如何从 UIImage 获取极值点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19144943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com