Python --Reduce photos beautifully with antialiasing

Applying anti-aliasing will reduce the jerkyness when reducing the photo. This is a Python code that reduces the photo files in a folder at once while maintaining the aspect ratio (aspect ratio), applies antialiasing, and saves them.

Comparison with / without anti-alias

I reduced the photos of about 4000px to 300px and compared them. In the bird image with AA, the small sand on the ground is hard to see because the color is integrated with the ground.

スクリーンショット 2015-11-19 21.03.02.png スクリーンショット 2015-11-19 21.03.06.png

Installation

#Install PIL
pip install PIL --allow-external PIL --allow-unverified PIL

Enlargement and reduction code

Confirmed to work only in python2.7 environment of mac

resize.py



# -*- coding: utf-8 -*-
import commands
import Image
import re

#Image height pixels when shrinking
PHOTO_HEIGHT = 300

#Full path of the folder containing the image
BASE_DIR = "/Users/XXXXX/Desktop/Photos"

#Image regular expression name
PHOTO_REGEX = r"P.*.[jpg|JPG]"

#Image prefix after resizing
PHOTO_RESIZE_PREFIX = "r_"


def main():
    #Get full image path
    _cmd = "cd {} && ls".format(BASE_DIR)
    l = commands.getoutput(_cmd)
    l = l.split("\n")
    l = [_l for _l in l if re.match(PHOTO_REGEX, _l)]

    #Generate a folder for output
    commands.getoutput("mkdir {}/output".format(BASE_DIR))

    #Read an existing file in read mode
    for _l in l:
        before_path = '{}/{}'.format(BASE_DIR, _l)
        filename = '{}{}'.format(PHOTO_RESIZE_PREFIX, _l)
        after_path = '{}/output/{}'.format(BASE_DIR, filename)
        resize(before_path, after_path, filename=_l)  #Shrink


def resize(before, after, height=PHOTO_HEIGHT, filename="", aa_enable=True):
    """
Resize the image
    :param str before:Original image file path
    :param str after:Image file path after resizing
    :param int height:Image height after resizing
    :param bool aa_enable:Whether to enable antialiasing
    :return:
    """
    #Open image readonly
    img = Image.open(before, 'r')
    #Calculate image pixels after resizing
    before_x, before_y = img.size[0], img.size[1]
    x = int(round(float(height / float(before_y) * float(before_x))))
    y = height
    resize_img = img
    if aa_enable:
        #Shrink with antialiasing
        resize_img.thumbnail((x, y), Image.ANTIALIAS)
    else:
        #Shrink without antialiasing
        resize_img = resize_img.resize((x, y))

    #Save the resized image
    resize_img.save(after, 'jpeg', quality=100)
    print "RESIZED!:{}[{}x{}] --> {}x{}".format(filename, before_x, before_y, x, y)

#Run
main()

Execution result


>>> python resize.py
RESIZED!:P1040673.jpg[4592x3448] --> 400x300
RESIZED!:P1050388.JPG[4592x3448] --> 400x300
RESIZED!:P1050389.JPG[4592x3448] --> 400x300
RESIZED!:P1050390.JPG[4592x3448] --> 400x300
RESIZED!:P1050391.JPG[4592x3448] --> 400x300
RESIZED!:P1050392.JPG[4592x3448] --> 400x300
RESIZED!:P1050393.JPG[4592x3448] --> 400x300
RESIZED!:P1050394.JPG[4592x3448] --> 400x300

Recommended Posts

Python --Reduce photos beautifully with antialiasing
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
Twilio with Python
Play with 2016-Python
Tested with Python
with syntax (Python)
Bingo with python
Excel with Python
Microcomputer with Python
Cast with python
Serial communication with Python
Zip, unzip with python
Django 1.11 started with Python3.6
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
Learning Python with ChemTHEATER 03
Sequential search with Python
"Object-oriented" learning with python
Run Python with VBA
Handling yaml with python
Solve AtCoder 167 with python
Serial communication with python
[Python] Use JSON with Python
Learning Python with ChemTHEATER 05-1
Learn Python with ChemTHEATER
1.1 Getting Started with Python
Binarization with OpenCV / Python
3. 3. AI programming with Python
Kernel Method with Python
Non-blocking with Python + uWSGI
Scraping with Python + PhantomJS
Posting tweets with python
Drive WebDriver with python
Use mecab with Python3
Voice analysis with python
Think yaml with python
Operate Kinesis with Python
Getting Started with Python
Use DynamoDB with Python
Zundko getter with python
Handle Excel with python
Ohm's Law with Python
Primality test with python
Run Blender with python
Solve Sudoku with Python
Python starting with Windows 7
Heatmap with Python + matplotlib
Multi-process asynchronously with python
Python programming with Atom
Use Python 3.8 with Anaconda
Competitive programming with python
Handle rabbimq with python
GRPC starting with Python