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)
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!!!!