opencv形状匹配(cv2.matchShape)

"""
21.4.3-形状匹配.py:
函数 cv2.matchShape() 可以帮我们比 两个形状或 廓的相似度。
如果返回值越小, 匹配越好。它是根据 Hu 矩来计算的。
#Hu 矩是归一化中心矩的线性组合
# 之所以这样做是为了能够获取 代表图像的某个特征的矩函数
# 这些矩函数对某些变化如缩放 ,旋转,镜像映射( 除了 h1)具有不变形。
"""
import cv2
import numpy as np
img1 = cv2.imread('hh.png', 0)
img=img1.copy()

ret, thresh = cv2.threshold(img1, 127, 255, 0)

contours, hierarchy = cv2.findContours(thresh, 2, 1)

area=[]
for k in range(len(contours)):
    area.append(cv2.contourArea(contours[k]))
##排序后返回原来的位置
area=np.argsort(area)

#绘制轮廓
cv2.drawContours(img1,contours[area[-1]],-1,(255,0,0),3)
cv2.drawContours(img1,contours[area[-2]],-1,(0,255,0),3)
cv2.drawContours(img1,contours[area[-3]],-1,(0,0,255),3)
#绘制轮廓的边界矩形
x,y,w,h=cv2.boundingRect(contours[area[-1]])
print('轮廓1',cv2.contourArea(contours[area[-1]]))
img1=cv2.rectangle(img1,(x,y),(x+w,y+h),(255,25,99),2)
cv2.imshow('img1',img1)
x,y,w,h=cv2.boundingRect(contours[area[-2]])
print('轮廓2',cv2.contourArea(contours[area[-2]]))
img1=cv2.rectangle(img1,(x,y),(x+w,y+h),(220,255,255),2)
cv2.imshow('img2',img1)
x,y,w,h=cv2.boundingRect(contours[area[-3]])
print('轮廓3',cv2.contourArea(contours[area[-3]]))
img1=cv2.rectangle(img1,(x,y),(x+w,y+h),(255,25,255),2)
cv2.imshow('img3',img1)
print('轮廓的个数',len(contours))
print('轮廓1和轮廓1',cv2.matchShapes(contours[area[-1]], contours[area[-1]], 1, 0.0))
print('轮廓1和轮廓2',cv2.matchShapes(contours[area[-1]], contours[area[-2]], 1, 0.0))
print('轮廓1和轮廓3',cv2.matchShapes(contours[area[-1]], contours[area[-3]], 1, 0.0))
# cv2.imshow('img4',img1)
# cv2.imshow('img5',img)
cv2.waitKey()

 

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一壶浊酒..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值