我有一个具有3个颜色通道的图像(2D阵列)。像这样:
[[[128 197 254]
[128 197 254]
[128 197 254]
...
[182 244 255]
[182 244 255]
[182 244 255]]
[[128 197 254]
[128 197 254]
[128 197 254]
...
[182 244 255]
[182 244 255]
[182 244 255]]
[[128 197 254]
[128 197 254]
[128 197 254]
...
[182 244 255]
[182 244 255]
[182 244 255]]
...
[[128 197 254]
[128 197 254]
[128 197 254]
...
[182 244 255]
[182 244 255]
[182 244 255]]
[[128 197 254]
[128 197 254]
[128 197 254]
...
[182 244 255]
[182 244 255]
[182 244 255]]
[[128 197 254]
[128 197 254]
[128 197 254]
...
[182 244 255]
[182 244 255]
[182 244 255]]]
我想获取例如[255、255、255]的颜色的索引。我尝试使用np.where()
或np.argwhere()
,但它比较的是值而不是数组。最快,最有效的方法是什么?
答案 0 :(得分:3)
IIUC,您可以使用np.nonzero
np.nonzero((arr==255).all(axis=2))
这将返回表示索引的数组元组。如果你这样做
arr[ind]
其中ind
是第一个expr的返回值,您可以访问/修改所有255的所有行。
答案 1 :(得分:-1)
使用np.numpy可以做到这一点
import numpy as np
# Generating an example array
width = 100
height = 100
channels = 3
img = np.random.rand(width, height, channels) * 255
# Defining the three value channels
r=0
g=1
b=2
# Defining the query values for the channels, here [255, 255, 255]
r_query = 255
g_query = 255
b_query = 255
# Print a 2D array with the coordinates of the white pixels
print(np.where((img[:,:,r] == r_query) & (img[:,:,g] == g_query) & (img[:,:,b] == b_query)))
这将为您提供一个二维数组,其中包含原始数组(图像)中白色像素[255、255、255]的坐标。
注意:另一种方法是使用OpenCV
mask = cv2.inRange(img, [255, 255, 255], [255, 255, 255])
output = cv2.bitwise_and(img, img, mask = mask)