phthon opencv 坐标点内
如果你想检查一个点是否在OpenCV中某个区域内,你可以使用cv2.pointPolygonTest函数。这个函数会判断一个点是在区域内(返回+1)、在区域外(返回-1),还是在区域边界上(返回0)。
以下是一个使用cv2.pointPolygonTest的例子:
import cv2
import numpy as np
from PIL import ImageDraw, ImageFont, Image
font = ImageFont.truetype("static/Fonts/simsun.ttc", 30)
def handle_image():
src_image = cv2.imread('images/193.jpg', cv2.COLOR_BGR2RGB)
# 假设你有一个轮廓,用一系列的点表示
# 例如:
contour = np.array([[98, 133], [400, 30], [474, 245], [171, 349]])
cv2.drawContours(src_image, [contour], -1, (255, 0, 0), 2)
# 你要检查的点
point0 = (340, 300)
text0 = pointInPolygon(src_image, contour, point0);
point1 = (140, 300)
text1 = pointInPolygon(src_image, contour, point1);
point2 = (140, 100)
text2 = pointInPolygon(src_image, contour, point2);
point3 = (460, 240)
text3 = pointInPolygon(src_image, contour, point3);
img = Image.fromarray(src_image)
draw = ImageDraw.Draw(img) # 创建一个画图对象
draw.text(point0, text0, font=font, fill=(0, 0, 255))
draw.text(point1, text1, font=font, fill=(0, 0, 255))
draw.text(point2, text2, font=font, fill=(0, 0, 255))
draw.text(point3, text3, font=font, fill=(0, 0, 255))
frame = np.array(img)
cv2.imshow('src_image', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
def pointInPolygon(image, contour, point):
cv2.circle(image, point, 2, (0, 0, 255), 2)
# 计算点是在轮廓内、外或边界上
# 注意:点的坐标是相对于轮廓的坐标系的
# 参数10表示是否将点当作整数处理,通常设置为False
inside = cv2.pointPolygonTest(contour, point, False)
# inside的值将是+1、-1或0
text = "点在轮廓内" if inside > 0 else "点在轮廓外" if inside < 0 else "点在轮廓上"
return text
if __name__ == '__main__':
handle_image()
执行程序,显示的结果如下:


浙公网安备 33010602011771号