how to process all images on a folder with python - python

I have a python script to procces jpeg on a folder and overwrite the names after done
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
#import jpegs from Repaired folder
im = Image.open('photo_2022-06-09_19-58-19.JPG')
# Crop
im = ImageOps.crop(im, border=17)
# Constract
im = ImageOps.autocontrast(im, cutoff = 1)
#sharpness
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
#color
enhancer = ImageEnhance.Color(im).enhance(3)
#save all jpegs and overwrite original file names
im.save("photo_2022-06-09_19-58-19.JPG", quality="maximum")
How can i process all jpeg files in that dir have a folder "repaired" and Overwrite the name of each processed file with the original file name?

I would use glob and do something like this:
import glob
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
for fname in glob.glob('./repaired/*.JPG'):
im = Image.open(fname)
im = ImageOps.crop(im, border=17)
im = ImageOps.autocontrast(im, cutoff = 1)
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
enhancer = ImageEnhance.Color(im).enhance(3)
im.save(fname, quality="maximum")
You can print fname to see what it looks like, and process that string if you need to get the filename out, e.g. to write the file into a different folder.

So it should be like this
import os
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
#import jpegs from Repaired folder
for filename in os.listdir():
if filename.endswith(".jpg"):
im = Image.open(filename)
# Crop
im = ImageOps.crop(im, border=17)
# Constract
im = ImageOps.autocontrast(im, cutoff = 1)
#sharpness
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
#color
enhancer = ImageEnhance.Color(im).enhance(3)
#save all jpegs and overwrite original file names
im.save(filename, quality="maximum")
else:
continue

Related

from single jpg to web conversion to all files in dir

i made python code to convert jpg into webp
from PIL import Image
import PIL
import os
import glob
# Open The Image:
image_path = "D:/..../image_name.jpg"
image = Image.open(image_path)
# Convert the image to RGB Colour:
image = image.convert('RGB')
# Save The Image as webp:
new_image_path = "D:/.../converted_image_name.webp"
image.save(new_image_path, 'webp')
#open converted image for inspection
new_image = Image.open(new_image_path)
new_image.show()
Don't know how to build a function that does the conversion for all files in folder, keeping the orginial file_names.
Here is a working solution to your problem:
from pathlib import Path
from PIL import Image
import PIL
import os
import glob
# the path to the directory containing the images
directory_path = 'D:\PATH'
def convert_images(directory_path):
for image_path in os.listdir(directory_path):
if image_path.endswith(".jpg"):
image = Image.open(os.path.join(directory_path, image_path))
# get image filename without an extension
name = Path(image_path).stem
rgb_image = image.convert('RGB')
new_image_path = f"{name}.webp"
rgb_image.save(os.path.join(directory_path, new_image_path), 'webp')
new_image = Image.open(new_image_path)
new_image.show()
continue
else:
continue
convert_images(directory_path)
final code
from pathlib import Path
from PIL import Image
import PIL
import os
import glob
# the path to the directory containing the images
directory_path = 'D:/Lokale schijf/SS2023/Python_API_imports/'
def convert_images(directory_path):
for image_path in os.listdir(directory_path):
if image_path.endswith(".jpg"):
image = Image.open(os.path.join(directory_path, image_path))
# get image filename without an extension
name = Path(image_path).stem
rgb_image = image.convert('RGB')
new_image_path = f"{name}.webp"
rgb_image.save(os.path.join(directory_path, new_image_path), 'webp')
new_image = Image.open(new_image_path)
new_image.show()
continue
convert_images(directory_path)

Save an image with the same name after editing in python opencv module

