首页 > 解决方案 > 如何使用 numpy 有效地初始化数组的一部分?

问题描述

我想弄清楚我是否可以使用 numpy 有效地将 3 维数组的区域设置为一个值。我的数组是具有 3 个颜色通道的黑色图像,我想将图像中一组像素周围的区域设置为某种颜色。

我的工作但缓慢的代码是这样的(提取的相关部分):

import skimage
import numpy as np

def clamp(n, upper, lower=0):
    return max(lower, min(n, upper))

def apply_contours(image, contours, color=(128.0,128.0,128.0), radius=5):
    """Draw the pixels in the contours in a given colour and size
    """
    for contour in contours:
        for pixel in contour:
            r1 = clamp(int(pixel[0])-radius, image.shape[0])
            r2 = clamp(int(pixel[0])+radius, image.shape[0])
            c1 = clamp(int(pixel[1])-radius, image.shape[1])
            c2 = clamp(int(pixel[1])+radius, image.shape[1])
            for y in range(r1,r2):
                for x in range(c1,c2):
                    for c in range(3):
                        image[y][x][c] = color[c]
    return image

input = skimage.io.imread("image.png")
contours = skimage.measure.find_contours(input, 0.5)
mask = np.zeros((input.shape[0],input.shape[1],3), dtype=np.uint8)
apply_contours(mask)

我没有太多使用 numpy,但我想到我应该可以通过用apply_contours类似这样的东西替换嵌套循环来加快速度:

image[r1:r2][c1:c2] = np.array([color[0],color[1],color[2])

但这似乎不起作用,因为生成的图像确实显示了任何变化,而循环版本显示了我的期望。

我也试过:

image[r1:r2][c1:c2][0] = color[0]
image[r1:r2][c1:c2][1] = color[1]
image[r1:r2][c1:c2][2] = color[2]

但这给了我一个错误IndexError: index 0 is out of bounds for axis 0 with size 0

是否有可能用 numpy 更有效地做我想做的事情?

标签: pythonnumpy

解决方案


我想通了,我在 numpy 的总 n00b 状态。正确的语法是:

image[r1:r2,c1:c2] = np.array([color[0],color[1],color[2])

推荐阅读