如何快速从颜色词典更改图像中的像素? [英] How can I quickly change pixels in a image from a color dictionary?

查看:91
本文介绍了如何快速从颜色词典更改图像中的像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像,我想从一个颜色图中更改图像中的所有颜色. {(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,Pillow,图像,图像处理,量化,量化,特定调色板,给定调色板,指定调色板,已知调色板,重新映射,重新映射,颜色映射,映射,LUT ,linalg.norm.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