I'm trying to save an image with the same name after editing on opencv. I can save with the same name. But I can't save in different file. So, this is my code:
import cv2
import numpy as np
import glob
filename = [img for img in glob.glob("./mypath_1/*.jpg")]
flist=sorted(filename)
images = []
path='./mypath_2/'
for image in flist:
img= cv2.imread(image)
alpha=2
beta=-420
img2=cv2.addWeighted(img,alpha,np.zeros(img.shape,img.dtype),0,beta)
hsv = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
cv2.imwrite( path+image, hsv)
Additionally, I tried this: cv2.imwrite( './mypath_2/'+image, hsv).
I do not save the image and I do not have a message error in this code.
Some suggestion?
import numpy as np
import cv2
import os
import sys
from pathlib import Path
if __name__ == "__main__":
#get alpha and beta values
alpha, beta =2, -420
# get directory path where the images are stored
image_dir = "/path/to/image read directory/"
# get directory path where you want to save the images
output_dir = "/path/to/image write directory/"
#iterate through all the files in the image directory
for _, _, image_names in os.walk(image_dir):
#iterate through all the files in the image_dir
for image_name in image_names:
# check for extension .jpg
if '.jpg' in image_name:
# get image read path(path should not contain spaces in them)
filepath = os.path.join(image_dir, image_name)
# get image write path
dstpath = os.path.join(output_dir, image_name)
print(filepath, dstpath)
# read the image
image = cv2.imread(filepath)
# do your processing
image2 = cv2.addWeighted(image, alpha,np.zeros_like(image),0,beta)
hsv = cv2.cvtColor(image2, cv2.COLOR_BGR2HSV)
# write the image in a different path with the same name
cv2.imwrite(dstpath, hsv)
print(image.shape, image2.shape, hsv.shape)
You can do it using 3 lines of code using nipath
import ntpath
filename = ntpath.basename("D:\coding\python\Sample Photos\1.jpg")
cv2.imwrite("D:\coding\python\Sample Photos\"+filename, img)

Take an image directory and resize all images in the directory

I am trying to convert high resolution images to something more manageable for machine learning. Currently I have the code to resize the images to what ever height and width I want however I have to do one image at a time which isn't bad when I'm only doing a 12-24 images but soon I want to scale up to do a few hundred images.
I am trying to read in a directory rather than individual images and save the new images in a new directory. Initial images will vary from .jpg, .png, .tif, etc. but I would like to make all the output images as .png like I have in my code.
import os
from PIL import Image
filename = "filename.jpg"
size = 250, 250
file_parts = os.path.splitext(filename)
outfile = file_parts[0] + '_250x250' + file_parts[1]
try:
img = Image.open(filename)
img = img.resize(size, Image.ANTIALIAS)
img.save(outfile, 'PNG')
except IOError as e:
print("An exception occured '%s'" %e)
Any help with this problem is appreciated.
Assuming the solution you are looking for is to handle multiple images at the same time - here is a solution. See here for more info.
from multiprocessing import Pool
def handle_image(image_file):
print(image_file)
#TODO implement the image manipulation here
if __name__ == '__main__':
p = Pool(5) # 5 as an example
# assuming you know how to prepare image file list
print(p.map(handle_image, ['a.jpg', 'b.jpg', 'c.png']))
You can use this:
#!/usr/bin/python
from PIL import Image
import os, sys
path = "\\path\\to\\files\\"
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((200,100), Image.ANTIALIAS)
imResize.save(f+'.png', 'png', quality=80)
resize()
You can loop over the contents of a directory with
import os
for root, subdirs, files in os.walk(MY_DIRECTORY):
for f in files:
if f.endswith('png'):
#do something
You can run through all the images inside the directory using glob. And then resize the images with opencv as follows or as you have done with PIL.
import glob
import cv2
import numpy as np
IMG_DIR='home/xx/imgs'
def read_images(directory):
for img in glob.glob(directory+"/*.png"):
image = cv2.imread(img)
resized_img = cv2.resize(image/255.0 , (250 , 250))
yield resized_img
resized_imgs = np.array(list(read_images(IMG_DIR)))
I used:
from PIL import Image
import os, sys
path = os.path.dirname(os.path.abspath(__file__))
dirs = os.listdir( path )
final_size = 244
print(dirs)
def resize_aspect_fit():
for item in dirs:
if ".PNG" in item:
print(item)
im = Image.open(path+"\\"+item)
f, e = os.path.splitext(path+"\\"+item)
size = im.size
print(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))
print(f)
new_im.save(f + 'resized.jpg', 'JPEG', quality=400)# png
resize_aspect_fit()
You can use this code to resize multiple images and save them after conversion in the same folder for let's say dimensions of (200,200):
import os
from PIL import Image
f = r' ' #Enter the location of your Image Folder
new_d = 200
for file in os.listdir(f):
f_img = f+'/'+file
try:
img = Image.open(f_img)
img = img.resize((new_d, new_d))
img.save(f_img)
except IOError:
pass
you can try to use the PIL library to resize images in python
import PIL
import os
import os.path
from PIL import Image
path = r'your images path here'
for file in os.listdir(path):
f_img = path+"/"+file
img = Image.open(f_img)
img = img.resize((100, 100)) #(width, height)
img.save(f_img)
from PIL import Image
import os
images_dir_path=' '
def image_rescaling(path):
for img in os.listdir(path):
img_dir=os.path.join(path,img)
img = Image.open(img_dir)
img = img.resize((224, 224))
img.save(img_dir)
image_rescaling(images_dir_path)

Converting images in a folder to grayscale using python and opencv and writing it to a specific folder

