Click here to Skip to main content
15,298,794 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
We are performing Auto Crop operations using OpenCV library in C# project, For few sample automatically cropping the image but for other samples images are not cropped.

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.FindContours(CannyImage, out contours, out hierarchy,RetrievalModes.External, ContourApproximationModes.ApproxSimple);


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);

What I have tried:

Tried finding the bounding box from contours
Updated 4-Jan-22 23:48pm

1 solution

A clear case for the debugger, because it is some special situation. So use the tool with some test data.
I think your fix coordinates in the code can be a problem when using different image sizes.
Also read the OpenCV documentation for limitations on image formats.

tip: saving to a fix path is problematic.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900