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 &lt;module&gt;
    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
    img[_colour_mask(img, incolour)] = outcolour
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.

[Edit]
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

def _colour_mask(img, colour):
    """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)
    img[_colour_mask(img, incolour)] = outcolour
    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)