[英]How to replace all RGB values in an Numpy Image Arrray based on an Target Pixel
我在 Numpy 數組中有一個圖像。 我將用黑色替換特定顏色,並將所有其他顏色替換為白色。 For 循環會變慢,我的 numpy 條件不起作用。
與數組匹配的所有像素 --> [121, 112, 131] 必須完全替換為另一個數組 --> [0, 0, 0]
所有其他帶有 --> [255, 255, 255]
我的結果以與第一通道匹配的監督像素結束 [True, False, False]
抱歉拼寫錯誤,我希望我的代碼更好理解。
我的示例結果:
import numpy as np
from scipy import misc
file = misc.face()
img = np.array(file)
target_color = [121, 112, 131]
true_color = [0, 0, 0]
false_color = [255, 255, 255]
true_mask = np.all(img == target_color, axis=2)
false_mask = np.all(img != target_color, axis=2)
img[true_mask] = true_color
img[false_mask] = false_color
print(img)
Output:
array([[[ 0, 0, 0],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
...,
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[121, 157, 96],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
...,
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]], dtype=uint8)
問題:
當第一個通道等於目標顏色時,還有像素。
Target Pixel: [121, 112, 131]
Overseen Pixel: [121, 157, 96]
您的圖像形狀是(768, 1024, 3)
。 您想要制作一個掩碼,它等於一個 3 元素數組。 您發現這樣做的正確方法是
mask = np.all(img == target_color, axis=2)
這是有效的,因為形狀是從最右邊的維度廣播的。 您無需計算img != target
即可獲得逆掩碼:
false_mask = ~mask
但你不需要這樣做。 您可以創建 output 陣列:
img = np.full_like(img, [255, 255, 255])
您可以設置被屏蔽的元素:
img[mask, :] = [0, 0, 0]
index :
很重要,因為您需要告訴它沿第三維處理所有內容,而掩碼處理前兩個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.