Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.19 KB | None | 0 0
  1. def angle_cos(p0, p1, p2):
  2.     d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
  3.     return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
  4.  
  5. def getCircles(img):#TEST THIS FUNCTION
  6. gray= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  7. circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1.2, 100)
  8. return circles
  9.  
  10.  
  11.  
  12.  
  13.  
  14. def getSquares(img, num_angles=4, MinContourAre=1000):
  15.     img = cv2.GaussianBlur(img, (5, 5), 0)
  16.     squares = []
  17.     for gray in cv2.split(img):
  18.         for thrs in range(0, 255, 26):
  19.             if thrs == 0:
  20.                 bin = cv2.Canny(gray, 0, 50, apertureSize=5)
  21.                 bin = cv2.dilate(bin, None)
  22.             else:
  23.                 _retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
  24.             bin, contours, _hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  25.             for cnt in contours:
  26.                 cnt_len = cv2.arcLength(cnt, True)
  27.                 cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
  28.                 if len(cnt) == num_angles and cv2.contourArea(cnt) > MinContourArea and cv2.isContourConvex(cnt):
  29.                     cnt = cnt.reshape(-1, 2)
  30.                     max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in range(4)])
  31.                     if max_cos < 0.1:
  32.                         squares.append(cnt)
  33.     return squares
  34. def getTriangles(img):#TEST THIS FUNCTION
  35. return getSquares(img,3)
  36.  
  37.  
  38. import os
  39. IMAGE_SHAPE=(360,640,3)
  40. os.chdir('C:\\Users\\user\\Downloads\\fromcamera')
  41.  
  42. import cv2
  43. import numpy as np
  44. from copy import deepcopy
  45. ##[:,:,::-1] надо, чтобы на первом месте был красный, на втором зеленый и на третьем синий
  46. yellow_square = cv2.imread('yellow.jpg')[:,:,::-1]
  47. green_square = cv2.imread('green.jpg')[:,:,::-1]
  48. yellow_triangle = cv2.imread('yellowtriangle.jpg')[:,:,::-1]
  49. green_triangle = cv2.imread('greentriangle.jpg')[:,:,::-1]
  50. yellow_circle = cv2.imread('yellowcircle.jpg')[:,:,::-1]
  51. red_circle = cv2.imread('redcircle.jpg')[:,:,::-1]
  52. green_circle = cv2.imread('greencircle.jpg')[:,:,::-1]
  53.  
  54. def inRange(image, color):
  55.     threshs = [cv2.inRange(image[:,:,i], color[0][i], color[1][i]).astype(bool) for i in range(3)]
  56.     mask = np.logical_and(threshs[0],threshs[1], threshs[2])
  57.     return mask
  58. def getRedboxCentre (image,color,image_name='gg.jpg',mask_color=[0,0,255],min_d_area=10):
  59. mask = inRange(image, color)
  60.     if mask.sum()>min_d_area:
  61.         print('Mask is found - area is '+str(mask.sum()))
  62.         cv2.imwrite('mask_'+image_name,255*mask.astype(int))
  63.         image1 = deepcopy(image)
  64.         image1[mask]=mask_color
  65.         cv2.imwrite(image_name, image)    
  66.     return 0
  67.  
  68. red_colormin =(95,20,20)
  69. red_colormax=(110,33,33)
  70. yellow_colormin=(125,135,75)
  71. yellow_colormax=(145,155,95)
  72. green_colormin=(13,57,57)
  73. green_colormax=(35,85,85)
  74. colors = [(red_colormin,red_colormax),(yellow_colormin,yellow_colormax),(green_colormin,green_colormax)]
  75. color_names=['red','yellow','green']
  76. red_images,red_names=[red_circle],['redcircle']#We consider brown-red color used to be some sort of ted
  77. yellow_images,yellow_names = [yellow_circle, yellow_triangle, yellow_square],['yellowcircle','yellowtriangle','yellowsquare']
  78. green_images, green_names=[green_circle, green_triangle, green_square],['greencircle','greentriangle','greensquare']
  79. data_struct=[[red_images,red_names],[yellow_images, yellow_names],[green_images,green_names]]
  80.  
  81.  
  82. def isPinRectangle(r, P): """ r: A list of four points, each has a x- and a y- coordinate P: A point """
  83. areaRectangle = 0.5*abs( # y_A y_C x_D x_B (r[0][1]-r[2][1])*(r[3][0]-r[1][0])
  84. # y_B y_D x_A x_C + (r[1][1]-r[3][1])*(r[0][0]-r[2][0]) )
  85. ABP = 0.5*( r[0][0]*(r[1][1]-r[2][1]) +r[1][0]*(r[2][1]-r[0][1]) +r[2][0]*(r[0][1]-r[1][1]) )
  86. BCP = 0.5*( r[1][0]*(r[2][1]-r[3][1]) +r[2][0]*(r[3][1]-r[1][1]) +r[3][0]*(r[1][1]-r[2][1]) )
  87. CDP = 0.5*( r[2][0]*(r[3][1]-r[0][1]) +r[3][0]*(r[0][1]-r[2][1]) +r[0][0]*(r[2][1]-r[3][1]) )
  88. DAP = 0.5*( r[3][0]*(r[0][1]-r[1][1]) +r[0][0]*(r[1][1]-r[3][1]) +r[1][0]*(r[3][1]-r[0][1]) )
  89. return areaRectangle == (ABP+BCP+CDP+DAP)
  90.  
  91. def is_into(point, contour, type_name):
  92. if type_name=='circle':
  93. (x,y,r)= contour
  94. cond = (point[0]-x)**2 +(point[1]-y)**2 < r**2)
  95. return cond
  96. elif type_name=='rectangle' or type_name=='triangle):
  97. val= cv2.pointPolygonTest(contour, point)
  98. return val==1
  99. #MAKE CONDITION FOR RECTANGLE
  100. else:
  101. raise Exception("Unknown type")
  102.  
  103.  
  104.  
  105.  
  106. #MAKE CONDITION FOR TRIANGLE
  107. else:
  108. raise Exception('Unknown type')
  109. pass
  110. def get_percent(contour, mask, type_name):
  111. total, match=0.0,0.0
  112. for i in range(IMAGE_SHAPE[0]):
  113. for j in range(IMAGE_SHAPE[1]):
  114. if is_into ((i,j), contour, type_name):
  115. total+=1
  116. if mask[i][j]:
  117. match+=1
  118. if total==0:
  119. return 0
  120. else:
  121. return match/total
  122. import itertools
  123. data={}
  124. for (images,names) in data_struct:
  125.     for (image,name) in zip(images,names):
  126. circle_contours = getCircles(image)
  127. rectangle_contours = getRectangles(image)
  128. triangle_contours = getTriangles(image)
  129. mask_list, mask_names = [ inRange(image, color) for color in colors], colors
  130. contour_list, contour_names=(
  131. [circle_contours, rectangle_contours, triangle_contours],['circle','rectangle','triangle'])
  132.  
  133. for contours, contour_name in zip(contour_list, contour_names):
  134. for mask, mask_name in zip(mask_list, mask_names):
  135. total_name = '_'.join(contour_name,mask_name,name)
  136. percents = [get_percent(contour, mask, total_name) for contour in contours]
  137. max_percent, final_contour= max(percents), contours[np.argmax(percents)]
  138. data[total_name]=(max_percent, final_contour,image)
  139.  
  140. ###filter data
  141. MIN_MATCH=0.8
  142. FILL_COLOR=[0,255,255]
  143. for key in range(data.keys():
  144. image=data[key][2]
  145. contour=data[key][1]
  146. if data[key][0]<MIN_MATCH:
  147. del data[key]
  148. else:
  149. mode = key.split('_')[0]
  150. save_name ='_'.join(key)+'.jpg'
  151. image1=deepcopy(image)
  152. for i,j in itertools.product(IMAGE_SHAPE[0],IMAGE_SHAPE[1]):
  153. if is_into((i,j), contour,mode):
  154. image1[i,j]=FILL_COLOR
  155. cv2.imwrite(save_name, image1)
  156.  
  157.  
  158.  
  159. def filter_squares(img):
  160.  
  161.     for square in squares:
  162.  
  163.         x_min = min([j[0] for j in squares])
  164.  
  165.         x_max = max([j[0] for j in squares])
  166.  
  167.         y_min = min([j[1] for j in squares])
  168.  
  169.         y_max = max(j[1] for j in squares)
  170.  
  171. squares = find_squares(yellow_square)
  172.  
  173. cv2.drawContours( yellow_square, squares, -1, (0, 255, 0), 1 )
  174.  
  175. cv2.imwrite('tmp2.jpg',yellow_square)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement