gpt4 book ai didi

image - imwrite 合并图像 : writing image after adding alpha channel to it opencv python

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:08 25 4
gpt4 key购买 nike

我想更改图像的背景并在将其保存为 png 文件之前为其添加 alpha channel 。

imshow 显示图像,但 imwrite 写入空图像。合并后的尺寸也是正确的,即当我打印 img_a.shape

时,合并后的图像有 (x,y,4)

图像深度为uint8。我尝试将其更改为 float32 然后除以 255 但似乎没有任何效果。我缺少一些基本的东西。

我应该怎么做才能使 imwrite 写入带有 alpha channel 的正确 png?我尝试了 cv2.mergenp.dstackimwrite 写入失败。用 gimp 打开它时,它显示一层。

以下是我的代码。

imgo = cv2.imread('PCP_1.jpg')
image = cv2.GaussianBlur(imgo, (5, 5), 0)
r = image.shape[0]
c = image.shape[1]
shp = (r,c,1)
c_red, c_green, c_blue = cv2.split(image)
#c_red = c_red.astype(np.float32)
#c_green =c_green.astype(np.float32)
#c_blue = c_blue.astype(np.float32)
alphachn = np.zeros(shp)
#alphachn = alphachn.astype(np.float32)
img_a = cv2.merge((c_red, c_green, c_blue, alphachn))
#img_a = np.dstack( (imgo, np.zeros(shp).astype(np.uint8) ) )
print img_a.shape
cv2.imshow('image', img_a)
cv2.imwrite('image_alpha.png', img_a)
k = cv2.waitKey(0)

最佳答案

问题出在您的 alpha channel 上,图像在 imshow 中显示但在 imwerite 中未显示的原因在于 cv2.imshow () 拒绝 alpha channel ,而 imwrite 考虑了 alpha channel 。

根据您的代码,您将 alpha channel 定义为 alphachn = np.zeros(shp),它创建了一个充满零的 numpy 矩阵,而一个全零值的 alpha channel 意味着 透明 图像,或者换句话说,如果 alpha channel 为零,则该像素的 RGB 值永远不可见,这就是您使用 imwrite() 获得空图像的原因。

要解决此问题,您应该将 alpha 初始化为 alphachn = np.ones(shp, dtype=np.uint8)*255,这会创建一个具有 255 值的 numpy 矩阵填进去了。如果您想调整 alpha channel 值以获得半透明结果,那么您可以使用 150 insted of 255。

关于image - imwrite 合并图像 : writing image after adding alpha channel to it opencv python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42314272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com