Last active
June 21, 2019 14:54
-
-
Save yoya/1499c6559748fb6759040b2dfca625f8 to your computer and use it in GitHub Desktop.
PIL Grayscale improve
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# (c) yoya@awm.jp 2019/06/20- | |
# ref) https://pillow.readthedocs.io/en/stable/reference/Image.html | |
import sys | |
from PIL import Image | |
_rgb2xyz_rec709 = ( | |
0.412453, 0.357580, 0.180423, 0, | |
0.212671, 0.715160, 0.072169, 0, # RGB mixing weight | |
0.019334, 0.119193, 0.950227, 0 ) | |
_gamma22LUT = [pow(x/255.0 , 2.2) * 255 for x in range(256)] * 3 | |
_gamma045LUT = [pow(x/255.0 , 1.0/2.2) * 255 for x in range(256)] | |
def grayscale(im): | |
if im.mode != "RGB": # mainly, care for mode=="P" | |
im = im.convert("RGB") | |
im = im.point(_gamma22LUT) # sRGB to linear (approximate value 2.2) | |
im_gray = im.convert("L", _rgb2xyz_rec709) | |
return im_gray.point(_gamma045LUT) # linear to sRGB | |
# main | |
_,infile,outfile = sys.argv | |
im = Image.open(infile) | |
im_gray = grayscale(im) | |
im_gray.save(outfile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment