如何从颜色字典快速更改图像中的像素? [英] How can I quickly change pixels in a image from a color dictionary?
问题描述
我有一个图像,我想从颜色图中更改图像中的所有颜色,例如.{(10,20,212):(60,40,112)...}
I have an image, I want to change all the colors in the image from a color map eg. {(10,20,212) : (60,40,112)...}
目前,我正在读取图像 OpenCV,然后迭代图像数组并更改每个像素,但这非常慢.
Currently, I am reading the image OpenCV and then iterating over the image array and changing each pixel, but this is very slow.
有什么办法可以更快地完成吗?
Is there any way I can do it faster?
推荐答案
对于这个问题,我提供了两个答案.这个答案更多地基于 OpenCV,另一个更多地基于 PIL/Pillow.结合我的其他答案阅读此答案,并可能混合搭配.
I am providing two answers to this question. This answer is more based in OpenCV and the other is more based in PIL/Pillow. Read this answer in conjunction with my other answer and potentially mix and match.
您可以使用 Numpy 的 linalg.norm()
找到颜色之间的距离,然后 argmin()
选择最近的.然后,您可以使用 LUT 查找表" 根据图像中的现有值查找新值.
You can use Numpy's linalg.norm()
to find the distances between colours and then argmin()
to choose the nearest. You can then use a LUT "Look Up Table" to look up a new value based on the existing values in an image.
#!/usr/bin/env python3
import numpy as np
import cv2
def QuantizeToGivenPalette(im, palette):
"""Quantize image to a given palette.
The input image is expected to be a Numpy array.
The palette is expected to be a list of R,G,B values."""
# Calculate the distance to each palette entry from each pixel
distance = np.linalg.norm(im[:,:,None] - palette[None,None,:], axis=3)
# Now choose whichever one of the palette colours is nearest for each pixel
palettised = np.argmin(distance, axis=2).astype(np.uint8)
return palettised
# Open input image and palettise to "inPalette" so each pixel is replaced by palette index
# ... so all black pixels become 0, all red pixels become 1, all green pixels become 2...
im=cv2.imread("image.png",cv2.IMREAD_COLOR)
inPalette = np.array([
[0,0,0], # black
[0,0,255], # red
[0,255,0], # green
[255,0,0], # blue
[255,255,255]], # white
dtype=np.uint8)
r = QuantizeToGivenPalette(im,inPalette)
# Now make LUT (Look Up Table) with the 5 new colours
LUT = np.zeros((5,3),dtype=np.uint8)
LUT[0]=[255,255,255] # white
LUT[1]=[255,255,0] # cyan
LUT[2]=[255,0,255] # magenta
LUT[3]=[0,255,255] # yellow
LUT[4]=[0,0,0] # black
# Look up each pixel in the LUT
result = LUT[r]
# Save result
cv2.imwrite('result.png', result)
输入图片
输出图像
关键字:Python、PIL、枕头、图像、图像处理、量化、量化、特定调色板、给定调色板、指定调色板、已知调色板、重新映射、重新映射、颜色映射、映射、LUT, 线性规范.
Keywords: Python, PIL, Pillow, image, image processing, quantise, quantize, specific palette, given palette, specified palette, known palette, remap, re-map, colormap, map, LUT, linalg.norm.
这篇关于如何从颜色字典快速更改图像中的像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!