[Python3] Code that can be used when you want to cut out an image in a specific size

Accumulation in the sense of memorandum and OUTPUT

Purpose of creation

Code to use when you want to crop all working images

Creation environment

・ Windows10 ・ Anaconda3 ・ Python3.7 ・ Jupyter Notebook


① Enter the name of the folder you want to crop ② If there is no folder, create a crop_folder in the current_folder and crop the image. ③ If the same folder name already exists, an error will occur to prevent erroneous operation.

Loading the library

All Necessary Libraries.py

import pathlib
import os
import shutil
import pprint
import numpy as np
from glob import glob
from PIL import Image
from tqdm import tqdm
from pathlib import Path



#Enter the folder name
folder_name = input('Enter the folder name :')
p = Path('C:/Users/H3051411/OUT/' + folder_name)
new_folder_name = '_crop_folder'
#New png from current path_Create folder
new_folder_path = os.path.join(p, new_folder_name)

#If there is no folder, copy and create
if not os.path.exists(new_folder_path):
    #Get the files in the directory
    #Convert new path extension to png file
    new_p = Path(new_folder_path)
    files = list(p.glob('*.*'))
    for i,f in tqdm(enumerate(files)):
        print('Number of image crops:{0}/{1}'.format(i+1,len(files)))
        img = Image.open(f)
        imgname = os.path.basename(f)
        newfname = 'crop_' + imgname
        # .crop((Upper left x,Upper left y,Lower right x,Lower right y))Specified by.
        #The upper left coordinates are(x, y) = (left, upper), The lower right coordinates are(x, y) = (right, lower)Corresponds to.
        img_resize = img.resize((634, 9606), Image.LANCZOS)
        img_resize.crop((0, 0, 634, 935)).save(new_p/newfname, quality=95)
    print('Folder already exists.')


・ Not functionalized ・ Low versatility because it is cut out to a specific size ・ It will take time if the number of images increases (untested)


Working time has been reduced from 1 hour to 1 minute. Also, I think there is a better way to write it.

Recommended Posts

[Python3] Code that can be used when you want to cut out an image in a specific size
[Python3] Code that can be used when you want to resize images in folder units
[Python3] Code that can be used when you want to change the extension of an image at once
I want to create a priority queue that can be updated in Python (2.7)
If you want to make a Windows application (exe) that can be actually used now using only Python
Scripts that can be used when using bottle in Python
[Subprocess] When you want to execute another Python program in Python code
I made a familiar function that can be used in statistics with Python
How to install a Python library that can be used by pharmaceutical companies
ANTs image registration that can be used in 5 minutes
When you want to plt.save in a for statement
A mechanism to call a Ruby method from Python that can be done in 200 lines
[Django] A memorandum when you want to communicate asynchronously [Python3]
I want to be able to run Python in VS Code
When you want to hit a UNIX command on Python
How to set up a simple SMTP server that can be tested locally in Python
Can be used with AtCoder! A collection of techniques for drawing short code in Python!
A program that automatically resizes the iOS app icon to the required image size in Python
Cut out an image with python
A timer (ticker) that can be used in the field (can be used anywhere)
[Python] When you want to use all variables in another file
If you want to assign csv export to a variable in python
Python standard input summary that can be used in competition pro
Check if you can connect to a TCP port in Python
When you want to replace multiple characters in a string without using regular expressions in python3 series
How to write when you want to put a number after the group number to be replaced with a regular expression in re.sub of Python
I wrote a tri-tree that can be used for high-speed dictionary implementation in D language and Python.
I created a template for a Python project that can be used universally
Python Note: When you want to know the attributes of an object
Cut out A4 print in the image
[Python] Code that can be written with brain death at the beginning when scraping as a beginner
I want to color a part of an Excel string in Python
How to build an environment when you want to use python2.7 after installing Anaconda3
[Python] I want to know the variables in the function when an error occurs!
A solution to the problem that the Python version in Conda cannot be changed
I tried to create a class that can easily serialize Json in Python
Create a plugin that allows you to search Sublime Text 3 tabs in Python
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
If "can not be used when making a PIE object" appears in make
A personal memo of Pandas related operations that can be used in practice
[Python] What to check when you get a Unicode Decode Error in Django
Functions that can be used in for statements
I want to create a window in Python
List of tools that can be used to easily try sentiment analysis of Japanese sentences in Python (try with google colab)
A convenient function memo to use when you want to enter the debugger if an error occurs when running a Python script.
Run the output code with tkinter, saying "A, pretending to be B" in python
Convert images from FlyCapture SDK to a form that can be used with openCV
Consideration when you can do a good job in 10 years with Python3 and Scala3.
Summary of statistical data analysis methods using Python that can be used in business
[Python] You can save an object to a file by using the pickle module.
What to do if you get an error when importing matplotlib in Python (Mac)
You can do it in 3 minutes! How to make a moving QR code (GIF)!
Set up an FTP server that can be created and destroyed immediately (in Python)
A story that an error occurred when PyInstaller was used in a program that uses googleapiclient
[Python] Introduction to web scraping | Summary of methods that can be used with webdriver
[Linux] When you want to search for a specific character string from multiple files
How to create a property of relations that can be prefetch_related by specific conditions
I want to write in Python! (1) Code format check
I want to embed a variable in a Python string
I want to easily implement a timeout in python
Basic algorithms that can be used in competition pros