以下实现分割的单通道mask图像的生成。
一、关于arr
1, arr是一个多边形的x y坐标的array,
[144.7, 134.2] 是这个多边形的一个点的x y坐标。
arr2是另一个多边形的 x y 坐标的array。
2, 数据类型要设置成np.int32, 不然会报错。
3,传入fillPolly做参数前要加中括号,不然会报错。
二、关于fillPoly
fillPoly 的color 参数,如果是生成单通道,填个数即可,
(255,0,0)不会报错,但是容易跟3通道的混淆。
cv2的color 是brg的顺序。
三、关于通道
一定要统一,
就是生成的图像是单通道,
读入的时候也是单通道读入。
如果生成的是3通道,
读入是单通道读入,
读入的数会不对。
import numpy as np
import cv2
import os
arr = np.array([[144.7, 134.2], [185.5, 132.3], [183.9, 149.6], [142.1, 150.0], [141.7, 143.0], [144.7, 137.3]], dtype=np.int32)
arr2 = np.array([[140.9, 183.4], [186.6, 181.1], [186.6, 188.8], [188.9, 198.4], [196.6, 220.3], [197.0, 236.4], [192.0, 246.0], [190.8, 255.2], [154.0, 257.9], [147.0, 216.8], [140.9, 198.0], [141.3, 183.8]], dtype=np.int32)
h, w = 288, 384
pth = r"F:\vscode_files\project\segment_side"
mask = np.zeros((h, w), dtype=np.int32)
cv2.fillPoly(mask, [arr], color=255)
cv2.fillPoly(mask, [arr2], color=255)
# 以上两行也可以用这一句代替 cv2.fillPoly(mask, [arr, arr2], color=255)
cv2.imwrite(os.path.join(pth, "2400.png"), mask)
单通道读入代码:
mask_img = cv2.imread(r"F:\vscode_files\project\segment_side\2400.png", cv2.IMREAD_GRAYSCALE)
print(mask_img.shape) # (288, 384)
print(mask_img)
list_ = []
for i in range(h):
for j in range(w):
if mask_img[i][j] not in list_:
list_.append(mask_img[i][j])
print(list_)
output:
(288, 384)
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]
[0, 255]