簡體   English   中英

如何有效地遍歷每個像素以節省 numpy 的時間?

[英]How to effectively loop through each pixel for saving time with numpy?

如您所知,遍歷每個像素並使用 opencv 訪問它們的值需要很長時間。 作為初學者,我嘗試自己學習 opencv 當我嘗試這種方法時,我花了大約 7-10 秒的時間來遍歷圖像並執行操作。

代碼如下

original_image = cv2.imread(img_f)

image = np.array(original_image)
for y in range(image.shape[0]):
    for x in range(image.shape[1]):
        # remove grey background
        if 150 <= image[y, x, 0] <= 180 and \
                150 <= image[y, x, 1] <= 180 and \
                150 <= image[y, x, 2] <= 180:
            image[y, x, 0] = 0
            image[y, x, 1] = 0
            image[y, x, 2] = 0

        # remove green dashes
        if image[y, x, 0] == 0 and \
                image[y, x, 1] == 169 and \
                image[y, x, 2] == 0:
            image[y, x, 0] = 0
            image[y, x, 1] = 0
            image[y, x, 2] = 0

在上面的代碼中,我只是想刪除灰色和綠色像素 colors。

我在這里發現了類似的問題,但我無法理解如何在我的用例中使用 numpy,因為我是 python 和 numpy 的初學者。

解決此問題的任何幫助或建議將不勝感激謝謝

您可以利用 NumPy 的矢量化操作來消除所有循環,這應該會更快。

# Remove grey background
is_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)
image = np.where(is_grey, 0, image)

# Remove green dashes
is_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)
is_green_dash = is_green_dash[..., np.newaxis]  # append a new dim at the end
image = np.where(is_green_dash, 0, image)

np.where的兩次調用都依賴於 NumPy 的廣播

您可以對圖像應用 numpy 過濾。 在您的場景中,它將是:

mask_gray = (
    (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & 
    (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & 
    (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)
)

image[mask_gray] = 0

mask_green = (
    (image[:, :, 0] == 0) &
    (image[:, :, 1] == 169) &
    (image[:, :, 2] == 0)
)

image[mask_green] = 0

mask_graymask_green這里是 boolean 個面具

如果您堅持編寫自己的循環...

你可以只使用numba 它是 Python 代碼的 JIT 編譯器。

from numba import njit

@njit
def your_function(input):
    ...
    return output

input = cv.imread(...) # yes this will shadow the builtin of the same name
output = your_function(input)

第一次調用your_function時,編譯需要一秒鍾。 所有進一步的呼叫都非常快。

暫無
暫無

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

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