給定一些任意輸入調色板,我如何將影像量化為給定的調色板?
雖然有很多使用 kmeans 的堆疊溢位解決方案,但我希望能夠使用專門在 opencv 中的預設調色板做類似的事情。例如,這可能包括使用聚類技術,其中 k 是固定的,并且質心由調色板預先確定,以便將每個像素分配給調色板中最接近的顏色。
例如,我想將一張圖片量化為最接近的白色、黑色、藍色、綠色和紅色顏色。
我的 BGR 調色板看起來像這樣:
palette = [
[0,0,0],
[255,0,0],
[0,255,0],
[0,0,255],
[255,255,255]
]
給定一些輸入圖片,我希望將圖片中的每個像素分配給上述調色板中最近的專案。
所以最終結果將如下所示:
import cv2
palette = [
[0,0,0],
[255,0,0],
[0,255,0],
[0,0,255],
[255,255,255]
]
def quantize_to_palette(image, palette):
# do something
# return the same image with all colors quantized to the nearest palette item
return
input = cv2.imread('input.jpg')
output = quantize_to_palette(image=input, palette=palette)
cv2.imwrite('output.jpg', output)
uj5u.com熱心網友回復:
您可以將其視為最近鄰問題,其中:
- 影像像素是一個點
- 調色板是一個索引
- 所有影像像素都是查詢
因此,您需要為每個查詢(影像中的一個像素)使用一定距離找到最近的調色板顏色。
原圖:
用你的調色板量化:
用一些隨機的 4 色調色板量化:
palette = np.random.randint(0, 255, size=(4, 3))
例子:
import cv2
import numpy as np
palette = np.array([[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]])
def quantize_to_palette(image, palette):
X_query = image.reshape(-1, 3).astype(np.float32)
X_index = palette.astype(np.float32)
knn = cv2.ml.KNearest_create()
knn.train(X_index, cv2.ml.ROW_SAMPLE, np.arange(len(palette)))
ret, results, neighbours, dist = knn.findNearest(X_query, 1)
quantized_image = np.array([palette[idx] for idx in neighbours.astype(int)])
quantized_image = quantized_image.reshape(image.shape)
return quantized_image
input = cv2.imread("tiger.png")
output = quantize_to_palette(image=input, palette=palette)
cv2.imwrite("output.jpg", output)
您也可以考慮使用其他距離和色彩空間。例如,與 LAB 顏色空間的 L2 距離更好地反映了人如何感知顏色相似性。
https://en.wikipedia.org/wiki/CIELAB_color_space#Perceptual_differences
圖片取自https://www.publicdomainpictures.net/en/view-image.php?image=156214
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/506597.html
上一篇:如何打破子行程內的while回圈