I have a set of patches, which each have a value or color, and I would like to apply/print them onto a 2D (image) numpy array. I know the size of each patch in x
and y
.
I can achieve what I want by doing
import numpy as np
import matplotlib.pyplot as plt
N = 150
M = 100
image = np.zeros([M, N])
istart = [10, 17, 88, 2, 34]
iend = [12, 23, 120, 19, 106]
jstart = [44, 1, 5, 95, 72]
jend = [47, 8, 26, 99, 73]
values = [1, 2, 3, 4, 5]
for k in range(len(istart)):
image[jstart[k]:jend[k]+1, istart[k]:iend[k]+1] += values[k]
fig, ax = plt.subplots()
ax.imshow(image)
fig.show()
where my image is 150x100 pixels and I have 5 patches. The istart
and iend
represent the start and end image pixel indices, respectively, in the x
direction for each patch. The jstart
and jend
are the equivalent for the y
direction.
The resulting image is here.
My problem is that the for
loop is slow when I have a large number of patches.
Is there a way to achieve this in a one-liner that would avoid the for
loop? I have tried to use numpy.add.at()
after having read this post, but I can only manage to get it working for one patch at a time.
Is there any way fancy indexing can be used in this case?
Many thanks for any help!