rafasalo
rafasalo

Reputation: 255

Problem when saving a png to jpg in opencv

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

Upvotes: 1

Views: 2369

Answers (1)

Shawn Mathew
Shawn Mathew

Reputation: 2337

As mentioned in the comments, simply removing the alpha channel does not remove the background in this case because the BGR channel has the artifact you are trying to remove, as is shown below when you only plot the B, G or R channel.

B channel

And your alpha channel looks like this

alpha channel

To achieve what you need, you'll need to apply some matrix math to get your result. I've attached the code here

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()

The result being an image with dimensions (1200, 1200, 3)

enter image description here

Upvotes: 4

Related Questions