Skip to content Skip to sidebar Skip to footer

How To Get Transparent Background From Jpeg Image By Converting To Png?

I want to make the background of an image (jpg/jpeg) transparent white. Below is my code which transfers green background to white (correctly identify edge of person): Input image

Solution 1:

Your approach might be somehow unfortunate. When antialiasing your mask, you get values in the range 0 ... 255, but you only set result[mask == 0] = bg (white). You don't take into account all the other pixels, which (gradually) also belong the original mask. So, I would re-arrange your code, and simply use the final mask as the alpha channel. I did that also using OpenCV; using the additional Pillow loop feels somehow cumbersome from my point of view.

That'd be a modified excerpt from your code:

import cv2
import numpy as np
import skimage.exposure

img = cv2.imread('rmQRJIS.jpg')
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower = (40, 80, 80)
upper = (90, 255, 255)
mask = cv2.inRange(img_hsv, lower, upper)
mask = 255 - mask

kernel = np.ones((3, 3), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_ERODE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

# Use initial, binary mask to set background to white
result = img.copy()
result[mask == 0] = (255, 255, 255)

# Save image just for intermediate output
cv2.imwrite('output_no_trans.png', result)

# Use antialiased mask as final alpha channel for transparency
mask = cv2.GaussianBlur(mask, (0, 0), sigmaX=3, sigmaY=3, borderType=cv2.BORDER_DEFAULT)
mask = skimage.exposure.rescale_intensity(mask, in_range=(127.5, 255), out_range=(0, 255))
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:, :, 3] = mask

# Save final image
cv2.imwrite('output.png', result)

As an intermediate output, I saved the image after setting the background to white:

Intermediate output

The final output including the alpha channel looks like this:

Final output

To be honest, the difference can be hardly seen here, since I had to downscale the output images before uploading to maintain PNG compatibility. Please, have a look at the fullsized images yourself, if the result is in your favor!

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
NumPy:         1.20.1
OpenCV:        4.5.1
scikit-image:  0.18.1
----------------------------------------

Post a Comment for "How To Get Transparent Background From Jpeg Image By Converting To Png?"