Ror*_*ory 3 python image imagemagick image-processing python-imaging-library
我想调整python中图像的颜色级别.我可以使用任何可以轻松安装在我的Ubuntu桌面上的python库.我想和ImageMagick一样-level(http://www.imagemagick.org/www/command-line-options.html#level).PIL(Python图像库)似乎没有它.我一直在调用convert图像然后再次读回文件,但这看起来很浪费.有更好/更快的方式吗?
如果我正确理解-levelImageMagick 的选项,那么level_image我提供的 功能应该做你想要的.
有两点需要注意:
代码:
import colorsys
class Level(object):
def __init__(self, minv, maxv, gamma):
self.minv= minv/255.0
self.maxv= maxv/255.0
self._interval= self.maxv - self.minv
self._invgamma= 1.0/gamma
def new_level(self, value):
if value <= self.minv: return 0.0
if value >= self.maxv: return 1.0
return ((value - self.minv)/self._interval)**self._invgamma
def convert_and_level(self, band_values):
h, s, v= colorsys.rgb_to_hsv(*(i/255.0 for i in band_values))
new_v= self.new_level(v)
return tuple(int(255*i)
for i
in colorsys.hsv_to_rgb(h, s, new_v))
def level_image(image, minv=0, maxv=255, gamma=1.0):
"""Level the brightness of image (a PIL.Image instance)
All values ? minv will become 0
All values ? maxv will become 255
gamma controls the curve for all values between minv and maxv"""
if image.mode != "RGB":
raise ValueError("this works with RGB images only")
new_image= image.copy()
leveller= Level(minv, maxv, gamma)
levelled_data= [
leveller.convert_and_level(data)
for data in image.getdata()]
new_image.putdata(levelled_data)
return new_image
Run Code Online (Sandbox Code Playgroud)
如果有一些方法可以使用PIL进行RGB→HSV转换(反之亦然),那么可以分割成H,S,V波段,使用V波段的.point方法并转换回RGB,加快进程很多; 但是,我还没有找到这样的方法.