OpenCV – cv2.pointPolygonTest でポリゴンの中に点が含まれるかどうか調べる

概要
OpenCV の cv2.pointPolygonTest() を使用して、点がポリゴンに含まれるかどうかを判定する方法を紹介します。
Advertisement
cv2.pointPolygonTest
retval = cv2.pointPolygonTest(contour, pt, measureDist)
引数
名前 | 型 | デフォルト値 |
---|---|---|
contour | ndarray | |
ポリゴンを表す点の一覧 | ||
pt | tuple of 2 ints | |
点 | ||
measureDist | bool | |
* measureDist=False の場合、点が輪郭の内側の場合は +1、輪郭の境界線上の場合は 0、輪郭の外側の場合は -1 を返す。 * measureDist=True の場合、点と輪郭との距離を返す。点が輪郭の内側の場合は正の値、輪郭の境界線上の場合は 0、輪郭の外側の場合は負の値を返す。 |
返り値
名前 | 説明 | ||
---|---|---|---|
int | ポリゴンの中に点が含まれるかどうか (measureDist の説明参照) |
In [1]:
import cv2
import numpy as np
from matplotlib import pyplot as plt
# ポリゴン
polygon = np.array([[170, 113], [167, 57], [259, 50], [259, 105]])
# 点
points = [(100, 100), (250, 70), (170, 113), (259, 250)]
# 描画する。
fig, ax = plt.subplots()
ax.set_xlim([0, 300])
ax.set_ylim([0, 300])
ax.set_aspect("equal")
ax.add_patch(plt.Polygon(polygon, fill=False))
for i, pt in enumerate(points):
# 点 pt がポリゴン polygon に含まれるかどうか判定する。
color = "green" if cv2.pointPolygonTest(polygon, pt, False) >= 0 else "gray"
ax.scatter(pt[:1], pt[1:], color=color)
ax.text(*pt, "({}, {})".format(*pt), fontsize=12)
plt.show()

-
前の記事
OpenCV – 物体検出で使われる Non Maximum Suppression について 2020.09.05
-
次の記事
OpenCV – 画像に透かし文字 (watermark) を入れる方法 2020.09.11