'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 result looks like

Bad rectangle

This is how I want it to come as

desired output

Thanks in advance! :)



Solution 1:[1]

The problems are as following:

(1) image is so bad that I have to decrease the arcLength()*0.08 instead of arcLength()*0.1;

(2) you have confuse of im and img, be careful.

import cv2
import numpy as np
from matplotlib import pyplot as plt
    
path = "/Users/summing/Desktop/skM2L.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
(ret, thresh) = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
edge = cv2.Canny(thresh, 100, 200)
(cnts, _) = cv2.findContours(edge.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    
total = 0
for c in cnts:
    epsilon = 0.08 * cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, epsilon, True)

    cv2.drawContours(img, [approx], -1, (0, 255, 0), 4)
    total += 1

print "I found {0} RET in that image".format(total)
cv2.imshow("Output", img)
cv2.waitKey(0)
exit()

And the code work find for me. Hope it help. Here is the result:

result.

Solution 2:[2]

Use approx as array. I hope this helps.

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

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Jeru Luke
Solution 2 Hamiz Ahmed