Ask Your Question

Revision history [back]

form a possible rectangle

I have images which have a noisy rectangle. I would like to find the four coordinates of the possible rectangle.

When I try to find using contours, I sometimes get multiple contours and the code fails. Is there any other way to get a rectangle from the image and its top right corner, top left corner, bottom right corner and bottom left corner. I'm enclosing some sample images of my use case.C:\fakepath\0.jpgC:\fakepath\1ccc.jpg(/upfiles/16039708746355454.jpg)C:\fakepath\IMG20200928112428.jpgC:\fakepath\csm_Ref_0057_Congo_RP_Card_1280__45ff38a60c.jpgC:\fakepath\a90e171b-b982-4b46-b637-7fc83d22e945a.pngC:\fakepath\CpV6bz4WIAAiv5na.jpgC:\fakepath\images (4)a.jpgC:\fakepath\images (4)a.jpgC:\fakepath\Tuareg ID Carda.jpgC:\fakepath\card3b.png

code

img=cv2.imread(imgpath,0);

kernel = np.ones((3,3), np.uint8); 

img = cv2.dilate(img, kernel, iterations=3) 

img = cv2.bitwise_not(img);

ret,thresh= cv2.threshold(img,127,255,cv2.THRESH_TOZERO)

edged = cv2.Canny(thresh, 30, 100) 

img_dilation = cv2.dilate(edged, kernel, iterations=1) 

contours, hierarchy = cv2.findContours(img_dilation,  cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

print("Number of Contours found = " + str(len(contours))) 

for contour in contours:

    peri = cv2.arcLength(contour, True)

    corners = cv2.approxPolyDP(contour, 0.05 * peri, True)

    cv2.polylines(img2, [corners], True, (255,255,255), 1, cv2.LINE_AA);

    print(corners,"corners")