在opencv中将png保存到jpg时出现问题

问题描述 投票:0回答:1

我正在运行这段代码并得到错误的结果:

        #saving image into a white bg
        img = cv2.imread(dir_img + id, cv2.IMREAD_UNCHANGED)
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
        print(img.shape)
        cv2.imwrite(dir_img + id, img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])

enter image description here

原始文件是具有透明背景的png。我不知道为什么,但是瓶颈后面的这种灰色图案可以节省。

原文件:enter image description here

python python-3.x opencv png
1个回答
1
投票

正如评论中所提到的,在这种情况下,简单地删除alpha通道并不会删除背景,因为BGR通道具有您要删除的工件,如下图所示,当您只绘制B,G或R通道时。

B channel

你的alpha通道看起来像这样

alpha channel

为了达到你的需要,你需要应用一些矩阵数学来得到你的结果。我在这里附上了代码

import cv2
import matplotlib.pyplot as plt

img_path = r"path/to/image"

#saving image into a white bg
img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
plt.imshow(img)
plt.show()
b,g,r, a = cv2.split(img)
print(img.shape)

new_img  = cv2.merge((b, g, r))
not_a = cv2.bitwise_not(a)
not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)
plt.imshow(not_a)
plt.show()
new_img = cv2.bitwise_and(new_img,new_img,mask = a)
new_img = cv2.add(new_img, not_a)

cv2.imwrite(output_dir, new_img)
plt.imshow(new_img)
print(new_img.shape)
plt.show()

结果是尺寸为(1200, 1200, 3)的图像

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.