c# 从图像中获取矩形边界
c# get rectangle bounds from image
假设我有一张图片
我想找到图像中的黑色矩形边界(右、左、宽、高)(假设此图像中没有其他黑色像素)。
到目前为止我的代码是:
private unsafe Bitmap GetDiffBitmap(Bitmap bmp)
{
bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
IntPtr scan0 = bmData.Scan0;
int stride = bmData.Stride;
int nWidth = bmp.Width;
int nHeight = bmp.Height;
for(int y = 0; y < nHeight; y++)
{
//define the pointers inside the first loop for parallelizing
byte* p = (byte*)scan0.ToPointer();
p += y * stride;
for (int x = 0; x < nWidth; x++)
{
//always get the complete pixel when differences are found
if(p[0]==0 && p[1]==0 && p[2]==0)
{
// p[0] = 255;
// p[1] = 255;
// p[2] =255;
right = nWidth;//geting the position of the lastest black pixel;
}
p += 4;
}
}
bmp.UnlockBits(bmData);
return bmp;
}
我的 nwidth 似乎也是图像宽度 - 所以它不起作用..我可以访问这些像素并且我可以更改它们但我不知道为什么我可以计算它们并找到合适的边界黑色矩形...如果有人能帮助我,我会非常感激,
这种图像分析存在一些问题:
1个替换
if(p[0]==0 && p[1]==0 && p[2]==0)
{
right = nWidth;//geting the position of the lastest black pixel;
}
和
if(p[0]==0 && p[1]==0 && p[2]==0)
{
right = x; //geting the position of the lastest black pixel;
}
您的 x 迭代变量已经计算出您所在的像素。
2 您提供的代码仅适用于 32bpp 像素格式。如果这是故意的,您应该检查您正在分析的位图是否采用兼容格式。
3 对于大多数压缩图像格式,您通常不会在黑色的所有 3 个颜色通道上都得到准确的 0,您应该进行 "less than something dark" 检查而不是零。
假设我有一张图片
我想找到图像中的黑色矩形边界(右、左、宽、高)(假设此图像中没有其他黑色像素)。 到目前为止我的代码是:
private unsafe Bitmap GetDiffBitmap(Bitmap bmp)
{
bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
IntPtr scan0 = bmData.Scan0;
int stride = bmData.Stride;
int nWidth = bmp.Width;
int nHeight = bmp.Height;
for(int y = 0; y < nHeight; y++)
{
//define the pointers inside the first loop for parallelizing
byte* p = (byte*)scan0.ToPointer();
p += y * stride;
for (int x = 0; x < nWidth; x++)
{
//always get the complete pixel when differences are found
if(p[0]==0 && p[1]==0 && p[2]==0)
{
// p[0] = 255;
// p[1] = 255;
// p[2] =255;
right = nWidth;//geting the position of the lastest black pixel;
}
p += 4;
}
}
bmp.UnlockBits(bmData);
return bmp;
}
我的 nwidth 似乎也是图像宽度 - 所以它不起作用..我可以访问这些像素并且我可以更改它们但我不知道为什么我可以计算它们并找到合适的边界黑色矩形...如果有人能帮助我,我会非常感激,
这种图像分析存在一些问题:
1个替换
if(p[0]==0 && p[1]==0 && p[2]==0)
{
right = nWidth;//geting the position of the lastest black pixel;
}
和
if(p[0]==0 && p[1]==0 && p[2]==0)
{
right = x; //geting the position of the lastest black pixel;
}
您的 x 迭代变量已经计算出您所在的像素。
2 您提供的代码仅适用于 32bpp 像素格式。如果这是故意的,您应该检查您正在分析的位图是否采用兼容格式。
3 对于大多数压缩图像格式,您通常不会在黑色的所有 3 个颜色通道上都得到准确的 0,您应该进行 "less than something dark" 检查而不是零。