김태희

add Sign Detection with Gaussian Filter

1 +import cv2
2 +import numpy as np
3 +
4 +def stackImages(scale,imgArray): #calculate convolution
5 + rows = len(imgArray)
6 + cols = len(imgArray[0])
7 + rowsAvailable = isinstance(imgArray[0], list)
8 + width = imgArray[0][0].shape[1]
9 + height = imgArray[0][0].shape[0]
10 + if rowsAvailable:
11 + for x in range ( 0, rows):
12 + for y in range(0, cols):
13 + if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
14 + imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
15 + else:
16 + imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
17 + if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
18 + imageBlank = np.zeros((height, width, 3), np.uint8)
19 + hor = [imageBlank]*rows
20 + hor_con = [imageBlank]*rows
21 + for x in range(0, rows):
22 + hor[x] = np.hstack(imgArray[x])
23 + ver = np.vstack(hor)
24 + else:
25 + for x in range(0, rows):
26 + if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
27 + imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
28 + else:
29 + imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
30 + if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
31 + hor= np.hstack(imgArray)
32 + ver = horx
33 + return ver
34 +
35 +def getContours(img):
36 + contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
37 + for cnt in contours:
38 + area = cv2.contourArea(cnt)
39 + print(area)
40 + if area>500:
41 + cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
42 + peri = cv2.arcLength(cnt,True)
43 + #print(peri)
44 + approx = cv2.approxPolyDP(cnt,0.02*peri,True)
45 + print(len(approx))
46 + objCor = len(approx)
47 + x, y, w, h = cv2.boundingRect(approx)
48 +
49 + if objCor ==3: objectType ="Tri"
50 + elif objCor == 4:
51 + aspRatio = w/float(h)
52 + if aspRatio >0.98 and aspRatio <1.03: objectType= "Square"
53 + else:objectType="Rectangle"
54 + elif objCor>4: objectType= "Circle"
55 + else:objectType="None"
56 +
57 +
58 + cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)
59 + cv2.putText(imgContour,objectType,
60 + (x+(w//2)-10,y+(h//2)-10),cv2.FONT_HERSHEY_COMPLEX,0.7,
61 + (0,0,0),2)
62 +
63 +
64 +path = 'TestPhoto/test08.jpg'
65 +img = cv2.imread(path)
66 +imgContour = img.copy()
67 +
68 +imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
69 +imgBlur = cv2.GaussianBlur(imgGray,(7,7),1) # Gaussian smoothing filter for noise(고주파) reduce
70 +imgCanny = cv2.Canny(imgBlur,50,50)
71 +getContours(imgCanny)
72 +
73 +imgBlank = np.zeros_like(img)
74 +imgStack = stackImages(0.6,([img,imgGray,imgBlur],
75 + [imgCanny,imgContour,imgBlank]))
76 +
77 +cv2.imshow("Stack", imgStack)
78 +
79 +cv2.waitKey(0)