【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)
推荐阅读
- 人脸识别|【人脸识别系列】| 实现自动化妆
- 推荐系统论文进阶|CTR预估 论文精读(十一)--Deep Interest Evolution Network(DIEN)
- Python专栏|数据分析的常规流程
- Python|Win10下 Python开发环境搭建(PyCharm + Anaconda) && 环境变量配置 && 常用工具安装配置
- Python绘制小红花
- Pytorch学习|sklearn-SVM 模型保存、交叉验证与网格搜索
- OpenCV|OpenCV-Python实战(18)——深度学习简介与入门示例
- python|8. 文件系统——文件的删除、移动、复制过程以及链接文件
- 爬虫|若想拿下爬虫大单,怎能不会逆向爬虫,价值过万的逆向爬虫教程限时分享
- 分布式|《Python3网络爬虫开发实战(第二版)》内容介绍