NumPy:如何检查元组是否在1D NumPy数组中



我在尝试检查python元组是否在一维numpy数组中遇到了一些麻烦。我正在做一个循环,它会记录图像中出现的所有颜色,并将它们存储到一个数组中。使用普通列表可以很好地工作,但是图像非常大,我认为NumPy数组将加快循环,因为它需要几分钟才能完成循环。

代码如下:

from PIL import Image
import numpy as np
img = Image.open("bg.jpg").convert("RGB")
pixels = img.load()
colors = np.array([])
for h in range(img.size[1]):
for w in range(img.size[0]):
if pixels[w,h] not in colors:
colors = np.append(colors, pixels[w,h])
else:
continue

当我运行这个时,我得到以下错误:

DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
if pixels[w,h] in colors:

提前感谢,如果你知道更快的方法,请告诉我。

我不确定你到底需要什么。但是我希望下一段代码会对你有所帮助。

import numpy as np
image = np.arange(75).reshape(5, 5, 3) % 8
# Get the set of unique pixles
pixel_list = image.reshape(-1, 3)
unique_pixels = np.unique(pixel_list, axis = 0)
# Test whether a pixel is in the list of pixels:
i = 0
pixel_in_list = (unique_pixels[i] == pixel_list).all(1).any(0)
# all(1) - all the dimensions (rgb) of the pixels need to match
# any(0) - test if any of the pixels match
# Test whether any of the pixels in the set is in the list of pixels:
compare_all = unique_pixels.reshape(-1, 1, 3) == pixel_list.reshape(1, -1, 3)
pixels_in_list = compare_all.all(2).any()
# all(2) - all the dimensions (rgb) of the pixels need to match
# any()  - test if any of the pixelsin the set matches any of the pixels in the list

我发现了一种更快的方法,使我的循环运行得更快,没有NumPy,那就是通过使用sets,这比使用列表或NumPy快得多。这就是代码现在的样子:

from PIL import Image
img = Image.open("bg.jpg").convert("RGB")
pixels = img.load()
colors = set({})
for h in range(img.size[1]):
for w in range(img.size[0]):
if pixels[w,h] in colors:
continue
else:
colors.add(pixels[w,h])

这解决了我最初的列表循环太慢的问题,并且它解决了NumPy无法比较元组的第二个问题。谢谢所有的回复,祝你有美好的一天。

假设pixels的形状为(3, w, h)(3, h, w)(即,颜色通道沿第一个轴),并假设您所追求的是图像中的唯一颜色:

channels = (channel.flatten() for channel in pixels)
colors = set(zip(*channels))

如果你想要一个list而不是colors = list(set(zip(*channels))).

你似乎误解了numpy的用处。元组的numpy数组不会比Python的元组列表快。numpy的速度在矩阵和向量的数值计算中起作用。元组的numpy数组不能利用numpy这么快的任何东西。

你要做的只是不适合用于numpy,并且根本不会帮助加快你的代码。

最新更新