十五天掌握OpenCV——轮廓相关函数

魏老师学生——Cecil:学习OpenCV-机器视觉之旅

凸缺陷

  1. 凸缺陷:对象上的凹陷。
  2. hull=cv2.convexHull(cnt,returnPoints=False) ——解释:找凸包。
  3. defects=cv2.convexityDefects(cnt,hull) ——解释:返回数组,每一行包含(起点,终点,最远点,到最远点的近似距离)。

代码演示

#coding=utf8
import cv2
import numpy as np

img=cv2.imread('123.jpg')
img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh=cv2.threshold(img_gray,127,255,0)
contours,hierarchy=cv2.findContours(thresh,2,1)
cnt=contours[0]

hull=cv2.convexHull(cnt,returnPoints=False)
defects=cv2.convexityDefects(cnt,hull)

for i in range(defects.shape[0]):
    s,e,f,d=defects[i,0]
    start=tuple(cnt[s][0])
    end=tuple(cnt[e][0])
    far=tuple(cnt[f][0])
    cv2.line(img,start,end,[0,255,0],2)
    cv2.circle(img,far,5,[0,0,255],-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Point Polygon Test

  1. 点到多边形最短距离。点在轮廓内,返回值正,轮廓外为负,轮廓上为0。
  2. dist=cv2.pointPolygonTest(cnt,(50,50),True) ——解释:第三参数measureDist。true:返回计算的最短距离。false:返回点与轮廓位置关系。

形状匹配

  1. cv2.matchShape(cnt1,cnt2,1,0,0) ——解释:比较两个形状或轮廓的相似度。根据Hu矩计算。
  2. Hu矩:归一化中心矩的线性组合,可获取代表图像的某个特征的矩函数。

代码演示

#coding=utf8
import cv2
import numpy as np

img1=cv2.imread('juzi.jpg',0)
img2=cv2.imread('juzi.jpg',0)

ret,thresh=cv2.threshold(img1,127,255,0)
ret,thresh2=cv2.threshold(img2,127,255,0)
contours,hierarchy=cv2.findContours(thresh,2,1)
cnt1=contours[0]
contours,hierarchy=cv2.findContours(thresh2,2,1)
cnt2=contours[0]

ret=cv2.matchShapes(cnt1,cnt2,1,0.0)
print(ret)

1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值