# Converting colours in an image using Python Imaging Library

I have written the beginning of a map engine which runs off PIL and some JavaScript client side. Ignoring the rest of the code that is in the same file as this function, can you suggest any improvements to this code here?

def convert_colour(region_number, incolour, outcolour):
#print(region_list.regions_d[region_number][0].split('\\')[7], incolour, outcolour)
img = Image.open(region_list.regions_d[region_number][0])
img = img.convert("RGBA")
newData = []
newData = [outcolour if item==incolour else item for item in img.getdata()]
img.putdata(newData)
img.save(region_list.regions_d[region_number][0], "PNG")
colour_change_single(region_number, outcolour)


Further to a suggestion I have tried to include numpy but recieve the following error:

Traceback (most recent call last):
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 227, in <module>
run_function_tests()
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 219, in run_function_tests
run_engine_test(change_list)
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 161, in run_engine_test
convert_colour(x[0], region_list.regions_d[x[0]][1], x[1])
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 115, in convert_colour
new_img = _convert_colour(img, incolour, outcolour)
File "D:\Anaconda3\Lib\idlelib\image-transparency.py", line 108, in _convert_colour
ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (216,4)


I realised there needs maybe some clarity about this traceback. run_function_tests() this has code to run a short test with my old code.

def run_engine_test(change_list):
for x in change_list:
convert_colour(x[0], region_list.regions_d[x[0]][1], x[1])


change_list = [(n,random.choice(colour_list.colour_list)) for n in region_list.regions_d]

We also have a function called colour detect which will check for patterns in the colour

def colour_detect():
#Detect if colours in the image match the colours on the palette and re-maps the dictionary if a region colour is changed
detected_colours = []
for x in region_list.regions_d:
region_colour = print_img_data(region_list.regions_d[x][0])
region_list.regions_d[x] = [region_list.regions_d[x][0], region_colour]
if region_colour not in detected_colours:
detected_colours.append(region_colour)


This is intended to be run at the beginnig of a "game or round" and then in between the engine ticks when actions like wars are comitted. Hence why it checks all of the images to ensure that the dictionary has been updated correctly.

After that the traceback comes from your functions.

 The error was related to a typo in my code. The suggestion provided reduced the time to do the functions by 2/3rds!!!!

This is the image i am editing (c)

The easiest way is to use the numpy interface for this, since it allows you to do operations on the whole image:

from PIL import Image
import numpy as np

"""Finds all indices of a single colour in a PIL.Image"""
if len(img.shape) == 3:
return (img == colour).all(axis=2).nonzero()
elif len(image.shape) == 2:
return (img == colour).nonzero()
else:
raise ValueError("Invalid image shape {}".format(img.shape))

def _convert_colour(img, incolour, outcolour):
"""Replaces incolour with outcolour in a PIL.Image.

Returns a new PIL.Image.
Assumes that img has as many channels as len(incolour) and len(outcolour).
"""
img = np.array(img)
return Image.fromarray(img)

def convert_colour(region_number, incolour, outcolour):
file_name = region_list.regions_d[region_number][0]
img = Image.open(file_name)
new_img = _convert_colour(img, incolour, outcolour)
new_img.save(file_name, "PNG")
colour_change_single(region_number, outcolour)

• I have amended my accepted answer as you have perfectly answered my question. I didn't think about using npy for this, but considering your experience, I will certainly take your advice. Thanks for your time :) Aug 22 '18 at 13:58
• @Swift: It does work with color images for me (you can even call image.convert("RGBA") on it without anything changing). Not sure if this would work with grayscale images, though. Aug 23 '18 at 9:28
• It's just that I get an error about mis-shaped or something like that. Let me reproduce it, perhaps you can explain the error I get. I really want to convert the colour conversion to np as it seems everyone is shouting about how much faster it can process this data for me. Aug 23 '18 at 9:32
• @Swift: Without seeing the error I cannot know what the reason is... Aug 23 '18 at 9:33
• Dont worry, I found the mishaped "Mustard_Yellow" value, like you said, it was missing the aplha value. Im so sorry, what a derp I can be at times haha! Aug 23 '18 at 9:49

# global

this uses global variable region_list, but only region_list.regions_d[region_number][0], which is probably a filename. Better would be to just pass the filename to this function, instead of using this global variable

what does colour_change_single(region_number, outcolour) do? It looks unrelated to changing the image, so wouldn't it make more sense to have the one invoking convert_colour to also take care of this?
Remove newData = []
Perhaps rename incolour and outcolour to more descriptive names.