Python opencv學習-10尋找凸缺陷,輸出輪廓形狀匹配度
阿新 • • 發佈:2021-02-03
技術標籤:Python OpenCV 影象學習-21年opencvpython
# 凸缺陷和輪廓形狀匹配 import cv2 import numpy as np img = cv2.imread('image/five.jpg') img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(img_gray, 140, 255, 0) im, contours, hierarchy = cv2.findContours(thresh, 2, 1) print(len(contours)) img = cv2.drawContours(img, contours, 1, (0, 255, 0), 3) # cv2.imshow('im', img) cnt = contours[1] # 注意隨著圖片的改變要檢測的輪廓序號也會發生變化,在本圖輪廓序號和二值化相關(閾值) hull = cv2.convexHull(cnt, returnPoints=False) # 注意引數 defects = cv2.convexityDefects(cnt, hull) print(defects) 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) # 計算輸出兩個輪廓的相似度-----輪廓形狀匹配 # ret值越小,越匹配 cnt1 = contours[0] cnt2 = contours[1] ret = cv2.matchShapes(cnt1, cnt2, 1, 0.0) print(ret) cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows()