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

Python 在opencv中将png保存为jpg时出现问题,python,python-3.x,opencv,png,Python,Python 3.x,Opencv,Png,我运行这段代码时得到了错误的结果: #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_

我运行这段代码时得到了错误的结果:

        #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])

原始文件是具有透明背景的png。我不知道为什么,但它的节省与这个灰色的模式背后的瓶颈

原始文件:

如评论中所述,在这种情况下,仅移除alpha通道不会移除背景,因为BGR通道具有您试图移除的工件,如下所示,当您仅绘制B、G或R通道时

你的阿尔法通道是这样的

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

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)


如评论中所述,在这种情况下,仅移除alpha通道不会移除背景,因为BGR通道具有您试图移除的工件,如下所示,当您仅绘制B、G或R通道时

你的阿尔法通道是这样的

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

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)


您可以共享原始文件吗?可能是因为您的图像后面有灰色图案,但它被alpha“隐藏”了channel@Alderven原始文件uploaded@Miki我如何删除它?你能共享原始文件吗?可能是因为你的图像后面有灰色图案,但它是“隐藏的”按字母顺序channel@Alderven原始文件uploaded@Miki如何删除它?