Python cv2.imshow工作正常,但cv2.imwrite保存黑色图像

2024-09-22 16:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用一个位掩码将一个对象从JPG图像剪切成一个具有透明背景的4通道PNG图像。当我用cv2.imshow显示结果时,它会正确显示,但如果我用cv2.imwrite保存它,它会显示黑色图像

例如:

这是原始图像

enter image description here

这是面具

enter image description here

以下是cv2.imshow()显示的正确结果

enter image description here

这是密码

# read the original jpg image
image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)

# create an empty 2d numpy array with zeros with the shape of the original image
arraymask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)

# poly_cords is an list with polygon coordinates for the mask
# create a numpy array from the polygon list
polynumpy = np.array(poly_cords, dtype=np.int32)

# fill the the zero 2d image with the polygon shape to create the mask image shown above
arraymask = cv2.fillPoly(arraymask, [polynumpy], color=255)

# create empty transparent image with 4 channels filled with zeros
transparent_im = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)

# fill up first 3 channels with only the part of the image that is the shape of the mask
transparent_im[arraymask == 255, :3] = image[arraymask == 255]

cv2.imshow("help", transp_image)
cv2.waitKey(0)

cv2.imwrite("image.png", transp_image)

解决方案:

我忘了填充alpha层

transparent_im[arraymask == 255, 3] = 255

Tags: ofthe图像imagecreatewithnpzeros