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

python opencv 实现单目标餐盘轮廓识别 

import cv2
import numpy as np


def 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_hierarchy


def 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, ret


if __name__ == '__main__':
    plate_type, ret = matchTemp("./pic/fangcai.png")
    print(plate_type, ret)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值