【问题标题】:imwrite merged image : writing image after adding alpha channel to it opencv pythonimwrite 合并图像:在向其添加 alpha 通道后写入图像 opencv python
【发布时间】:2017-07-07 22:39:55
【问题描述】:

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

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

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

我应该怎么做才能让imwrite 用 alpha 通道写入正确的 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)

【问题讨论】:

    标签: image python-2.7 opencv numpy


    【解决方案1】:

    问题在于您的 alpha 通道,图像显示在 imshow 但未显示在 imwerite 的原因在于 cv2.imshow() 拒绝 alpha 通道而 imwrite 接受考虑 Alpha 通道。

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

    对于修复,您应该将 alpha 初始化为 alphachn = np.ones(shp, dtype=np.uint8)*255,它创建了一个填充了 255 值的 numpy 矩阵。如果您想调整 Alpha 通道值以获得半透明结果,则可以使用 255 中的 150。

    【讨论】:

    • 我在合并之前做了 alphachn = np.ones(shp)*255 然后 alphachn.astype('uint8') 。 imwrite 已成功写入图像。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2016-07-26
    相关资源
    最近更新 更多