目录
笔记:
两个函数都只能填充凸多边形,凹多边形会丢失一部分内容,用人脸关键点做掩码时出现了这个情况。
顺时针排序,然后填充多边形
函数可以用来填充凸多边形,需要提供凸多边形的顶点,先顺时针排序,然后再填充多边形。
import cv2
import numpy as np
from functools import reduce
import operator
import math
img = cv2.imread(r'd:/qinlan.jpg')
shape = img.shape
points_704 = np.array([[30, 280], [240, 290],[30, 30], [280, 30]])
coords =points_704
#开始顺时针排序
center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), coords), [len(coords)] * 2))
points_new=sorted(coords, key=lambda coord: (-135 - math.degrees(math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) % 360, reverse=True)
points_new=np.array(points_new)
height = shape[1]
# 图片的高度尺寸
img_result = img.copy()
cv2.fillConvexPoly(img, points_new, 1)
bitwisexor = cv2.bitwise_xor(img, img_result)
cv2.imshow("bitwisexor", bitwisexor)
cv2.imshow("img", img)
cv2.waitKey(0)
先计算质心,然后顺时针排序
import numpy as np
import cv2
def sort_points_clockwise(points):
# Calculate the centroid of the points
centroid = np.mean(points, axis=0)
# Calculate the angle of each point relative to the centroid
angles = np.arctan2(points[:, 1] - centroid[1], points[:, 0] - centroid[0])
# Sort the points by angle in clockwise order
sorted_points = points[np.argsort(angles)]
return sorted_points
# Create a blank image
img = np.zeros((1080, 1920, 3), np.uint8)
# Define multiple points (some of which may be outside the image bounds)
points = np.array([[100, 100], [500, 400], [1500, 800], [1200, 1500], [200, 700]])
# Sort points in clockwise order
sorted_points = sort_points_clockwise(points)
# Fill the polygon with white color
cv2.fillConvexPoly(img, sorted_points, (255, 255, 255))
# Display the image
cv2.imshow("Polygon", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.fillPoly()函数可以用来填充任意形状的图型.可以用来绘制多边形,工作中也经常使用非常多个边来近似的画一条曲线.cv2.fillPoly()函数可以一次填充多个图型.
img = np.zeros((1080, 1920, 3), np.uint8)
area1 = np.array([[250, 200], [300, 100], [750, 800], [100, 1000]])
area2 = np.array([[1000, 200], [1500, 200], [1500, 400], [1000, 400]])
cv2.fillPoly(img, [area1, area2], (255, 255, 255))
plt.imshow(img)
plt.show()
参考:
cv2.fillConvexPoly()与cv2.fillPoly()填充多边形_Wanderer001的博客-CSDN博客