OpenCV|基于Python OpenCV的单目标轮廓匹配

【OpenCV|基于Python OpenCV的单目标轮廓匹配】python opencv 实现单目标餐盘轮廓识别

import cv2 import numpy as npdef template(template): temp = cv2.imread(template, 0) # temp_gray = cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY) _, temp_thresh = cv2.threshold(temp, 127, 255, 0) plate_contours, temp_hierarchy = cv2.findContours(temp_thresh, 2, 1) return plate_contours, temp_hierarchydef matchTemp(img): # 模版特征 templates_contours = [] fang_contours, temp_hierarchy = template('./pic/temp_fang1.png') hua_contours, temp_hierarchy = template('./pic/temp_hua.png') circle_contours, temp_hierarchy = template('./pic/temp_circle.png') long_contours, temp_hierarchy = template('./pic/temp_long5.png') templates_contours = [fang_contours[0], hua_contours[0], circle_contours[0]] # print(fang_contours[0]) # templates_contours = sorted(templates_contours, key=lambda x: x[0])# cv2.drawContours(temp, hua_contours, 0, (0, 0, 255), 2)# 花盘子 # cv2.drawContours(temp, fang_contours, 1, (0, 255, 0), 2)# 方盘子# 盘子特征 img = cv2.imread(img) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, img_thresh = cv2.threshold(img_gray, 150, 255, 0) # 腐蚀 >> 膨胀 kernel_1 = np.ones((5, 5), np.uint8) kernel_2 = np.ones((5, 5), np.uint8) img_erosion = cv2.erode(img_thresh, kernel_1, iterations=1) img_dilation = cv2.dilate(img_erosion, kernel_2, iterations=1)img_contours, img_hierarchy = cv2.findContours(img_dilation, 2, 1)img_contours_list = []for img_contour in img_contours: # if cv2.contourArea(img_contour) > 500: img_contours_list.append(img_contours) # 获取最大 img_contour_area = max(img_contours_list) i = img_contours_list.index(img_contour_area)ret1 = cv2.matchShapes(hua_contours[0], img_contours[i], 1, 0) ret2 = cv2.matchShapes(fang_contours[0], img_contours[i], 1, 0) ret3 = cv2.matchShapes(circle_contours[0], img_contours[i], 1, 0) ret4 = cv2.matchShapes(long_contours[0], img_contours[i], 1, 0) print(ret4) ret = min(ret1, ret2, ret3, ret4)if ret > 0.03: # 无匹配 plate_type = "无"else: if ret1 == ret: # 匹配花盘子 plate_type = "花盘子" elif ret2 == ret: # 匹配方盘子 plate_type = "方盘子" elif ret4 == ret: # 匹配方盘子 plate_type = "长盘子" else: plate_type = "圆盘子"return plate_type, retif __name__ == '__main__': plate_type, ret = matchTemp("./pic/fangcai.png") print(plate_type, ret)


    推荐阅读