简体   繁体   English

有没有什么简单的方法可以用 cv2 分析透明的 png 图像?

[英]Is there any easy way to analyse transparent png image with cv2?

I am trying to load a transparent image (just without background) with CV2 but when I try to show the image I get a black background.我正在尝试使用 CV2 加载透明图像(只是没有背景),但是当我尝试显示图像时,我得到了黑色背景。 Is there any possible (and easy) way to load transparent PNG image?有没有可能(且简单)的方法来加载透明的 PNG 图像? The input:输入:

我得到的结果 The result:结果: 我得到的结果

This is the result I get: Even if i'm trying this code:这是我得到的结果:即使我正在尝试此代码:

import cv2
im = cv2.imread("image.png", cv2.IMREAD_UNCHANGED)
cv2.imshow('test',im)

I get the result with black background我得到黑色背景的结果

The image you are loading has four channels.您正在加载的图像有四个通道。 Check the array size.检查数组大小。 Channel 4 is the alpha channel and you can save the image back accordingly with an alpha channel.通道 4 是 Alpha 通道,您可以使用 Alpha 通道相应地将图像保存回来。 You can also generate a mask from the alpha channel (in OpenCV masks are binary with values 0, and 255, respectively).您还可以从 alpha 通道生成掩码(在 OpenCV 中,掩码是二进制值,分别为 0 和 255)。

Most of OpenCV operations work on 4-channel images, but they do not treat the alpha channel special or derive any information from it.大多数 OpenCV 操作适用于 4 通道图像,但它们不会特殊处理 alpha 通道或从中获取任何信息。

cv.loadImage() is for MultiCameraCalibration. cv.loadImage() 用于 MultiCameraCalibration。 Use cv.imread() for single images.对单个图像使用 cv.imread()。 To get transparency, you must use the flag of cv.IMREAD_UNCHANGED要获得透明度,您必须使用 cv.IMREAD_UNCHANGED 标志

Here is how to do that in Python/OpenCV.下面是如何在 Python/OpenCV 中做到这一点。 Note that with the cv.imshow you will not see transparency.请注意,使用 cv.imshow 您将看不到透明度。 It will be black.它会是黑色的。 To do further analysis, you should extract the alpha channel as a mask and use that for whatever you want to do to limit the processing to the shoe and not the background around it.要进行进一步分析,您应该将 Alpha 通道提取为蒙版,并将其用于任何您想做的事情,以限制对鞋子的处理,而不是它周围的背景。

import cv2

# load image with alpha channel
img = cv2.imread('shoe.png', cv2.IMREAD_UNCHANGED)

# get mask from alpha channel
mask = img[:,:,3]

# view images
# NOTE: imshow does not show transparency. It will be black there.
cv2.imshow('img', img)
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Saving the image does contain transparency as can be seen when viewed with some external viewer.
cv2.imwrite('shoe_copy.png', img)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM