簡體   English   中英

如果 numpy 圖像陣列中的像素顏色比任何其他顏色更接近調色板中的一種顏色,如何有效地更新該像素的顏色?

[英]How do I efficiently update the color of a pixel in a numpy image array if it is closer to one color in a palette than any other color?

假設我有一個用於圖像img的 numpy 數組:

import numpy as np

img = np.random.rand(100,100,3) * 255

以及 colors 的列表, palette

white = np.array([255,255,255])
red = np.array([255,0,0])
blue = np.array([0,0,255])
palette = np.array([white, red, blue])

如何創建一個新的圖像數組new_img ,其中每個像素通過歐幾里得距離比調色板中的任何其他 colors 更接近白色( [255,255,255] )並且所有其他像素顏色保留為是。 (能夠改變距離函數會很好,但不是硬性要求。)

我可以通過迭代每個像素的for循環以幼稚的方式做到這一點,但它當然比它可能需要的要慢得多。

首先找到每個向量的距離,然后找到最小距離的索引。

import numpy as np

img = np.random.rand(100,100,3) * 255
white = np.array([255,255,255])
red = np.array([255,0,0])
blue = np.array([0,0,255])
palette = np.array([white, red, blue])

palette_type = np.linalg.norm(img[...,None,:]-palette[:,:], axis=-1).argmin(axis=-1) ## 0 stands for white, 1 for red and 2 for blue.

new_img  = palette[palette_type]

感謝 Murali 提供了極大幫助的解決方案 我拿了那個:

import numpy as np

img = np.random.rand(100,100,3) * 255
white = np.array([255,255,255])
red = np.array([255,0,0])
blue = np.array([0,0,255])
palette = np.array([white, red, blue])

palette_type = np.linalg.norm(img[...,None,:]-palette[:,:], axis=-1).argmin(axis=-1) ## 0 stands for white, 1 for red and 2 for blue.

new_img  = palette[palette_type]

並添加了幾行,通過使白色像素透明並將所有其他像素保持為其原始顏色,使其更進一步:

mask = np.all(new_img == white, axis=-1)
img_copy = img.copy()
img_copy[mask] = white
h,w, _ = img_copy.shape
transparent_img = np.dstack((img_copy, np.zeros((h,w),dtype=np.uint8)+255))
masked_white = (transparent_img[:, :, 0:3] == white).all(2)
transparent_img[masked_white] = [0,0,0,0]

暫無
暫無

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

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