I have a loop which fills up a 2-D NumPy array with pixel information for PIL, this array is called 'Shadows'. The colours are either white or blue. I want to build up a final image from these where the white is dominant. i.e. if one image in the loop has a blue pixel on co-ordinate x,y and another image in the loop has a white pixel on the same co-ordinate then the final pixel will be white.
This is currently done by:
import math, random, copy
import numpy as np
from PIL import Image, ImageDraw
colours = {0: (255,255,255), 1: (0,0,255)}
#width and height of area of interest
w = 100 #100 meter
h = 200 #200 meter
NumberOfDots = 10
DotRadius = 20
NumberOfRuns = 3
Final = np.array([[colours[0] for x in range(w)] for y in range(h)])
Shadows = np.array([[colours[0] for x in range(w)] for y in range(h)])
for SensorNum in range(NumberOfRuns):
Shadows = np.array([[colours[0] for x in range(w)] for y in range(h)])
for dot in range(NumberOfDots):
ypos = random.randint(DotRadius, h-DotRadius)
xpos = random.randint(DotRadius, w-DotRadius)
for i in range(xpos - DotRadius, xpos + DotRadius):
for j in range(ypos - DotRadius, ypos + DotRadius):
if math.sqrt((xpos - i)**2 + (ypos - j)**2) < DotRadius:
Shadows[j][i] = colours[1]
im = Image.fromarray(Shadows.astype('uint8')).convert('RGBA')
im.save('result_test_image'+str(SensorNum)+'.png')
#This for loop below is the bottle-neck. Can its speed be improved?
if SensorNum > 0:
for i in range(w):
for j in range(h):
#White space dominates.
#(pixel by pixel) If the current images pixel is white and the unfinshed Final
#images pixel is blue then set the final pixel to white.
if np.all(Shadows[j][i]==colours[0]) and np.all(Final[j][i]==colours[1]):
Final[j][i] = colours[0]
else:
Final = copy.deepcopy(Shadows)
im = Image.fromarray(Final.astype('uint8')).convert('RGBA')
im.save('result_final_test.png')
The final nested for loop is what I am interested in improving. This works fine but the iteration is a huge bottle neck. Is there anyway to this quicker by using some vectoring etc?
Shadowsin contrast to what you say is not andarray. Could you please give a working example including all imported modules?ndarrayscan't holdtuples. Numpy is converting thetupleto a an array with shape(3, ). The calculation time for this is nearly 2 times more than using arrays.