import glob
import cv2
import os
import numpy as np
from PIL import Image
images=[]
images=np.array(images)
path='C:\Users\Quantum\Desktop\test'
count=0
images = [cv2.imread(file,0) for file in glob.glob("E:\homework\Computer vision\Faces\*.jpg")]
for i in range(len(images)):
# im = Image.fromarray(images[i])
# cv2.imwrite(str(path) + '.jpg', images[count])
cv2.imwrite(os.path.join(path, 'pic.jpg'), images[count])
count+=1
Trying to select all the images from a folder and the images are getting selected and are converted to grayscale although I dont know how to write those images to a specific folder.Kindly help
#multiple image conversions
import cv2
import os,glob
from os import listdir,makedirs
from os.path import isfile,join
path = '/root/Desktop/Anil' # Source Folder
dstpath = '/root/Desktop/Anil2' # Destination Folder
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in same folder")
# Folder won't used
files = list(filter(lambda f: isfile(join(path,f)), listdir(path)))
for image in files:
try:
img = cv2.imread(os.path.join(path,image))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,gray)
except:
print ("{} is not converted".format(image))
for fil in glob.glob("*.jpg"):
try:
image = cv2.imread(fil)
gray_image = cv2.cvtColor(os.path.join(path,image), cv2.COLOR_BGR2GRAY) # convert to greyscale
cv2.imwrite(os.path.join(dstpath,fil),gray_image)
except:
print('{} is not converted')
import cv2
import glob, os, errno
# Replace mydir with the directory you want
mydir = r'C:\Users\Quantum\Desktop\testoutput'
#check if directory exist, if not create it
try:
os.makedirs(mydir)
except OSError as e:
if e.errno == errno.EEXIST:
raise
for fil in glob.glob("*.jpg"):
image = cv2.imread(fil)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to greyscale
cv2.imwrite(os.path.join(mydir,fil),gray_image) # write to location with same name
import os,cv2
path = r'C:\Users\me\Desktop\folder' # Source Folder
dstpath = r'C:\Users\me\Desktop\desfolder' # Destination Folder
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in asme folder")
# Folder won't used
files = os.listdir(path)
for image in files:
img = cv2.imread(os.path.join(path,image))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imwrite(os.path.join(dstpath,image),gray)
import cv2
from os import listdir,makedirs
from os.path import isfile,join
path = r'C:\Users\fakabbir.amin\Desktop\pdfop' # Source Folder
dstpath = r'C:\Users\fakabbir.amin\Desktop\testfolder' # 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))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,gray)
except:
print ("{} is not converted".format(image))
This code snippet will take all the images from path and write into another folder mentioned in dstpath.

Resize multiple images in a folder (Python)

I already saw the examples suggested but some of them don't work.
So, I have this code which seems to work fine for one image:
im = Image.open('C:\\Users\\User\\Desktop\\Images\\2.jpg') # image extension *.png,*.jpg
new_width = 1200
new_height = 750
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\\Users\\User\\Desktop\\resized.tif') # .jpg is deprecated and raise error....
How can I iterate it and resize more than one image ? Aspect ration need to be maintained.
Thank you
# Resize all images in a directory to half the size.
#
# Save on a new file with the same name but with "small_" prefix
# on high quality jpeg format.
#
# If the script is in /images/ and the files are in /images/2012-1-1-pics
# call with: python resize.py 2012-1-1-pics
import Image
import os
import sys
directory = sys.argv[1]
for file_name in os.listdir(directory):
print("Processing %s" % file_name)
image = Image.open(os.path.join(directory, file_name))
x,y = image.size
new_dimensions = (x/2, y/2) #dimension set here
output = image.resize(new_dimensions, Image.ANTIALIAS)
output_file_name = os.path.join(directory, "small_" + file_name)
output.save(output_file_name, "JPEG", quality = 95)
print("All done")
Where it says
new_dimensions = (x/2, y/2)
You can set any dimension value you want
for example, if you want 300x300, then change the code like the code line below
new_dimensions = (300, 300)
I assume that you want to iterate over images in a specific folder.
You can do this:
import os
from datetime import datetime
for image_file_name in os.listdir('C:\\Users\\User\\Desktop\\Images\\'):
if image_file_name.endswith(".tif"):
now = datetime.now().strftime('%Y%m%d-%H%M%S-%f')
im = Image.open('C:\\Users\\User\\Desktop\\Images\\'+image_file_name)
new_width = 1282
new_height = 797
im = im.resize((new_width, new_height), Image.ANTIALIAS)
im.save('C:\\Users\\User\\Desktop\\test_resize\\resized' + now + '.tif')
datetime.now() is just added to make the image names unique. It is just a hack that came to my mind first. You can do something else. This is needed in order not to override each other.
I assume that you have a list of images in some folder and you to resize all of them
from PIL import Image
import os
source_folder = 'path/to/where/your/images/are/located/'
destination_folder = 'path/to/where/you/want/to/save/your/images/after/resizing/'
directory = os.listdir(source_folder)
for item in directory:
img = Image.open(source_folder + item)
imgResize = img.resize((new_image_width, new_image_height), Image.ANTIALIAS)
imgResize.save(destination_folder + item[:-4] +'.tif', quality = 90)

Categories

Resources