|
|
import numpy as np |
|
|
import cv2 |
|
|
from matplotlib import pyplot as plt |
|
|
|
|
|
def visualize_mask(points, size, save_path="mask.png"): |
|
|
""" |
|
|
输入: |
|
|
points : 多边形坐标 [[x1,y1], [x2,y2], ...] |
|
|
size : 图像尺寸 [height, width] |
|
|
save_path : 输出图片保存路径(默认当前目录mask.png) |
|
|
|
|
|
输出: |
|
|
展示并保存包含多边形顶点(红色)和掩码区域(半透明绿)的图片 |
|
|
""" |
|
|
|
|
|
assert len(size) == 2, "size must be [height, width]" |
|
|
height, width = size |
|
|
assert height > 0 and width > 0, "invalid image size" |
|
|
|
|
|
|
|
|
canvas = np.zeros((height, width, 4), dtype=np.uint8) |
|
|
|
|
|
|
|
|
polygon = [] |
|
|
for x, y in points: |
|
|
|
|
|
x = int(np.clip(round(x), 0, width-1)) |
|
|
y = int(np.clip(round(y), 0, height-1)) |
|
|
polygon.append([x, y]) |
|
|
polygon = np.array([polygon], dtype=np.int32) |
|
|
|
|
|
|
|
|
mask = np.zeros((height, width), dtype=np.uint8) |
|
|
cv2.fillPoly(mask, polygon, color=1) |
|
|
canvas[..., 1] = 80 * mask |
|
|
canvas[..., 3] = 200 * mask |
|
|
|
|
|
|
|
|
for idx, (x, y) in enumerate(polygon[0]): |
|
|
color = (0, 0, 255, 255) |
|
|
cv2.circle(canvas, (x, y), radius=5, color=color, thickness=-1) |
|
|
cv2.putText(canvas, str(idx+1), (x+7, y+3), |
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255,255), 1) |
|
|
|
|
|
|
|
|
cv2.polylines(canvas, polygon, isClosed=True, |
|
|
color=(255, 0, 0, 255), thickness=2) |
|
|
|
|
|
|
|
|
cv2.imwrite(save_path, canvas) |
|
|
|
|
|
|
|
|
plt.figure(figsize=(10, 6)) |
|
|
plt.title(f"Mask Visualization (Saved to {save_path})") |
|
|
plt.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGRA2RGBA)) |
|
|
plt.axis('off') |
|
|
plt.show() |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
points = [ |
|
|
[602.245, 290.396], |
|
|
[585.264, 289.452], |
|
|
[568.283, 301.716], |
|
|
[557.905, 309.264], |
|
|
[546.584, 324.358], |
|
|
[543.754, 342.283], |
|
|
[544.698, 365.867], |
|
|
[552.245, 381.905], |
|
|
[571.113, 398.886], |
|
|
[583.377, 407.377], |
|
|
[597.528, 409.264], |
|
|
[607.905, 398.886], |
|
|
[626.773, 387.566], |
|
|
[636.208, 384.735], |
|
|
[646.584, 381.905], |
|
|
[660.735, 370.584], |
|
|
[661.679, 335.679], |
|
|
[654.132, 313.037], |
|
|
[639.981, 302.660], |
|
|
[618.283, 293.226] |
|
|
] |
|
|
size = [960, 1280] |
|
|
|
|
|
|
|
|
visualize_mask( |
|
|
points=points, |
|
|
size=size, |
|
|
save_path="custom_mask_visualization.png" |
|
|
) |