opencv 判断点在多边形内外
????????基于Python 和 OpenCV 畫出多邊形,以及判斷某個點是不是在多邊形內。
1、cv2.pointPolygonTest() 函數
????????函數定義:cv2.pointPolygonTest(contour, pt, measureDist)
????????函數功能:找到圖像里的點和輪廓之間的最短距離. 它返回的距離當點在輪廓外的時候是負值,當點在輪廓內是正值,如果在輪廓上是0。
????????其中,contour 為輪廓多邊形;pt 為坐標點;measureDist, 若為True,是找帶符號的距離;若為False,會找點是否在內,外,或輪廓上(相應返回+1, -1, 0)。
測試用例:
import cv2mask = cv2.imread(r"mask.jpg", 0) mask[mask > 100] = 255 mask[mask != 255] = 0cnts, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) print("mask info:", mask.shape, len(cnts))pt0 = (131, 104) # 外點, 紅色 pt1 = (166, 157) # 輪廓上的點 pt2 = (260, 170) # 內點 img = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) img = cv2.circle(img, pt0, 2, (0, 0, 255), 2) # 紅色 img = cv2.circle(img, pt1, 2, (0, 255, 0), 2) # 綠色 img = cv2.circle(img, pt2, 2, (255, 0, 0), 2) # 藍色dst0 = cv2.pointPolygonTest(cnts[0], pt0, 1) dst1 = cv2.pointPolygonTest(cnts[0], pt1, 1) dst2 = cv2.pointPolygonTest(cnts[0], pt2, 1) print("dst:", dst0, dst1, dst2) cv2.imwrite(r"ret.jpg", img)測試結果:
dst: -58.52 2.82 44.28圖像:
2、cv2.polylines() 函數
函數定義:img = cv2.polylines(img, pts, isClosed, color, thickness, lineType, shift)
其中:
????????pts 是多邊形定點構成的矩陣,將傳入的點一次連接。
????????isClosed - 表示繪制的多邊形是否閉合. 如閉合(True),則每個曲線的最后一個頂點到第一個頂點是連接的,若不閉合(False),則多邊形就不閉合。
示例代碼:
import cv2 import numpy as np# 純白圖像 img = np.zeros((500, 500, 3), np.uint8) img[:] = [255, 255, 255]# 四個頂點坐標 pts = np.array([[100, 100], [200, 20], [370, 6], [450, 200]], np.int32) # 頂點個數:4,矩陣變成4*1*2維 pts = pts.reshape((-1, 1, 2)) # (4,1,2) cv2.polylines(img, [pts], isClosed=True, color=(0, 0, 255), thickness=3) cv2.imwrite(r"a.jpg", img)結果:
3、關鍵代碼
# 四個頂點坐標 pts = np.array([[100, 100], [200, 20], [370, 6], [450, 200]], np.int32)# 頂點個數:4,矩陣變成4*1*2維 pts = pts.reshape((-1, 1, 2)) # (4,1,2)# 畫多邊形 img = cv2.polylines(img, [pts], isClosed=True, color=(0, 0, 255), thickness=3)# 測試點與多邊形的距離 dist = cv2.pointPolygonTest(pts, (307, 100), True)擴展閱讀:
1、opencv python 輪廓/凸缺陷/PointPolygonTest/形狀匹配
opencv python 輪廓/凸缺陷/PointPolygonTest/形狀匹配 - SegmentFault 思否
????????形狀匹配:
????????OpenCV附帶了一個函數cv2.matchShapes(),它使我們能夠比較兩個形狀或兩個輪廓,并返回一個顯示相似性的度量。 結果越低,匹配就越好.它是根據hu-moment值計算的。
????????ret = cv2.matchShapes(cnt1,cnt2,1,0.0)
2、比好好的opencv專欄
https://blog.csdn.net/kakiebu/category_7398390.html
總結
以上是生活随笔為你收集整理的opencv 判断点在多边形内外的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 统计检验问题:Friedman Test
- 下一篇: 如何利用语音评测技术设计英语口语选择题