Convert images to sepia toning with PIL (Python Imaging Library)

What do you want to do

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.

Execution result

The original image haku12.png

Execution result haku12sepia.png

script

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

Convert images to sepia toning with PIL (Python Imaging Library)
Convert PDFs to images in bulk with Python
Convert list to DataFrame with python
A sample for drawing points with PIL (Python Imaging Library).
PIL (Python Imaging Library) installation memorandum
Convert PIL format images read from form with Django to base64 format
Convert memo at once with Python 2to3
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
Convert FX 1-minute data to 5-minute data with Python
Add Gaussian noise to images with python2.7
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
Upload images to Google Drive with Python
Sample to convert image to Wavelet with Python
Library comparison summary to generate PDF with Python
Convert PDF to image (JPEG / PNG) with Python
Convert svg file to png / ico with Python
Convert Windows epoch values to date with python
Introduction of Python Imaging Library (PIL) using HomeBrew
Convert strings to character-by-character list format with python
Convert 202003 to 2020-03 with pandas
How to convert / restore a string with [] in python
Create an image file using PIL (Python Imaging Library).
Convert the image in .zip to PDF with Python
How to convert JSON file to CSV file with Python Pandas
PyInstaller memorandum Convert Python [.py] to [.exe] with 2 lines
I made a program to convert images into ASCII art with Python and OpenCV
Bordering images with python Part 1
[python] Convert date to string
Convert numpy int64 to python int
[Python] Convert list to Pandas [Pandas]
How to convert an array to a dictionary with Python [Application]
Connect to Wikipedia with Python
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
Post to slack with Python 3
Convert color space from RGB to CIELAB with PIL (Pillow)
Send experiment results (text and images) to slack with Python
Convert garbled scanned images to PDF with Pillow and PyPDF
Convert Scratch project to Python
[Python] Convert Shift_JIS to UTF-8
Switch python to 2.7 with alternatives
Write to csv with Python
Convert images passed to Jason Statham-like in Python to ASCII art
Save images on the web to Drive with Python (Colab)
Convert video to black and white with ffmpeg + python + opencv
Convert python 3.x code to python 2.x
Convert to a string while outputting standard output with Python subprocess
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda
Made it possible to convert PNG to JPG with Pillow of Python
I made a library to easily read config files with Python
Convert files written in python etc. to pdf with syntax highlighting
I tried to automatically collect images of Kanna Hashimoto with Python! !!
The fastest way to get camera images regularly with python opencv
[Python] Try to recognize characters from images with OpenCV and pyocr
Number recognition in images with Python
Convert .ipynb to .html (with BatchFile)
Python: How to use async with
Link to get started with python
Introduction to Python Numerical Library NumPy
[Python] Write to csv file with Python