更改图像的调色板

问题描述

我正在尝试编写一个程序来将图像的调色板转换为自定义的预定调色板。 不幸的是它不起作用,我认为问题在于我如何转换颜色。对于它,我只是将每个像素的 RGB 值与自定义调色板的 RGB 值进行比较,然后将像素颜色替换为与原始 RGB 值差异最小的 RGB。

import PIL,math,numpy
from colormap import hex2rgb
from colormap import rgb2hex
from PIL import Image

rgb_pallete_r,rgb_pallete_g,rgb_pallete_b = [],[],[] # creates list for the rgb values of the custom palette
hex_pallete = list(colour_map) # creates list of all the hex values from the palette
for i in range(0,len(hex_pallete)): # adds the individual rgb for each palette colour to there respective list 
  rgb_pallete_r.append(hex2rgb(hex_pallete[i])[0])
  rgb_pallete_g.append(hex2rgb(hex_pallete[i])[1])
  rgb_pallete_b.append(hex2rgb(hex_pallete[i])[2])
  
def convert_image(path,height,width):

  colour = []
  image = Image.open(path) # load image using PIL
  new_image = image.resize((width,height)) # resize image so it is the desired height and width in pixels 
  
  for x in range(width): # loops through all the pixels on the x axis
   for y in range(height): # loops though all the pixels on the y axis 
       r,g,b = new_image.getpixel((x,y)) # gets r g b colour value for the pixel

       colour.append(r),colour.append(g),colour.append(b) # add r g b value to respecctive list for later
       new_image.putpixel((x,y),replace_colour(r,b)) # replaces pixel with new colour
        
  result = new_image.resize(image.size,Image.NEAREST) # resizes image to orginal size
  result.show() # shows image

def replace_colour(r,b):


  holding_colours,log = [],[] #holds all the distances and there index

  hex_pallete = list(colour_map) #gets the hex values of the colours from the dictorary
  for i in range(0,len(hex_pallete)): # loops through all the colour in the pallete   
    distance = math.sqrt(abs((rgb_pallete_r[i]-r)^2+(rgb_pallete_g[i]-g)^2+(rgb_pallete_b[i]-b)^2)) # calculates distance from pixel rgb to pallete rgb
    holding_colours.append(distance) # adds the distance to a list 
    log.append(i) # adds there index to a seperate list 

  new_colour = numpy.argmin(holding_colours) # return the smallest distance 
  print(rgb_pallete_r[new_colour],rgb_pallete_g[new_colour],rgb_pallete_b[new_colour])# for debugging
  return rgb_pallete_r[new_colour],rgb_pallete_b[new_colour]# returns the new rgb

我不太确定我做错了什么,但我认为它要么是我计算距离的地方,要么是我返回值的地方。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)