Pro*_*icT 3 c++ winapi image-processing
我想用一种特定颜色裁剪图像,就像透明蒙版一样,并且我想创建包围图像的最小盒子。
一张图片可以更好地解释我的意思:
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));
Run Code Online (Sandbox Code Playgroud)
我想,我也知道如何确定最后一行,但我不确定这一点,也不知道如何找出边界框的侧面。
要找到图像的边界框,您只需按行和列浏览图像,直到找到不透明像素。通过这样做,您可以获得边界框的最小值和最大值。
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
Run Code Online (Sandbox Code Playgroud)
希望我的回答对您有帮助。