Give pixels with certain color a different RGB value in python

Question:

I’ve got a weather site, but it’s missing a personalized radar.
I’ve found open radar data for my country (the netherlands) but it already has a specific color. I found that python can manipulate colors with the image lib, but i’m not that good with python. How can I get python to recognize the radar colors, pixel by pixel, and change them to a different color? Sample image:

This
(source: weerplaza.nl)

Answers:

Your image’s type is GIF. It makes the job more difficult because the color of GIF is palette-based, not RGB. OpenCV is not support GIF right now, your best option maybe Pillow.

So, according to this SO’s post you first need to find the palette, then convert the palette to RGB and find which color is in which pixel (which can be done easily by using some tools like colorpix).

Next, you change that color in the palette and write this new palette back to the image.

import Image

im = Image.open("pathtonos_radar_285.gif")

try:
    i = 0
    while 1:
        im.seek(im.tell() + 1)
        
        # get color of each pixel
        pal_inds = list(im.getdata())
        pal_rgbs = list(im.convert('RGB').getdata())
        
        # change a specific color to another color
        # eg. (190, 5, 3) to (138, 218, 47)
        pal_rgbs = [color if color != (190, 5, 3) else (138, 218, 47) for color in pal_rgbs]
        
        # remake a new palette
        pal_map = dict((zip(pal_inds, pal_rgbs)))
        palette = [pal_map[i] for i in sorted(pal_map)]
        flat_palette = [ind for rgb in palette for ind in rgb]
        
        # put the palette back to image
        im.putpalette(flat_palette)
        im.show()
        im.save('name%d' %i, 'jpg')
        i+=1
except EOFError:
    print 'done'

Since the GIF contains more than one frame, I save each frame as separate image.

Answered By: dragon2fly
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.