How to detect an image border programmatically?

前端 未结 5 1441
春和景丽
春和景丽 2021-02-11 07:47

I\'m searching for a program which detects the border of a image, for example I have a square and the program detects the X/Y-Coords

Example:

alt text http://img

5条回答
  •  难免孤独
    2021-02-11 08:15

    This is a very simple edge detector. It is suitable for binary images. It just calculates the differences between horizontal and vertical pixels like image.pos[1,1] = image.pos[1,1] - image.pos[1,2] and the same for vertical differences. Bear in mind that you also need to normalize it in the range of values 0..255.

    But! if you just need a program, use Adobe Photoshop.

    Code written in C#.

    public void SimpleEdgeDetection()
    {
        BitmapData data = Util.SetImageToProcess(image);
        if (image.PixelFormat != PixelFormat.Format8bppIndexed)
            return;
    
        unsafe
        {
            byte* ptr1 = (byte *)data.Scan0;
            byte* ptr2;
            int offset = data.Stride - data.Width;
            int height = data.Height - 1;
            int px;
    
            for (int y = 0; y < height; y++)
            {
                ptr2 = (byte*)ptr1 + data.Stride;
                for (int x = 0; x < data.Width; x++, ptr1++, ptr2++)
                {
                    px = Math.Abs(ptr1[0] - ptr1[1]) + Math.Abs(ptr1[0] - ptr2[0]);
                    if (px > Util.MaxGrayLevel) px = Util.MaxGrayLevel;
                    ptr1[0] = (byte)px;
                }
                ptr1 += offset;
            }
        }
        image.UnlockBits(data);
    }
    

    Method from Util Class

    static public BitmapData SetImageToProcess(Bitmap image)
    {
        if (image != null)
            return image.LockBits(
                new Rectangle(0, 0, image.Width, image.Height),
                ImageLockMode.ReadWrite,
                image.PixelFormat);
    
        return null;
    }
    

    If you need more explanation or algorithm just ask with more information without being so general.

提交回复
热议问题