我有一個包含 RGB 像素的影像。我有一個meaningful_pixels: List[Tuple(int, int, int)]我認為是有意義的資訊的像素串列,我想將所有其他像素設定為白色(255, 255, 255)
這是原圖

我正在嘗試將其轉換為

我已經成功創建了“允許像素”串列,它是左上角矩形的“紫色到黃色”漸變,它存盤在meaningful_pixels形狀變數中(num_of_pixels,3)。
我可以通過創建蒙版并使用它來更改像素來洗掉黑色矩形
# actual code
mask = np.all(image == [0, 0, 0], axis=-1)
image[mask] = [255, 255, 255]
但是當我有一個值串列而不是一個值時,我不知道如何創建一個掩碼。
我能夠使用 for 回圈來完成它,但性能非常糟糕。我需要幫助來使用 numpy“矢量化”方法來實作最高性能。就像是:
#pseudocode
image = np.remove_value_if_not_in_list(image, allowed_pixels)
解決方案
# creates mask of "allowed pixels"
mask = np.all(np.isin(img, allowed_pixels) == [True, True, True], axis=-1)
# use inverted mask to replace pixels with white
img[~mask] = [255, 255, 255]
uj5u.com熱心網友回復:
我將numpy.where()用于類似的程序。我也將它與numpy.isin()結合起來,這將實作你想要的。
代碼示例類似于:
import numpy as np
#pseudocode
image = np.where(np.isin(image, list_of_exlusions), image, mask_value)
uj5u.com熱心網友回復:
您可以使用np.vectorizePython 函式并將其應用于ndarrayusing 廣播。
def is_not_meaningful_pixel(pixel):
return pixel not in meaningful_pixels
mask = np.vectorize(is_not_meaningful_pixel)(image)
image[mask] = (255, 255, 255)
這是一個更具體的資料示例:
BAD_VALUES = (2, 3, 4)
REPLACEMENT_VALUE = 99
data = np.arange(7)
def condition(val):
return val in BAD_VALUES
vectorized_condition = np.vectorize(condition)
mask = vectorized_condition(data)
data[mask] = REPLACEMENT_VALUE
print(data)
# output
[ 0 1 99 99 99 5 6]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317017.html
上一篇:通過numpy陣列索引和
下一篇:【Rails】acts_as_paranoid環境,我想物理洗掉使用relationdependent的記錄::destroy
