圆形、矩形和三角形的识别与定位
import cv2 from scipy import * import queue #读入图像 img=cv2.imread(r'C:\Users\Jimmy\Desktop\wwww.png') gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) img_Guassian = cv2.GaussianBlur(gray,(5,5),0) thresh2 = cv2.adaptiveThreshold(img_Guassian, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2) def cfs(img): """传入二值化后的图片进行连通域分割""" w,h = img.shape visited = set() q = queue.Queue() offset = [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)] cnts = [] for x in range(w): for y in range(h): x_axis = [] y_axis = [] if img[x,y] == 0 and (x,y) not in visited: q.put((x,y)) visited.add((x,y)) while not q.empty(): x_p,y_p = q.get() for x_offset,y_offset in offset: x_c,y_c = x_p+x_offset,y_p+y_offset if (x_c,y_c) in visited: continue visited.add((x_c,y_c)) try: if img[x_c,y_c] == 0: q.put((x_c,y_c)) x_axis.append(x_c) y_axis.append(y_c) except: pass if x_axis and y_axis: min_x,max_x = min(x_axis),max(x_axis) min_y, max_y = min(y_axis), max(y_axis) if max_x - min_x > 2 and max_y - min_y > 2: # 宽度小于3的认为是噪点,根据需要修改 cnts.append((min_x,max_x,min_y, max_y )) return cnts def judge(img,cnts): num = 0 label=[] #存放标签 for i in range(len(cnts)): # temp1 = img[cnts[i][0] - 10:cnts[i][1] + 10, cnts[i][2] - 10:cnts[i][3] + 10] # 彩色图 四个点的顺序是左,上。右下 temp = thresh2[cnts[i][0] - 10:cnts[i][1] + 10, cnts[i][2] - 10:cnts[i][3] + 10] # 二值图 a = int((cnts[i][0] + cnts[i][1]) / 2) b = int((cnts[i][2] + cnts[i][3]) / 2) img[a - 3:a + 3, b - 3:b + 3] = [0, 0, 0] # 把中心标黑 image, cons, hierachy = cv2.findContours(temp, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # img=cv2.drawContours(img,cons,1,(0,255,0),2) #在目标二值图上寻找边缘 x, y, w, h = cv2.boundingRect(cons[1]) # print(x,y,w,h) # img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1) goal = [] ding = [] # 2/3处穿线 for j in range(w): if temp[int(x + h / 2)][y + j] == 0: goal.append(y + j) if temp[int(x + (2 / 3) * h)][y + j] == 0: ding.append(y + j) A = max(goal) - min(goal) B = max(ding) - min(ding) temp[int(x + h / 2)][int(y + w / 2)] = 0 # 标黑 if abs(A - w) > 0.1 * w: # cv2.putText(img,"triangle",(a,b),1,(255,255,255),1) # print("第" + str(num) + "个目标为三角形") label.append(0) elif abs(B - w) > 0.08 * w: label.append(1) else: label.append(2) num += 1 return label cnts=cfs(thresh2) print(cnts) label= judge(img,cnts) print(label) # img=edages(img,thresh2) cv2.imshow('img',img) cv2.waitKey(0)
根据边界矩形的宽、目标中心线、目标1/3线之间的关系,判断图形。