脾气暴躁–将小数组放在大数组的坐标处吗?

时间:2020-08-10 10:39:36

标签: python arrays numpy

我有以下2D-numpy数组:

matrix = np.zeros((250, 250))

现在,在各种坐标下,我不仅要用较小的数组替换坐标值,还要替换其局部附近的值。作为替代品,我们可以选择钻石:

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

我想出了以下相当草率的方法,并且想知道是否有一个更简单/更优雅的解决方案。此外,如果两个对象足够靠近,则此方法将覆盖:

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

谢谢。

3 个答案:

答案 0 :(得分:1)

您需要更好地利用numpy切片功能。据我了解,两个随机数组coords_r, coords_c是您要放置星星的中心坐标。我会

  1. 将其转换为矩形作物坐标列表
  2. 循环遍历坐标并将星星放置在每个切片中

类似

def center_to_bbox(coords, star_size):
    coords_x, coords_y = coords
    x1, y1, x2, y2 = coords_x - star_size, coords_y - star_size, coords_x + star_size + 1, 
    coords_y + star_size + 1,
    bboxes =(x1, y1, x2, y2)
    return bboxes
x_coords = np.random.randint(0, 250 - 3, 20)  
y_coords = np.random.randint(0, 250 - 3 , 20)
x1, y1, x2, y2 = bboxes
for x1_, y1_, x2_, y2_ in zip(x1, y1, x2, y2):
    matrix[y1_:y2_, x1_:x2_] = star

还请注意,您也可以减去恒星的尺寸,这样以后就不必在边界处进行补偿

答案 1 :(得分:1)

前段时间我问了类似的问题:Add small image to the canvas as numpy arrays

这是我为您解决的问题:

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

这就是我得到的: enter image description here

答案 2 :(得分:0)

似乎您可能想使用scipy sparse matrices。只需定义较小的矩阵并将其添加到较大的矩阵即可。 lil_matrix似乎是您正在寻找的合适格式。