-1

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

KSAH
  • 15
  • 6
soc17302
  • 1
  • 1
  • Welcome to SO! Please take the [tour], read [ask], and provide a [mre]. What have you tried so far? Why do your solutions not meet your expectations? – Pranav Hosangadi Aug 03 '20 at 14:36
  • What do you mean when you say you *"want to treat similar colours as transparent 5%"*? Similar to what? What is the 5% for? Please give an example input and corresponding output image and show what you have tried so far. – Mark Setchell Aug 03 '20 at 16:15

2 Answers2

2

Here is one way to do that in Python/OpenCV

  • Read the input
  • Define the desired color (blue) to be made transparent
  • Define the tolerance amount (5%)
  • Create upper and lower bounds on the color according to the tolerance
  • Threshold on color and invert
  • Put the threshold result into the alpha channel of the input
  • Save the results

Input:

enter image description here

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:

enter image description here

Transparent result:

enter image description here

fmw42
  • 46,825
  • 10
  • 62
  • 80
0
        img = Image.open(images_dir +'/'+ filename)
        img.save(create_path +'/'+ filename.split('.')[0]+'.png', 'png')
Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18
  • The first line opens the image(replace `filename` with your image name and its extension. The second changes the extension and saves file to the same directory – Seyi Daniel Aug 03 '20 at 14:33
  • I need to convert image, not rename this – soc17302 Aug 03 '20 at 14:41
  • The `img.save` does that. It's not mandatory, you do `create_path +'/'+ filename.split('.')[0]+'.png`, you may save your open file to png using an filename you prefer. – Seyi Daniel Aug 03 '20 at 14:51