簡體   English   中英

帶有 np.logical_and 的 numpy np.where 中的意外行為

[英]Unexpected behaviour in numpy np.where with np.logical_and

我想在用 Pillow 創建的 numpy 三維數組(X/Y/RGB)中找到一個 RGB 像素

conditions = np.logical_and(np.logical_and(array[:,:,0]==rgb[0],array[:,:,1]==rgb[1]),array[:,:,2]==rgb[2])
res = np.flip(np.transpose(np.where(conditions))).tolist()

它就像一個魅力。

但是,我想添加一個容差,所以我只是通過以下方式更改了條件:

abs(array[:,:,i]-rgb[i]) <= tolerance

但這不能按預期工作,它返回零而不是容忍范圍內的像素。 如何向我的上部代碼段添加容差?

您的代碼似乎正確識別給定容差內的值。

這是我的測試代碼:

import numpy as np
array = np.reshape(np.array([i%3 + (i//3) / 10 for i in range(27)]), (3,3,3))
print('array:', array, '', sep='\n')
rgb = [0,1,2]
for x in range(3):
    for y in range(3):
        print(f'x={x} y={y} rgb={array[x,y,:]}')

conditions = np.logical_and(np.logical_and(array[:,:,0]==rgb[0],array[:,:,1]==rgb[1]),array[:,:,2]==rgb[2])
print('', 'conditions:', conditions, sep='\n')
res = np.flip(np.transpose(np.where(conditions))).tolist()
print(res)
print('', 'res:', res, sep='\n')

tolerance = 0.35
conditions = np.logical_and(np.logical_and(abs(array[:,:,0]-rgb[0]) <= tolerance,abs(array[:,:,1]-rgb[1]) <= tolerance),abs(array[:,:,2]-rgb[2]) <= tolerance)
print('', f'conditions @ tolerance={tolerance}:', conditions, sep='\n')
res = np.flip(np.transpose(np.where(conditions))).tolist()
print(res)
print('', 'res:', res, sep='\n')

輸出:

array:
[[[0.  1.  2. ]
  [0.1 1.1 2.1]
  [0.2 1.2 2.2]]

 [[0.3 1.3 2.3]
  [0.4 1.4 2.4]
  [0.5 1.5 2.5]]

 [[0.6 1.6 2.6]
  [0.7 1.7 2.7]
  [0.8 1.8 2.8]]]

x=0 y=0 rgb=[0. 1. 2.]
x=0 y=1 rgb=[0.1 1.1 2.1]
x=0 y=2 rgb=[0.2 1.2 2.2]
x=1 y=0 rgb=[0.3 1.3 2.3]
x=1 y=1 rgb=[0.4 1.4 2.4]
x=1 y=2 rgb=[0.5 1.5 2.5]
x=2 y=0 rgb=[0.6 1.6 2.6]
x=2 y=1 rgb=[0.7 1.7 2.7]
x=2 y=2 rgb=[0.8 1.8 2.8]

conditions:
[[ True False False]
 [False False False]
 [False False False]]
[[0, 0]]

res:
[[0, 0]]

conditions @ tolerance=0.35:
[[ True  True  True]
 [ True False False]
 [False False False]]
[[0, 1], [2, 0], [1, 0], [0, 0]]

res:
[[0, 1], [2, 0], [1, 0], [0, 0]]

問題是在 PIL Image 上調用np.array()自動創建一個dtype=uint8 在我的邏輯測試期間,值可能會高於 255,因此出現意外行為

可以更改邏輯以使其工作,但array = np.array(im,dtype=np.int16)也可以解決問題(即使它的優化程度較低)

暫無
暫無

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

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