亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何選擇 NumPy 數組中的所有非黑色像素?

如何選擇 NumPy 數組中的所有非黑色像素?

揚帆大魚 2021-07-02 10:01:10
我正在嘗試使用 NumPy 獲取與特定顏色不同的圖像像素列表。例如,在處理以下圖像時:我設法使用以下方法獲得所有黑色像素的列表:np.where(np.all(mask == [0,0,0], axis=-1))但是當我嘗試這樣做時:np.where(np.all(mask != [0,0,0], axis=-1))我得到了一個非常奇怪的結果:看起來 NumPy 只返回了 R、G 和 B 非 0 的索引這是我正在嘗試做的一個最小的例子:import numpy as npimport cv2# Read maskmask = cv2.imread("path/to/img")excluded_color = [0,0,0]# Try to get indices of pixel with different colorsindices_list = np.where(np.all(mask != excluded_color, axis=-1))# For some reason, the list doesn't contain all different colorsprint("excluded indices are", indices_list)# Visualizationmask[indices_list] = [255,255,255]cv2.imshow(mask)cv2.waitKey(0)
查看完整描述

3 回答

?
Helenr

TA貢獻1780條經驗 獲得超4個贊

必要性:需要具有這種形狀的矩陣 = (any,any,3)


解決方案:


COLOR = (255,0,0)

indices = np.where(np.all(mask == COLOR, axis=-1))

indexes = zip(indices[0], indices[1])

for i in indexes:

    print(i)

解決方案2:


獲取特定顏色的間隔,例如 RED:


COLOR1 = [250,0,0]

COLOR2 = [260,0,0] # doesnt matter its over limit


indices1 = np.where(np.all(mask >= COLOR1, axis=-1))

indexes1 = zip(indices[0], indices[1])


indices2 = np.where(np.all(mask <= COLOR2, axis=-1))

indexes2 = zip(indices[0], indices[1])


# You now want indexes that are in both indexes1 and indexes2

解決方案 3 - 證明有效


如果以前的不起作用,那么有一種解決方案可以 100% 有效


從 RGB 通道轉換為 HSV。從 3D 圖像制作 2D 蒙版。2D 蒙版將包含色調值。比較色相比 RGB 更容易,因為色相是 1 個值,而 RGB 是具有 3 個值的向量。在您擁有帶有 Hue 值的 2D 矩陣后,請執行上述操作:


HUE1 = 0.5

HUE2 = 0.7 


indices1 = np.where(HUEmask >= HUE1)

indexes1 = zip(indices[0], indices[1])


indices2 = np.where(HUEmask <= HUE2)

indexes2 = zip(indices[0], indices[1])

您可以對 Saturation 和 Value 執行相同的操作。



查看完整回答
反對 回復 2021-07-13
?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

對于選擇非黑色像素的特殊情況,在查找非零像素之前將圖像轉換為灰度會更快:

non_black_indices = np.nonzero(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY))

然后將所有黑色像素更改為白色,例如:

img[non_black_indices] = [255,255,255]

同樣,這僅適用于選擇非 [0,0,0] 像素,但如果您正在處理數千張圖像,則較一般方法的速度提升變得顯著。


查看完整回答
反對 回復 2021-07-13
  • 3 回答
  • 0 關注
  • 281 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號