繁体   English   中英

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-iteration变量已经计算出您所在的像素。

2您提供的代码仅适用于32bpp像素格式。 如果这是故意的,则应检查所分析的位图是否为兼容格式。

3对于大多数压缩图像格式,您通常不会在所有3个彩色通道上获得完全为0的黑色,因此应进行“小于暗”检查,而不是零。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM