Skip to main content
3 of 6
included the error
Swift
  • 133
  • 5

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
    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)
Swift
  • 133
  • 5