0

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!

nvaytet
  • 61
  • 6
  • Matplotlib can plot patches directly. Would that help you? – Joe Jun 04 '20 at 19:43
  • 1
    Does this answer your question? [Selecting multiple slices from a numpy array at once](https://stackoverflow.com/questions/43413582/selecting-multiple-slices-from-a-numpy-array-at-once) – Joe Jun 04 '20 at 19:45
  • Thanks @Joe. The end goal is to actually fill the 2D array, the image was there more for illustration. So using `matplotlib` patches doesn't help me. Thanks for linking the other post, i'll check it out! – nvaytet Jun 05 '20 at 07:52

0 Answers0