Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Contour Approximation OpenCV

I am using opencv for python. For a bad shape, we use approxpolyDP().For this, I created a bad rectangle(added to the post)

While using this, I only get 2 dots and not a proper rectangle.

Can anyone help me why this is happening?

import cv2
import numpy as np

im = cv2.imread("badrect.png")
img = im
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(img,100,200)


(_,cnts,_) = cv2.findContours(canny,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

cnt = cnts[0]

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)

cv2.drawContours(im,approx,-1,(0,255,0),3)

cv2.imshow("img",im)
cv2.waitKey(0)
cv2.destroyAllWindows()

This is how the output comes out as

This is how the output comes out as

This is my desired result This is my desired result!

click to hide/show revision 2
retagged

Contour Approximation OpenCV

I am using opencv for python. For a bad shape, we use approxpolyDP().For this, I created a bad rectangle(added to the post)

While using this, I only get 2 dots and not a proper rectangle.

Can anyone help me why this is happening?

import cv2
import numpy as np

im = cv2.imread("badrect.png")
img = im
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(img,100,200)


(_,cnts,_) = cv2.findContours(canny,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

cnt = cnts[0]

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)

cv2.drawContours(im,approx,-1,(0,255,0),3)

cv2.imshow("img",im)
cv2.waitKey(0)
cv2.destroyAllWindows()

This is how the output comes out as

This is how the output comes out as

This is my desired result This is my desired result!