I have used Magick.NET to detect all the edges using Canny Edge Detection which basically converts an image to a binary version where the edges are in white and the rest of the image black However I have failed in using the library HoughLine method to detect rectangles or squares on the image. The image however has a very perfect square on it and would like to know which library or algorithm I can use to detect the rectangle on that image, Thank You. Below is my code

//add reference to image magick
using ImageMagick;

//this code is inside a method

//create a new instance of Magick Image
MagickImage image = new MagickImage("image1.jpg");
//detect that the edges on the image
image.CannyEdge();
//Save the image with edges 
image.Write("output.jpg");
//how can I use this library or any other library to detect the rectangle on the image

Here's an example I found on the web. It uses OpenCV and another method. Disclaimer: I don't know if this will work for your images or if it's good enough.

using OpenCvSharp;
using OpenCvSharp.Extensions;

class Program
{
    static void Main(string[] args)
    {
        // Load the image
        Mat img = Cv2.ImRead("image.jpg", ImreadModes.Grayscale);

        // Convert to binary image
        Cv2.Threshold(img, img, 128, 255, ThresholdTypes.Binary);

        // Find the contours
        Point[][] contours;
        HierarchyIndex[] hierarchy;
        Cv2.FindContours(img, out contours, out hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);

        // Iterate through the contours and draw the squares
        for (int i = 0; i < contours.Length; i++)
        {
            Point[] contour = contours[i];
            if (Cv2.IsContourConvex(contour) && contour.Length == 4)
            {
                Cv2.DrawContours(img, contours, i, Scalar.Red, 2);
            }
        }

        // Show the image
        using (new Window("Squares", img.ToBitmap()))
        {
            Cv2.WaitKey();
        }
    }
}

`

commented: Let me try this solution out, I qm assuming you used the latest version of OpenCvSharp. +0

Sorry no. This is code that is untested and just for giving you ideas about possible other solutions.

commented: Okay thanks for the help, I will try other solutions. Chat GPT generates code that does not compile +0

The above code did compile but is untested. What did ChatGPT produce?

commented: let me test it and provide you with feedback +0

Sorry but this is not my code. Random code that I can't do more than throw in Visual Studio 2008 (all I have here) and see what it thought about it.

I wanted to not leave without any ideas so my thought was to explore OpenCV.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.