'OpenCV : How to clear Image Background of ID Card without losing quality

I want to clear an image background of ID without losing quality, Keep only the text with white background

Using the following code is not efficient, produce high noise and distortion

 img = cv2.imread(imge)

# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Convert BGR to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# define range of black color in HSV
lower_val = np.array([0,0,0])
upper_val = np.array([179,255,135])

# Threshold the HSV image to get only black colors
mask = cv2.inRange(hsv, lower_val, upper_val)

# invert mask to get black symbols on white background
mask_inv1 = cv2.bitwise_not(mask)

mask_inv = cv2.blur(mask_inv1,(5,5))

How I can achieve clean background with these images

Samples

enter image description here

enter image description here

Output

enter image description here enter image description here



Solution 1:[1]

Using Rembg to get perfect output like below

Rembg is an offline tool to remove images background. you can simply install Rembg package using pip in python

pip install rembg

afterthat,

rembg i path/to/input.png path/to/output.png

output1

output2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1