Problem when saving a png to jpg in opencv

时间:2019-03-19 15:10:08

标签: python python-3.x opencv png

I'm running this piece of code and getting a wrong result:

        #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

The original file is a png with a transparent background. I don't know why but it's saving with this grey pattern behind the bottle neck.

Original File: enter image description here

1 个答案:

答案 0 :(得分: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