0

I'm trying to replace a color range with some specific color using PIL module. Suppose I want to change the color of the sky,I need to generate a list of the color of pixels.

enter image description here

My code currently

from PIL import Image, ImageColor

im = Image.open("iphone.jpg", "r")
to_be_replaced = ImageColor.getcolor("#5f86c9", "RGB")
newcolor = ImageColor.getcolor("#c9bb5f", "RGB")
print(to_be_replaced, newcolor)

pix = im.load()
width, height = im.size
for w in range(width):
    for h in range(height):
        r, g, b = pix[(w, h)]
        if (r, g, b) == to_be_replaced:
            pix[w, h] = newcolor
        else:
            pix[w, h] = (r, g, b)
im.save('test.png', 'PNG')

newcolor here is the yellow color, and to_be_replaced is the color of a pixel from the sky.

Code output till now: enter image description here The script works, but currently, it changes the color of just a pixel with the specified color. I want to replace the color of the whole sky. Can anybody please help me with this problem?

  • You are changing a specific color value. If you want to change the color of the sky you would need to determine the window range of values you would want to replace. You could try segmentation on a single color spectrum to get the mask of the sky. I am assuming you only want to color the blue sky. – Jason Chia Nov 05 '21 at 07:34
  • @JasonChia Yes I want to replace the blue color. I'm pretty new to this so can you guide me through "segmentation on a single color spectrum"? – Asad Kareem Nov 05 '21 at 07:36
  • 2
    You have RGB color in your image. For this particular problem you want to only replace BLUE. Simply find all pixels where the B value is significantly greater than R and G and it should work well enough (will fail if there is blue elsewhere). if you want more complex methods: a quick google search for sky segmentation and you'll find many papers on various approaches and algorithms. – Jason Chia Nov 05 '21 at 07:47
  • Not sure if using array (https://stackoverflow.com/questions/53155749/replace-elements-in-numpy-array-avoiding-loops) is faster or not ? You should check it – pippo1980 Nov 08 '21 at 09:42
  • Better example here https://stackoverflow.com/questions/19666626/replace-all-elements-of-python-numpy-array-that-are-greater-than-some-value – pippo1980 Nov 08 '21 at 09:49

0 Answers0