You could create a class that extends the threading.Thread
class and then override the run
to perform the task you want to perform if the condition is met.
Then get all images with listdir
and iterate over it, assigning a new thread to each image. Finally, start each thread. Below is a sample code of the above description:
import threading
import os
class FileThread(threading.Thread):
def __init__(self, image):
threading.Thread.__init__(self)
self.image = image
def run(self):
if image.endswith('.jpg'):
# Do stuff
# List that will hold all threads.
threadList = []
# List that will hold all images.
images = os.listdir(imagePath)
# Assign each image to a thread.
for image in images:
threadList.append(FileThread(image))
# Start threads.
for thread in threadList:
thread.start()
Another way is to use the multiprocessing
module and assign each image to a process:
import multiprocessing as mp
import os
# The function that will apply to every image.
def imageFunc(image):
if image.endsWith(".jpg"):
# Do something
# An output queue that will hold the results.
output = mp.Queue()
# A list of processes that will perform the 'imageFunc' on each image.
processes = [mp.Process(target=imageFunc, args=(image)) for image in os.listdir(imagePath)]
# Starting all the processes...
for p in processes:
p.start()
# ...and wait for them to finish.
for p in processes:
p.join()
# Finally, retrieve the results from the above processes.
result = [output.get() for p in processes]