10 hough su canny, plotto le hough lines su un'immagine bianca, applico la funzione cv2.findContours con retrieval_mode = external per trovare i contorni esterni. Se i contorni esterni sono più di 1, devo riapplicare la hough aumentando la threshold, in modo da rendere unico il contorno esterno.
12 hough_contorni = cv2.HoughLinesP(edges_canny,1,np.pi/180,threshold=t,minLineLength=1,maxLineGap=m)
13 if cv2.__version__[0] ==
'3' :
14 hough_contorni = [i[0]
for i
in hough_contorni]
15 elif cv2.__version__[0] ==
'2' :
16 hough_contorni = hough_contorni[0]
18 raise EnvironmentError(
'Opencv Version Error. You should have OpenCv 2.* or 3.*')
21 img4 = cv2.imread(file_name,0)
22 ret,bianca = cv2.threshold(img4,255,255,cv2.THRESH_BINARY_INV)
23 bianca2 = bianca.copy()
25 for x1,y1,x2,y2
in hough_contorni:
26 cv2.line(bianca2,(x1,y1),(x2,y2),(0,0,0),2)
28 ret,bianca2 = cv2.threshold(bianca2,253,255,cv2.THRESH_BINARY_INV)
29 if cv2.__version__[0] ==
'3' :
30 img_copy, contours, hierarchy = cv2.findContours(image = bianca2.copy(), mode = cv2.RETR_EXTERNAL, method = cv2.CHAIN_APPROX_SIMPLE)
31 elif cv2.__version__[0] ==
'2' :
33 contours, hierarchy = cv2.findContours(bianca2.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
35 raise EnvironmentError(
'Opencv Version Error. You should have OpenCv 2.* or 3.*')
37 while(len(contours)!=1):
41 hough_contorni = cv2.HoughLinesP(edges_canny,1,np.pi/180,threshold=t,minLineLength=1,maxLineGap=m)
42 if cv2.__version__[0] ==
'3' :
43 hough_contorni = [i[0]
for i
in hough_contorni]
44 elif cv2.__version__[0] ==
'2' :
45 hough_contorni = hough_contorni[0]
47 raise EnvironmentError(
'Opencv Version Error. You should have OpenCv 2.* or 3.*')
49 bianca2 = bianca.copy()
50 for x1,y1,x2,y2
in hough_contorni:
51 cv2.line(bianca2,(x1,y1),(x2,y2),(0,0,0),2)
52 ret,bianca2 = cv2.threshold(bianca2,253,255,cv2.THRESH_BINARY_INV)
55 if cv2.__version__[0] ==
'3' :
56 img_copy, contours, hierarchy = cv2.findContours(image = bianca2.copy(), mode = cv2.RETR_EXTERNAL, method = cv2.CHAIN_APPROX_SIMPLE)
57 elif cv2.__version__[0] ==
'2' :
59 contours, hierarchy = cv2.findContours(bianca2.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
61 raise EnvironmentError(
'Opencv Version Error. You should have OpenCv 2.* or 3.*')
62 return (hough_contorni,contours)