Python PIL Crop all Images in a Folder - python

Currently I am trying to crop all images inside a folder under the address of: C:\\Users\\xie\\Desktop\\tiff\\Bmp and then resave them into the same folder. Below is the code I am trying to experiment with, both run without error but does nothing. Also note I am using windows as platform.
Code 1:
from PIL import Image
import os.path, sys
path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
dirs = os.listdir(path)
def crop():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imCrop = im.crop(30, 10, 1024, 1004)
imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)
crop()
Code 2:
for f in os.listdir("C:\\Users\\xie\\Desktop\\tiff\\Bmp"):
for f in ("C:\\Users\\xie\\Desktop\\tiff\\Bmp"):
if f.endswith('.bmp'):
print (f, end=" ")
i = Image.open(f)
area = (30, 10, 1024, 1004)
cropped_i = i.crop(area)
cropped_i.show()
cropped_i.save('Cropped{}.bmp', "BMP", quality=100, optimize=True)
Thanks, any help or suggestions are greatly appreciated!

Code 1 : Corrected
This is your corrected code, you almost had it right, you have to join the path correctly, in your code you weren't adding a separator / between the path and the filename. by using os.path.join you can combine a directory path and a filename.
Furthermore, crop takes a tuple of 4, not 4 arguments.
from PIL import Image
import os.path, sys
path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
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)
imCrop = im.crop((30, 10, 1024, 1004)) #corrected
imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)
crop()

This is more or less a rough version of code, I used with opencv, it should work the same for PIL also
import glob
import numpy as np
from PIL import Image
image_list = []
for filename in glob.glob('name_of_folder/*.jpg'):
im=Image.open(filename)
image_list.append(im)
a=0
c=[]
for i in range(0,len(image_list)):
#ur image cropping and other operations in here for each image_list[i]
c.append(image_list[i])
c[i].save()

Related

Python/PIL Resize all images in all subfolder and save as new file name

I am going to resize image file which located in Desktop with set of subfolder.
I try following command and it works without rename save new.
from PIL import Image
import os, sys
import glob
root_dir='./././Desktop/python/'
def resize():
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((450,600), Image.ANTIALIAS)
imResize.save(filename , 'JPEG', quality=90)
resize()
My question is how can I add the correct command to save the renewe resized image file with append 'f + _thumbnail' + .jpg?
E.g file1 > file1_thumbnail.jpg
I tried add followings to row print(filename) but show error.
f, e = os.path.splitext(path+item)
size = im.size
ratio = float(final_size) / max(size)
new_image_size = tuple([int(x*ratio) for x in size])
im = im.resize(new_image_size, Image.ANTIALIAS)
new_im = Image.new("RGB", (final_size, final_size))
new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
May I know how can fix it?
Many Thanks
You can use python slicing of strings for this -
You can modify your code to -
from PIL import Image
import os, sys
import glob
root_dir='./././Desktop/python/'
def resize():
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((450,600), Image.ANTIALIAS)
filename = filename[:-4] + " _thumbnail" + filename[-4:]
imResize.save(filename , 'JPEG', quality=90)
resize()
The ".jpg" can be sliced at the end.

Python Resize all images in a folder

I have the following code that I thought would resize the images in the specified path But when I run it, nothing works and yet python doesn't throw any error so I don't know what to do. Please advise. Thanks
import cv2
import numpy as np
import os
from PIL import Image
def image_resize(folder):
images = []
num_images = 0
location = folder+"_"
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder, filename))
if img is not None:
new_img = np.array(Image.fromarray(img).resize((200, 200), Image.ANTIALIAS)) # Resize the images to 50 X 50
images.append(new_img)
num_images += 1
cv2.imwrite("{}/{}".format(location, filename), new_img)
return None
image_resize("2S1")
image_resize("SLICY")
image_resize("BRDM-2")
image_resize("BTR-60")
image_resize("D7")
image_resize("T62")
image_resize("ZIL131")
image_resize("ZSU-23_4")
all image in folder: G:\sar
help me
It does not do anything because your for loop is not finding any files in the folder. You are never passing the "G:\sar" part of the file path.

