如何根据图像上旋转矩形的坐标制作蒙版?

How to make a mask from rotated rectangle's coordinates on image?

我有下图four points的坐标。我想从 four coordinates 的矩形区域制作一个 mask。我怎样才能做到这一点?我试过关注 code.

back=np.zeros(rotated_img.shape)
mask=np.zeros(rotated_img.shape)
# back[rotated_img==2]=255
back[rotated_img>0]=255
plt.imshow(back)
plt.show()

# ++++++++++++++++++++++++++++++++++=
Y1,Y2,Y3,Y4,X1,X2,X3,X4=[],[],[],[],[],[],[],[]

for lb in label.keys():
    # co-ordinate
    idx = np.where(img==lb)
    y_min,y_max,x_min,x_max = np.min(idx[0]), np.max(idx[0]), np.min(idx[1]), np.max(idx[1])
    
    x1,x2,x3,x4=x_min,x_max,x_max,x_min
    y1,y2,y3,y4=y_min,y_min,y_max,y_max
    
    X1.append(x1)
    X2.append(x2)
    X3.append(x3)
    X4.append(x4)
    
    Y1.append(y1)
    Y2.append(y2)
    Y3.append(y3)
    Y4.append(y4)

# +++++++++++++++++++++++++++++
x1,x2,x3,x4=min(X1),max(X2),max(X3),min(X4)
y1,y2,y3,y4=min(Y1),min(Y2),max(Y3),max(Y4)

coords=np.array([[x1,y1],[x2,y2],[x3,y3],[x4,y4]],dtype="float32")
print(coords)

new_coords=[]
coord_mat=np.concatenate([coords,np.ones((4,1))],axis=1)
for c in coord_mat:
    new_coords.append(np.dot(M,c))

plt.imshow(back)
for c in new_coords:
    plt.plot(c[0], c[1], 'go--', linewidth=2, markersize=12)
    print(c[0], c[1])

plt.show()

Outout:

[[  0.   0.]
 [731.   0.]
 [731. 127.]
 [  0. 127.]]
-0.4652977851045641 365.5743741577959
632.5992723813201 0.07437415779594403
696.0992723813201 110.05960043841964
63.03470221489543 475.5596004384196

如果 mask 只是指一个 numpy 数组,它在矩形外部为 0,在矩形内部为 1(或者相反,或者您喜欢的任何值),那么 cv2 可以为您做到这一点,它只是绘制一个多边形。使用输出中的值:

import cv2
import numpy
from matplotlib import pyplot as plt
x = np.zeros((475, 696), dtype=np.uint8)
pts = np.array([[-0.4652977851045641, 365.5743741577959],
[632.5992723813201, 0.07437415779594403],
[696.0992723813201, 110.05960043841964],
[63.03470221489543, 475.5596004384196]], np.int32).reshape(-1, 1, 2)
plt.imshow(cv2.fillPoly(x,[pts],255), cmap='gray')

这个returns: