'find closed contour for sample image using opencv

I am having problem in finding closed contour box for my image:

Input Image

My problem is I have to create rectangle around brown box so as to perform operation only on box. (here, the box is just an example. It can be of different color with different background).

I am currently using Canny for edge detection and cv2.findContour for contour box detection, although it's pretty close for height but for width contours from background creating mess and adding into the width as can be seen below:

Target Image

Below is the code I wrote for this:

            import cv2
            import imutils

            img = cv2.imread(img)
            image = imutils.resize(img, width=600)
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            edged = cv2.Canny(gray, 15, 200,True)
            edged = cv2.dilate(edged, None, iterations=2)
            edged = cv2.erode(edged, None, iterations=2)
            
            edged = 255-edged
            cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            cnts = cnts[0] if imutils.is_cv2() else cnts[1]
            
            for c in cnts:
                # if the contour is not sufficiently large, ignore it
                if cv2.contourArea(c) < 300:
                    continue
                orig = image.copy()
                
                x,y,w,h = cv2.boundingRect(c)
                cv2.rectangle(orig,(x,y),(x+w,y+h),(0,255,255),2)
                cv2.drawContours(orig, c, -1, (255, 255, 0), 3)
                
                # show the output image
                cv2.imshow("Image", orig)
                cv2.waitKey(0)

Is there any other approach I can follow which is easy like above or modify some part to achieve my task to create rectangle around box?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source