winforms 如何使用EmguCV和windows窗体裁剪图像的白色区域

ulydmbyx  于 2023-02-13  发布在  Windows
关注(0)|答案(1)|浏览(221)

我的项目需要自动裁剪图像,以消除周围的图纸(晶格)的空白。

下面是我的代码

grayImage = grayImage.ThresholdBinary(new Gray(threshold), new Gray(255));

VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
CvInvoke.FindContours(grayImage, contours, null, RetrType.External, ChainApproxMethod.ChainApproxSimple);

for (int i = 0; i < contours.Size; i++)
{

Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);

    if (rect.Width > minWidth && rect.Height > minHeight)
    {
        CvInvoke.DrawContours(image, contours, i, new MCvScalar(255, 0, 0), 2);
    }

}

imageBox.Image = image;
zujrkrfu

zujrkrfu1#

主要问题是FindContours找到白色轮廓,图像背景是白色的。
我们使用ThresholdBinaryInv而不是ThresholdBinary
ThresholdBinaryInv应用阈值,并在应用阈值后反转白色(图案将是黑底白字,而不是白底黑字)。
代码示例:

using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using System.Drawing;

namespace Testings
{
    public class Program
    {
        static void Main(string[] args)
        {
            int threshold = 254;
            var image_file_name = @"auxetic_lattice_screen.png";

            Mat image = new Mat(image_file_name, Emgu.CV.CvEnum.ImreadModes.Color);  //Read input image as BGR

            var grayImage = new Image<Gray, System.Byte>(image_file_name); //Read input image as Grayscale

            //grayImage = grayImage.ThresholdBinary(new Gray(threshold), new Gray(255));
            grayImage = grayImage.ThresholdBinaryInv(new Gray(threshold), new Gray(255)); // Use ThresholdBinaryInv - invert black and white so that the pattern be white

            VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
            CvInvoke.FindContours(grayImage, contours, null, RetrType.External, ChainApproxMethod.ChainApproxSimple);

            int minWidth = grayImage.Width / 2;
            int minHeight = grayImage.Height / 2;
            Mat croppedImage = null;

            for (int i = 0; i < contours.Size; i++)
            {
                Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);

                if (rect.Width > minWidth && rect.Height > minHeight)
                {
                    croppedImage = new Mat(image.Clone(), rect); //Crop the rectangle
                    CvInvoke.DrawContours(image, contours, i, new MCvScalar(255, 0, 0), 2);
                }
            }

            

            //Show images for testing
            CvInvoke.Imshow("grayImage", grayImage);
            CvInvoke.Imshow("image", image);
            CvInvoke.WaitKey();

            CvInvoke.Imwrite("output_image.png", image); //Save output for testing
            CvInvoke.Imwrite("croppedImage.png", croppedImage); //Save output for testing            
        }
    }
}

结果:

相关问题