簡體   English   中英

如何用numpy有效地初始化數組的部分?

[英]How to efficiently initialize parts of an array with 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做更有效的事情嗎?

我想通了,我的n00b總狀態是numpy。 正確的語法是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM