gpt4 book ai didi

c++ - 在具有透明度的图像中创建边界框

转载 作者:搜寻专家 更新时间:2023-10-31 00:32:09 25 4
gpt4 key购买 nike

我想用一种特定颜色裁剪图像,就像透明蒙版一样,我想创建最小的框来包围图像。

我的意思的图片肯定会更好地解释它:

Images with bounding boxes

RGB(255,0,255) 是透明蒙版,绿色框代表所需的边界框。

我已经弄清楚了边界框的顶线:

    int nAlloc = (128 * 128) * 4;
unsigned char* buf = new unsigned char[nAlloc];
GetBitmapBits(hBMP, nAlloc, buf);
for(int i = 0; i < nAlloc; i += 4)
{
if(buf[i] == 255 && buf[i + 1] == 0 && buf[i + 2] == 255)
{
continue;
}
// If I hit a first non-transparent pixel,
// I can then calculate the row where is that pixel located.
else if(set_pixel == false)
{
set_pixel = true;
index = ceil((float)(i / 4.0 / 128.0));
}
... // Converting non-transparent pixels to Black&White
}

//I'm then drawing the bitmap to window like so:
TransparentBlt(hdc, 5, 305 - index, 128, 128, hDC, 0, 0, 128, 128, RGB(255, 0, 255));

我想,我也知道如何确定最后一行,但我不确定,也不知道如何找出边界框的边。

最佳答案

要找到图像的边界框,您只需按行和按列检查图像,直到找到不透明的像素。通过这样做,您可以获得边界框的最小值和最大值。

RECT BoundingBox = { 0,0,0,0 };
const int nAlloc = (128 * 128) * 4;
unsigned char* buf = new unsigned char[nAlloc];
GetBitmapBits(hBMP, nAlloc, buf);

bool found;

//search upper bound
found = false;
for (int row = 0; row<128 && !found; row++) //row
{
for (int col = 0; col<128 && !found; col++) //column
{
int idx = (row * 128 + col) * 4;
if (!(buf[idx] == 255 && buf[idx + 1] == 0 && buf[idx + 2] == 255)) //not transparent
{
BoundingBox.top = row;
found = true;
}
}
}

//search lower bound
found = false;
for (int row = 127; row >= 0 && !found; row--) //row
{
for (int col = 127; col >= 0 && !found; col--) //column
{
int idx = (row * 128 + col) * 4;
if (!(buf[idx] == 255 && buf[idx + 1] == 0 && buf[idx + 2] == 255)) //not transparent {
BoundingBox.bottom = row;
found = true;
}
}
}


//search left bound
found = false;
for (int col = 0; col<128 && !found; col++) //row
{
for (int row = 0; row<128 && !found; row++) //column
{
int idx = (row * 128 + col) * 4;
if (!(buf[idx] == 255 && buf[idx + 1] == 0 && buf[idx + 2] == 255)) //not transparent {
BoundingBox.left = col;
found = true;
}
}
}


//search right bound
found = false;
for (int col = 127; col >= 0 && !found; col--) //row
{
for (int row = 127; row >= 0 && !found; row--) //column
{
int idx = (row * 128 + col) * 4;
if (!(buf[idx] == 255 && buf[idx + 1] == 0 && buf[idx + 2] == 255)) //not transparent {
BoundingBox.right = col;
found = true;
}
}
}

//now the variable "BoundingBox" contains your BoundingBox

希望我的回答对您有所帮助。

关于c++ - 在具有透明度的图像中创建边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32191887/

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