python opencv 轮廓:更多函数

import numpy as np
import cv2

im = cv2.imread('zhua.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,100,255,0)#findContours函数修改原图
#cv2.findContours()函数的三个参数,第一个是原图,第二个是轮廓获取方式,第三个是轮廓近似方法。
img, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
img=cv2.drawContours(img,contours,-1,(0,255,0),3)

cnt = contours[-1]

# cv2.imshow('image2',img)
# cv2.waitKey(0)
cv2.destroyAllWindows()
# 凸面缺陷
hull = cv2.convexHull(cnt,returnPoints=False)#我们要传returnPoints = False来找凸形外壳。
defects = cv2.convexityDefects(cnt,hull)
# 它返回了一个数组,每行包含这些值:[start point, end point, farthest point, approximate distance to farthest point].
# 记住最前三个返回值是cnt的索引
print(defects[0,0,0])
203
import cv2
import numpy as np

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

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
# 这个函数找到图像里的点和轮廓之间的最短距离。它返回的距离当点在轮廓外的时候是负值,当点在轮廓内是正值,如果在轮廓上是0
# 比如,我们可以检查(50, 50)这个点

dist=cv2.pointPolygonTest(cnt,(500,500),True)
#第三个参数是measureDist, 如果为True,是找带符号的距离。如果为False,会找点是否在内,外,或轮廓上(会相应返回+1, -1, 0)
print(dist)
-238.9016534057477
# 匹配形状
# cv2.matchShapes()来让我们可以比较两个形状,或者两个轮廓来返回一个量表示相似度。结果越低,越相似,它是根据hu矩来计算的

import cv2
import numpy as np

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

ret, thresh = cv2.threshold(img1, 100, 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)

0.06213205685249473
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值