如何使用numpy高效地初始化数组的各个部分?

2024-04-25 21:39:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图弄清楚是否可以使用numpy有效地将三维数组的一个区域设置为一个值。我的数组是一个有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更有效地完成我想做的事情


Tags: inimagenumpyfornpcolorr2c2