rchavezj / OpenCV_Projects

List of OpenCV projects to further increase the computer vision community. Coding in Python & C++(In progress).

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Automatically Cropping image using OpenCV

DeepakHirapur opened this issue · comments

Hi,

We are performing Auto Crop operations using OpenCV library in C# project, For few sample automatically cropping the image but for other samples It was not cropping properly.

Let us know anything is missing in source code.

Please find the below piece of code.

        `Mat image = new Mat();
        Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();
        Nullable<bool> result = openFileDlg.ShowDialog();
        if (result == true)
        {
            image = Cv2.ImRead(openFileDlg.FileName);
        }
        
        Mat GrayImage = new Mat();
        Cv2.CvtColor(image, GrayImage, ColorConversionCodes.BGR2GRAY);

        Mat BlurImage = new Mat();
        Cv2.GaussianBlur(GrayImage,BlurImage, new OpenCvSharp.Size(5,5),0);

        Mat CannyImage = new Mat();
        OpenCvSharp.Point[][] contours;
        HierarchyIndex[] hierarchy;
        Cv2.Canny(BlurImage, CannyImage, 80, 150,7);

        Cv2.ImShow("Original Image", image);
        Cv2.ImShow("Canny Edged Image", CannyImage);
        Cv2.DestroyAllWindows();
       
        Cv2.FindContours(CannyImage, out contours, out hierarchy,RetrievalModes.External, ContourApproximationModes.ApproxSimple);

        image.SaveImage(@"C:\Users\TestAccount\Documents\AutoCrop_OpenCV\Output03012022\20220103.jpeg");

        var contourIndex = 0;
        var previousArea = 0;
        var biggestContourRect = Cv2.BoundingRect(contours[0]);
        while ((contourIndex >= 0))
        {
            var contour = contours[contourIndex];

            var boundingRect = Cv2.BoundingRect(contour); //Find bounding rect for each contour
            var boundingRectArea = boundingRect.Width * boundingRect.Height;
            if (boundingRectArea > previousArea)
            {
                biggestContourRect = boundingRect;
                previousArea = boundingRectArea;
            }
            
            contourIndex = hierarchy[contourIndex].Next;
        }
        

        var finalImage = new Mat(image, biggestContourRect); //Crop the image
        string outputBaseDirectory = @"C:\Users\TestAccount\Documents\AutoCrop_OpenCV\Output03012022";
        finalImage.SaveImage(string.Format("{0}{1}{2}", outputBaseDirectory, "\\Output", System.IO.Path.GetFileName(openFileDlg.FileName)));
        Cv2.ImShow("Final Image", finalImage);`