Here is a sample of pixel loading.
Read the pixels of the original image → Process → Write the processed data It becomes the procedure such as.
Specifically, read pixels → convert to grayscale → convert to sepia tones → write pixels This process is performed for all pixels one by one.
I know there is a more efficient way.
The original image
Execution result
Runs on Python 2.7. It seems that PIL does not yet support Python 3 series.
image-sepia.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Filter to convert image to sepia
First argument:Input file name
Second argument:Output file name (optional)
Sepia is a black-brown paint made from squid ink, and making an image sepia-toned means making it look like it was drawn.
-Extract brightness information by grayscale
-Converts the whole to brownish
'''
import sys
import Image
def grayscale(r,g,b):
'''
Convert RGB values to grayscale (black and white)
'''
#NTSC weighted average method
gray = int(r * 0.298912 + g * 0.586611 + b * 0.114478)
#Simple averaging method
#gray = int((r+g+b)/3)
return gray
def sepiatone(r,g,b):
'''
Convert RGB values to sepia
There seems to be no rule to convert to sepia, so if it looks like that, it's OK.
'''
gray = grayscale(r,g,b)
#sr = int(gray * 0.9);sg = int(gray * 0.7);sb = int(gray * 0.4)
#sr = gray; sg = int(gray * 0.8);sb = int(gray * 0.6)
sr = int(gray * 0.8 + 2); sg = int(gray * 0.6 + 2);sb = int(gray * 0.4 + 2)
return sr,sg,sb
def make_image(infile, outfile):
'''
Convert image to sepia
'''
img = Image.open(infile)
img = img.convert("RGB")
x,y = img.size
for ly in range( y):
for lx in range( x):
r,g,b = img.getpixel((lx, ly))
sr,sg,sb = sepiatone(r,g,b)
img.putpixel((lx,ly), (sr,sg,sb))
#↓ If you want to make it look a little faded
#img.putpixel((lx,ly), ((r+sr)/2,(g+sg)/2,(b+sb)/2))
img.save(outfile)
return
def usage():
sys.stderr.write("Usage: %s infile [outfile] \n" % sys.argv[0])
return
if __name__ == '__main__':
argvs = sys.argv
argc = len(argvs)
#Argument check
if ((argc == 1 ) or (argc > 3)):
usage()
sys.exit(1)
if (argc > 2):
outfile = argvs[2]
else:
outfile = "output.png "
infile = argvs[1]
make_image(infile , outfile)
# EOF
Recommended Posts