Reputation: 3
I have a folder of photos and want to crop 2 corners of it and then rotate 1 angle 180 degrees for 2 similar cropped images. I have a problem with image rotation and saving. This is the code that i got till now
from PIL import Image
import os.path, sys
path = r"D:\Machine_Learning\img"
dirs = os.listdir(path)
def crop():
for item in dirs:
fullpath = os.path.join(path,item) #corrected
if os.path.isfile(fullpath):
im = Image.open(fullpath)
f, e = os.path.splitext(fullpath)
save_dir = r'D:\Machine_Learning\img\crop'
imCropTop = im.crop((2125, 70, 2148, 310)) #corrected
imCropTop.save(f+'TOP_Cropped.bmp', "BMP", quality=100)
imCropBot = im.crop((2125, 684, 2148, 924)) # corrected
imCropBot.save(f + 'BOT_Cropped.bmp', "BMP", quality=100)
crop()
Upvotes: 0
Views: 1241
Reputation: 3677
This works for me. I have changed some of your variable names to fit with pep 8. Clear variable names help to avoid confusion (especially avoid single character names - my pet hate)
You will, of course, have to use your own directory names.
from PIL import Image
import os.path
SOURCE_DIRECTORY = "../scratch/load_images/my_images"
TARGET_DIRECTORY = "../scratch/load_images/my_cropped_images/"
directory_list = os.listdir(SOURCE_DIRECTORY)
def crop():
for source_file in directory_list:
source_path = os.path.join(SOURCE_DIRECTORY, source_file)
if os.path.isfile(source_path):
raw_image = Image.open(source_path)
file_name = os.path.basename(source_path)
file_name, extension = os.path.splitext(file_name)
image_cropped_top = raw_image.crop((2125, 70, 2148, 310))
image_cropped_top.save(TARGET_DIRECTORY + file_name+'TOP_Cropped.bmp', "BMP", quality=100)
if __name__ == '__main__':
crop()
Upvotes: 1