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

Python cv2.imshow工作正常,但cv2.imwrite保存黑色图像,python,numpy,opencv,opencv-python,Python,Numpy,Opencv,Opencv Python,我试图使用一个位掩码将一个对象从JPG图像剪切成一个具有透明背景的4通道PNG图像。当我用cv2.imshow显示结果时,它会正确显示,但如果我用cv2.imwrite保存它,它会显示黑色图像 例如: 这是原始图像 这是面具 以下是cv2.imshow()显示的正确结果 这是密码 # read the original jpg image image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) # create an empty 2d n

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

例如:

这是原始图像

这是面具

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

这是密码

# 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

“创建空的透明图像,其中4个通道填充了零”。。。。你永远不会改变alpha通道——0的alpha是完全透明的。而
imshow
忽略alpha,这就是为什么你可以看到一些东西。无论您使用什么程序来查看
image.png
都不会忽略alpha,而且由于您使整个图像完全透明,因此您无法看到任何图像。谢谢。现在我明白了!