有没有一种方法可以使用Pillow将图像转换为HSL?

时间:2019-03-03 15:28:59

标签: python python-imaging-library

是否可以使用Python中的Pillow将图像转换为HSL?

理想情况下,我希望能够打开JPEG,将其转换为HSL,更改HSL值,转换回RGB并保存。

我唯一能想到的方法是在每个像素上使用colorsys.rgb_to_hls

1 个答案:

答案 0 :(得分:0)

枕头(5.4.1)不支持将RGB转换为HSL:

Python 3.7.2 (default, Dec 27 2018, 07:35:52)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
>>> im = Image.open("Tests/images/hopper.png")
>>> hsl = im.convert("HSL")
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/PIL/Image.py", line 1030, in convert
    im = self.im.convert(mode, dither)
ValueError: conversion from RGB to HSL not supported

但是,如果可以使用它,则支持RGB to HSV:

from PIL import Image

print("Open a JPEG")
im = Image.open("Tests/images/hopper.png")
px = im.load()
print(im.mode)  # "RGB"
print(px[0, 0])  # (20, 21, 67) ~= navy

print("Convert it to HSV")
hsv = im.convert("HSV")
px = hsv.load()
print(hsv.mode)  # "HSV"
print(px[0, 0])  # (169, 178, 67) ~= navy

print("Change an HSV value")
px[0, 0] = (0, 255, 255)  # red
print(px[0, 0])  # (0, 255, 255) == red

print("Convert back to RGB and save")
im2 = hsv.convert("RGB")
px = im2.load()
print(im2.mode)  # "RGB"
print(px[0, 0])  # (255, 0, 0) == red
im2.save("out.png")