viewing images from local path(directory) in python?

i'm trying to retrieve images from my local directory using array list but i got all images from list but i don't know how to show images from list one by one.
Please help me if anyone knows.
my.py:
import os, os.path
imgs = []
# print(imgs)
path = "C:/Users/admin/PycharmProjects/my_module/static/files"
valid_images = [".jpg",".gif",".png",".tga"]
print(valid_images)
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
os.listdir(path).append(f)
# Image.show(f)
There are several options depending on your environment and visualization libraries. Check this good answer
You need to do from PIL import Image, then you could do Image.open(path + "/" + f).show(). Try this:
import os, os.path
from PIL import Image
imgs = []
path = "path/to/directory"
valid_images = [".jpg", ".gif", ".png", ".tga"]
print(valid_images)
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext in valid_images:
imgs.append(path + "/" + f)
img = Image.open(path + "/" + f)
img.show()
print(imgs)
I have tried and i got my expected output.
py:
import os
from PIL import Image
img=[]
path="C:/Users/admin/PycharmProjects/my_module/static/files/"
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
os.listdir(path).append(f)
image = Image.open(f)
image.show()

histogram.cpp:3915: error: (-215) _src.type() == CV_8UC1 in function cv::equalizeHist

files2 = [f for f in listdir(dstpath) if isfile(join(dstpath,f))]
for image in files2:
img = cv2.imread(os.path.join(dstpath,image))
equ = cv2.equalizeHist(img)
dstPath2 = join(dstpath,image)
cv2.imwrite(dstPath2,equ)
I have a folder consisting of grayscale images in jpg format but when I run my above code for Histogram equalization it gives me the above mentioned error. Pls help
imread load image in color mode by default. Try to use img = cv2.imread(your_image_path,cv2.IMREAD_GRAYSCALE) instead
#author: Quantum
"""
import cv2
import os
from os import listdir,makedirs
from os.path import isfile,join
path = r'' # Source Folder
dstpath = r'' # Destination Folder
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in asme folder")
# Folder won't used
files = [f for f in listdir(path) if isfile(join(path,f))]
for image in files:
try:
img = cv2.imread(os.path.join(path,image),cv2.IMREAD_GRAYSCALE)
**imgnew=cv2.equalizeHist(img)**
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,imgnew)
except:
print ("{} is not converted".format(image))
All I did was added the histeq function while my files are converted to grayscale

Python Pillow resize images trouble: it runs well but there're no images

I'm learning Python and try to use Pillow to resize images in a folder, then save them to another folder with the same filename. However, the program runs well, when I check the destination folder, there're no images...
My code is as below:
from PIL import Image
import os, glob, sys
src_path = "D:/Test_A/src/*.png"
dst_path = "D:/Test_A/dst/"
img_list = glob.glob(src_path)
for XXPNG in img_list:
fn = os.path.basename(XXPNG)
im = Image.open(XXPNG)
print(fn, im.size)
nim = im.resize((119, 119), Image.ANTIALIAS)
nim.save("dst_path","PNG")
print("Resize Done")
Please help me find my bug, or give my any advise.
Thank you very much for help and bearing my poor English.
"dst_path" with " is a normal text, not variable dst_path - so you save in file with name "dst_path".
You need dst_path without " - plus filename
nim.save(dst_path + fn, "PNG")
or with os.path.join()
nim.save(os.path.join(dst_path, name), "PNG")
Code:
from PIL import Image
import os, glob, sys
src_path = "D:/Test_A/src/*.png"
dst_path = "D:/Test_A/dst/"
img_list = glob.glob(src_path)
for fullpath in img_list:
name = os.path.basename(fullpath)
im = Image.open(fullpath)
print(name, im.size, '=>', os.path.join(dst_path, name))
nim = im.resize((119, 119), Image.ANTIALIAS)
nim.save(os.path.join(dst_path, name), "PNG")
#nim.save(dst_path + name, "PNG")
print("Resize Done")

Categories