我有兩個陣列。一個是影像陣列,另一個是調色板陣列。兩者都有包含 8 位 RGB 通道的元素。我需要用調色板中最接近的顏色替換影像中的每種顏色。
目前我正在測量 RGB 空間中的距離,這并不理想,但易于實作。
這是我的實作:
image_array = np.array(image) # converts PIL image, values are uint8
# palette values are also 8-bit but I use int so I don't have to cast types
palette_array = np.array(palette, dtype=[('red', np.int), ('green', np.int), ('blue', np.int)])
mapped_image = np.empty((image_height, image_width, 3), dtype=np.uint8)
for x in range(image_width):
for y in range(image_height):
r, g, b = image_array[y, x]
distances_squared = (r-palette['red'])**2 (g-palette['green'])**2 (b-palette['blue'])**2
closest_index = np.argmin(distances_squared)
closest_color = palette.flat[closest_index]
mapped_image[y, x] = closest_color
調色板有 4096 種隨機顏色(無法進行簡單轉換)。映射 600x448 大小的影像時,即使在我的核心 i5 機器上也需要大約一分鐘。我計劃在像樹莓派這樣的低端設備上使用它,映射一個小影像大約需要 3 分鐘。
這太慢了。我相信當使用 numpy 語法實作完整回圈時,這可以大大加快速度,但我不知道如何做到這一點。
如何從原始影像到映射的影像都使用 numpy 語法實作?
uj5u.com熱心網友回復:
您可以嘗試使用 scipy 中的 cKDTree 函式。
import numpy as np
from scipy.spatial import cKDTree
palette=np.random.randint(0, 255, size=(4096,3), dtype=np.uint8) # random palette
image_in=np.random.randint(0, 255, size=(800, 600, 3), dtype=np.uint8) # random image
size=image_in.shape
vor=cKDTree(palette)
test_points=np.reshape(image_in, (-1,3))
_, test_point_regions = vor.query(test_points, k=1)
image_out=palette[test_point_regions]
np.reshape(image_out, size)
該程式運行大約 0.8 秒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519865.html
上一篇:如何在ASP.NETCore6.0中撰寫單元測驗友好的代碼?
下一篇:XYZ坐標到XY網格
