Issue
I have the following 2D-numpy array:
matrix = np.zeros((250, 250))
Now, at various coordinates, I want to replace not just the coordinate value but its local vicinity too with a smaller array. As exemplary replacement we can take a diamond:
import skimage.morphology
star = skimage.morphology.diamond(3) # small array / replacement
coords_r = np.random.randint(0, 250, 20) # row coordinates
coords_c = np.random.randint(0, 250, 20) # column coordinates
I came up with the following rather sloppy way and was wondering if there was a simpler / more elegant solution. Furthermore, this method will overwrite if two objects are close enough:
max_r, max_c = matrix.shape
obj = star
half_obj = int((star.shape[0])/2)
for r, c in zip(coords_r, coords_c):
curr_obj = obj
start_r = r-half_obj-1
end_r = r+half_obj
start_c = c-half_obj-1
end_c = c+half_obj
# Check if on corners
if r-half_obj-1 < 0:
start_r = 0
curr_obj = curr_obj[-r:, :]
if r+half_obj > matrix.shape[0]:
end_r = max_r
curr_obj = curr_obj[:max_r-start_r, :]
if c-half_obj-1 < 0:
start_c = 0
curr_obj = curr_obj[:, -c:]
if c+half_obj > matrix.shape[1]:
end_c = max_c
curr_obj = curr_obj[:, :max_c-start_c]
matrix[start_r:end_r, start_c:end_c] = curr_obj
Thanks in advance.
Solution
I asked similar question some time ago: Add small image to the canvas as numpy arrays
Here is my solution to your problem:
matrix_size = 250
star_size = 3
matrix = np.ones((matrix_size, matrix_size))
star = 1 - skimage.morphology.diamond(star_size)
coords_r = np.random.randint(0, matrix_size, 20) # row coordinates
coords_c = np.random.randint(0, matrix_size, 20) # column coordinates
for r, c in zip(coords_r, coords_c):
matrix[max(r - star_size, 0):r + star_size + 1, max(c - star_size, 0):c + star_size + 1] *= star[max(star_size - r, 0):star_size + matrix_size - r, max(star_size - c, 0):star_size + matrix_size - c]
matrix = 1-matrix
Answered By - Fallen Apart
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.