Hi all I need to open images from a folder one by one do some processing on images and save them back to other folder. I am doing this using following sample code.
path1 = path of folder of images
path2 = path of folder to save images
listing = os.listdir(path1)
for file in listing:
im = Image.open(path1 + file)
im.resize((50,50)) % need to do some more processing here
im.save(path2 + file, "JPEG")
Is there any best way to do this?
Thanks!
Sounds like you want multithreading. Here's a quick rev that'll do that.
from multiprocessing import Pool
import os
path1 = "some/path"
path2 = "some/other/path"
listing = os.listdir(path1)
p = Pool(5) # process 5 images simultaneously
def process_fpath(path):
im = Image.open(path1 + path)
im.resize((50,50)) # need to do some more processing here
im.save(os.path.join(path2,path), "JPEG")
p.map(process_fpath, listing)
(edit: use multiprocessing instead of Thread, see that doc for more examples and information)
You can use glob to read the images one by one
import glob
from PIL import Image
images=glob.glob("*.jpg")
for image in images:
img = Image.open(image)
img1 = img.resize(50,50)
img1.save("newfolder\\"+image)
Related
I'm trying to turn images in a folder into individual .mp4 videos that last 10 seconds each.
I've tried to accomplish this with MoviePy, however I could only join these images together into one video rather than multiple individual videos of a single different image in each video or I would have to code each and every single image into a 10 second long video file.
The way I done all images at once was by the following code:
clips = []
for filename in os.listdir('imagefolder/'):
if filename.endswith(".jpg"):
clips.append(ImageClip('imagefolder/' + str(filename)))
final_video_clip = concatenate_videoclips(clips, method="compose")
final_video_clip.write_videofile("memes.mp4", fps=24, remove_temp=True, codec="libx264", audio_codec="aac")
Closes I got was this code:
from importlib.resources import path
import os
from moviepy.editor import *
import glob
import tempfile
import itertools as IT
import os
clips = []
for filename in os.listdir('imagesfolder/'):
if filename.endswith(".jpg"):
clips.append([ImageClip('imagesfolder/' + str(filename)).set_duration(10)])
for clip in clips[0:]:
print(clip)
final_video_clip = concatenate_videoclips(clip, method="compose")
for i, clip in enumerate(clip):
final_video_clip.write_videofile("memes" + str(i) +".mp4", fps=24, remove_temp=True, codec="libx264", audio_codec="aac")
Any Ideas?
Thanks!
i'm trying to make something that returns a random image from a folder to eventually put together an outfit. the path is a specific folder, as each path is a different type of clothing article (i.e. a folder/path for pants would be /Users/xxx/Desktop/outfit_images/5pants)
def article(path):
files = os.listdir(path) # listdir gives you a list with all filenames in the provided path.
randomFile = random.choice(files) # random.choice then selects a random file from your list
image = Image.open(path + '/' + randomFile) # displayed the image
return image
i'm using the code above to have the specified clothing article file as the input, and then select a random image from that file. i however, get errors (.DS_Store selection error) every few attempts becuase of the hidden files on the mac '.', '..', and want to figure out how to avoid selecting these hidden files. i would prefer to use a method other than running the rm from the terminal. any help is greatly appreciated!
You can use glob for this:
import glob
import os
def article(path):
files = glob.glob(os.path.join(path, '*'))
randomFile = random.choice(files)
image = Image.open(path + '/' + randomFile)
return image
I'm trying to convert all files from a directory from .jpg to .png. The name should remain the same, just the format would change.
I've been doing some researches and came to this:
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
im.save('img11.png')
print(os.path.join(directory, filename))
continue
else:
continue
I was expecting the loop to go through all my .jpg files and convert them to .png files. So far I was doing only with 1 name: 'img11.png', I haven't succed to build something able to write the adequate names.
The print(os.path.join(directory, filename)) works, it prints all my files but concerning the converting part, it only works for 1 file.
Do you guys have any idea for helping me going through the process?
You can convert the opened image as RGB and then you can save it in any format.
You can try the following code :
from PIL import Image
import os
directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
name='img'+str(c)+'.png'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue
You're explicitly saving every file as img11.png.
You should get the name of your jpg file and then use that to name and save the png file.
name = filename[:-4]
im.save(name + '.png')
I would have used os.rename() function like below.
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
prefix = filename.split(".jpg")[0]
os.rename(filename, prefix+".png")
Please let me know if this is what you wanted. Try the code with some copied images inside a test folder, before applying to the intended folder. All the best.
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
prefix = filename.split(".jpg")[0]
im = Image.open(filename)
im.save(prefix+'.png')
else:
continue
Please try this one and let me know.
I am trying to learn how to use multiprocessing with PIL using python 2.7 on a 64 bit windows 7 pc.
I can successfully create (and save) the thumbnails using PIL to the desired location on my pc. When I try to implement multiprocessing, my code does not create any thumbnails and it loops through the files about twice as fast. I have about 9,000 image files in multiple directories and sub directories (I have no control over the file names not directory structure)
here is the basis of the code that works.
from multiprocessing import Pool, freeze_support
import os
from fnmatch import fnmatch
from timeit import default_timer as timer
from PIL import Image, ImageFile
starttime = timer()
SIZE = (125, 125)
SAVE_DIRECTORY = r'c:\path\to\thumbs'
PATH = r'c:\path\to\directories\with\photos
def enumeratepaths(path):
""" returns the path of all files in a directory recursively"""
def create_thumbnail(_filename):
try:
ImageFile.LOAD_TRUNCATED_IMAGES = True
im = Image.open(_filename)
im.thumbnail(SIZE, Image.ANTIALIAS)
base, fname = os.path.split(_filename)
outfile = os.path.split(_filename)[1] + ".thumb.jpg"
save_path = os.path.join(SAVE_DIRECTORY, outfile)
im.save(save_path, "jpeg")
except IOError:
print " cannot create thumbnail for ... ",_filename
if __name__ == '__main__':
freeze_support() # need this in windows; no effect in *nix
for _path in enumeratepaths(PATH):
if fnmatch(_path, "*.jpg"):
create_thumbnail(_path)
# pool = Pool()
# pool.map(create_thumbnail, _path)
# pool.close()
# pool.join()
The code works and creates the 9,000 thumbnails in the desired location. When I comment out create_thumbnail(_path) and un-comment the multiprocessing code, the code iterates thru the directory structure twice as fast but does not create any thumbnails. How would I adjust the multiprocessing code to make it work?
the code "pool.map(create_thumbnail, _path)" needs to be pool.map(create_thumbnail(_path), _path) to create the thumbnails
So I'm trying to use pillow to apply kernals to .jpg images in python and I'm trying to process an entire image set at once. I have a script here that will iterate through the training set, apply the edge finding filter, and save the result in a different folder. Whenever I try to do that using the .save command it throw an error telling me there is no such file as the one I'm saving it to. The thing is, I'm trying to create that file. It doesn't do this when I've got a definite file name, only when I'm trying to do it iterativly. Can anyone see what the problem here is?
import PIL
import os
from PIL import Image
from PIL import ImageFilter
from PIL.ImageFilter import (FIND_EDGES)
num = 1
path = "/home/<me>/Desktop/<my documents>/<my project>/Training Set Cars/"
dirs = os.listdir(path)
for filename in dirs:
print(filename)
im = Image.open(path + filename)
aString = str(num)
print("/home/<me>/Desktop/<my documents>/<my project>/Training Car Edges/%s.jpg" % aString)
ERROR HERE>>> im.filter(FIND_EDGES).save("/home/<me>/Desktop/<my documents>/<my project>/Training Car Edges/%s.jpg" % aString)
num += 1