20
20
edged = cv2 .Canny (blurred ,30 ,50 )
21
21
#cv2.imshow("Canny",edged)
22
22
23
- image ,contours ,hierarchy = cv2 .findContours (edged ,cv2 .RETR_LIST ,cv2 .CHAIN_APPROX_NONE )
24
- contours = sorted (contours ,key = cv2 .contourArea ,reverse = True )
23
+ image , contours = cv2 .findContours (edged , cv2 .RETR_EXTERNAL , cv2 .CHAIN_APPROX_SIMPLE )
25
24
26
- for c in contours :
27
- p = cv2 .arcLength (c ,True )
28
- approx = cv2 .approxPolyDP (c ,0.02 * p ,True )
25
+ print (f"Total number of contours found: { len (contours )} " )
29
26
27
+ valid_contours = []
28
+ for i , c in enumerate (contours ):
29
+ print (f"Examining contour { i } " )
30
+
31
+ # Check if the contour has any points
32
+ if len (c ) == 0 :
33
+ print (f"Contour { i } is empty" )
34
+ continue
35
+
36
+ # Try to calculate the area
37
+ try :
38
+ area = cv2 .contourArea (c )
39
+ print (f"Contour { i } area: { area } " )
40
+
41
+ # Check if the area is valid
42
+ if area > 10000 : # Adjust this threshold as needed
43
+ valid_contours .append ((area , c ))
44
+ else :
45
+ print (f"Contour { i } has too small area" )
46
+ except cv2 .error as e :
47
+ print (f"Error calculating area for contour { i } : { e } " )
48
+
49
+ print (f"Number of valid contours found: { len (valid_contours )} " )
50
+ contours = sorted (valid_contours , key = lambda x : x [0 ], reverse = True )
51
+
52
+ if len (contours ) > 0 :
53
+ # Get the largest contour
54
+ _ , largest_contour = contours [0 ]
55
+
56
+ # Approximate the polygon
57
+ p = cv2 .arcLength (largest_contour ,True )
58
+ approx = cv2 .approxPolyDP (largest_contour ,0.02 * p ,True )
59
+
60
+ # Check if it's a quadrilateral
30
61
if len (approx ) == 4 :
31
62
target = approx
32
- break
33
- approx = mapper .mapp (target )
63
+ print ("Found a quadrilateral contour" )
64
+
65
+ # Apply perspective transform
66
+ approx = mapper .mapp (target )
67
+ pts = np .float32 ([[0 ,0 ],[800 ,0 ],[800 ,800 ],[0 ,800 ]])
68
+ op = cv2 .getPerspectiveTransform (approx ,pts )
69
+ dst = cv2 .warpPerspective (orig ,op ,(800 ,800 ))
70
+ cv2 .imshow ("Scanned final" ,dst )
71
+ else :
72
+ print (f"Found contour with { len (approx )} sides" )
73
+ else :
74
+ print ("No valid contours found" )
34
75
35
- pts = np .float32 ([[0 ,0 ],[800 ,0 ],[800 ,800 ],[0 ,800 ]])
36
- op = cv2 .getPerspectiveTransform (approx ,pts )
37
- dst = cv2 .warpPerspective (orig ,op ,(800 ,800 ))
38
- cv2 .imshow ("Scanned final" ,dst )
76
+ cv2 .waitKey (0 )
77
+ cv2 .destroyAllWindows ()
0 commit comments