我的脚本没有按我的预期运行。我的代码有问题吗?
from PIL import Image
import colorsys
def change_red_to_blue_hsl(image_path, output_path):
img = Image.open(image_path).convert('RGBA')
width, height = img.size
new_img = Image.new('RGBA', (width, height))
for x in range(width):
for y in range(height):
r, g, b, a = img.getpixel((x, y))
h, l, s = colorsys.rgb_to_hls(r/255., g/255., b/255.)
if (h >= 0 and h <= 1/6) or (h >= 5/6 and h <= 1):
h = (h + 4/6) % 1
r, g, b = colorsys.hls_to_rgb(h, l, s)
new_img.putpixel((x, y), (int(r*255), int(g*255), int(b*255), a))
new_img.save(output_path)
change_red_to_blue_hsl("C:\\color\\tes.png", "C:\\color\\tes_output.png")
期望(输入是
tes.png
和预期结果:红色调被蓝色调替换)。
结果
我尝试从各种来源进行搜索,但在处理颜色渐变的图像时,我还没有找到任何可以专门将红色变为蓝色的东西。
您的输入图像在 HSL 颜色空间中从左到右如下所示:
Red Orange Yellow
0,100,50 40,100,50 60,100,50
你的输出图像如下所示:
Blue Green Yellow
240,100,50 120,100,50 60,100,50
因此,饱和度和亮度是恒定的,但您希望将 0..60 范围内的色调映射到 240..60 范围内。所以,我想你想要:
newHue = 240 - 3*OldHue