I need to write script in Python, like this with options:
- Enable PNG transparency
- Treat similar colors as transparent. 5%
How can I do this?
Potential solutions
ffmpeg, imagemagick
I need to write script in Python, like this with options:
How can I do this?
ffmpeg, imagemagick
Here is one way to do that in Python/OpenCV
Input:
import cv2
import numpy as np
# load image
img = cv2.imread('barn.jpg')
# specify blue color
color = (230,160,120)
b = color[0]
g = color[1]
r = color[2]
# specify tolerance as percent
tol = 5
tol = 5/100
# make lower and upper bounds as color minus/plus 5%
bl = int((1-tol) * b)
gl = int((1-tol) * g)
rl = int((1-tol) * r)
lower = (bl,gl,rl)
bu = int((1+tol) * b)
gu = int((1+tol) * g)
ru = int((1+tol) * r)
upper = (bu,gu,ru)
# threshold on color and invert
mask = cv2.inRange(img, lower, upper)
mask = 255 - mask
# put mask into alpha channel
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:, :, 3] = mask
# save resulting masked image
cv2.imwrite('barn_transp_blue.png', result)
# display result, though it won't show transparency
cv2.imshow("MASK", mask)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Threshold image:
Transparent result:
img = Image.open(images_dir +'/'+ filename)
img.save(create_path +'/'+ filename.split('.')[0]+'.png', 'png')