我在嘗試檢查 python 元組是否在一維 numpy 陣列中時遇到了一些麻煩。我正在研究一個回圈,它將記錄影像中存在的所有顏色并將它們存盤到一個陣列中。使用普通串列效果很好,但影像非常大,我認為 NumPy Arrays 會加速回圈,因為完成回圈需要幾分鐘。
代碼如下所示:
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:
提前致謝,如果您知道更快的方法,請告訴我。
uj5u.com熱心網友回復:
我不確定你到底需要什么。但我希望下一段代碼對你有所幫助。
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
uj5u.com熱心網友回復:
我找到了一種更快的方法來使我的回圈在沒有 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 無法比較元組的第二個問題。謝謝大家的回復,祝大家有個美好的一天。
uj5u.com熱心網友回復:
假設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,并且根本無助于加速您的代碼。
uj5u.com熱心網友回復:
如何檢查元組是否在一維numpy陣列中:
>>> colors = [(1,2,3),(4,5,6)]
>>> for x in colors:
print(x)
if isinstance(x, tuple):
print("is tuple")
(1, 2, 3)
is tuple
(4, 5, 6)
is tuple
但是您應該使用串列而不是 numpy 陣列。錯誤很明顯,該功能已被棄用。這是對標題中提出的問題的回答。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/335469.html
