回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>这是一个后续问题:<a href="https://stackoverflow.com/questions/29433243/convert-image-to-specific-palette-using-pil-without-dithering">Convert image to specific palette using PIL without dithering</a></p>
<p>我也想创建一个脚本,它可以将图像转换为一组特定的颜色,而不必进行抖动。在</p>
<p>我已经实现了“自定义量化”功能,作为问题的答案。除了一个大问题外,大多数脚本都运行良好。在</p>
<p>浅绿色的RGB(130190,40)被浅棕色的RGB(166、141、95)代替。<em>(见鬃毛左上角的浅绿色。)</em></p>
<pre><code>from PIL import Image
def customConvert(silf, palette, dither=False):
''' Convert an RGB or L mode image to use a given P image's palette.
PIL.Image.quantize() forces dither = 1.
This custom quantize function will force it to 0.
https://stackoverflow.com/questions/29433243/convert-image-to-specific-palette-using-pil-without-dithering
'''
silf.load()
# use palette from reference image made below
palette.load()
im = silf.im.convert("P", 0, palette.im)
# the 0 above means turn OFF dithering making solid colors
return silf._new(im)
palette = [
0,0,0,
0,0,255,
15,29,15,
26,141,52,
41,41,41,
65,105,225,
85,11,18,
128,0,128,
135,206,236,
144,238,144,
159,30,81,
165,42,42,
166,141,95,
169,169,169,
173,216,230,
211,211,211,
230,208,122,
245,245,220,
247,214,193,
255,0,0,
255,165,0,
255,192,203,
255,255,0,
255,255,255
] + [0,] * 232 * 3
# a palette image to use for quant
paletteImage = Image.new('P', (1, 1), 0)
paletteImage.putpalette(palette)
# open the source image
imageOrginal = Image.open('lion.png').convert('RGB')
# convert it using our palette image
imageCustomConvert = customConvert(imageOrginal, paletteImage, dither=False).convert('RGB')
</code></pre>
<p>CIE76三角洲-E:</p>
<p>当前:RGB(130190,40)-->;RGB(166,141,95)=57.5522</p>
<p>预期值:RGB(130190,40)-->;<strong>RGB(144238144)</strong>=31.5623</p>
<hr/>
<p>有人能解释一下如果我写的代码不正确或建议如何让它工作。在</p>
<p><a href="https://i.stack.imgur.com/Af4n4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Af4n4.png" alt="Original Image"/></a>
<a href="https://i.stack.imgur.com/9dzem.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9dzem.png" alt="Custom Convert"/></a></p>