I'm trying to do image augmentations for which I'm getting images from a large number of folders Doing this in a sequel takes lots of time, so I'm running the same script in different terminals in order to complete augmentations very quickly by providing the start and end value of the list index as shown in the below code.
do_augmentations(args):
total_count = len(all_folders)
split_no = total_count //2
start = split_no
if split_no == 0:
split_no = 1
end = total_count
for folder in all_folders[start:end]:
allImgs = list(paths.list_images(folder))
count = len(allImgs)
for img in allImages:
augmentations(img)
cv2.imwrite(img)
def main():
all_folders= os.walk(folderpath)
do_augmentations(all_folders)
I was wondering if we could use multiple CPU cores with multithreading and multiprocessing packages in Python in parallel rather than sequentially because it takes a long time. Here I'm mentioning the start and end value of the folder number to run separately in multiple terminals to run faster . I tried using a multiprocessing library to implement this in parallel, but it runs in the same sequential manner as before. Below is the code of my approach to solving this.
from multiprocessing import pool
from multiprocessing.dummy import Pool as ThreadPool
do_augmentations(args):
all_folers = args[0]
bpath = args[1]
for folder in all_folders:
allImgs = list(paths.list_images(folder))
count = len(allImgs)
for img in allImages:
augmentations(img)
cv2.imwrite(img)
def main():
bpath = 'img_foldr'
all_folders= os.walk(folderpath)
pool = ThreadPool(4)
pool.map(do_augmentations,[[all_folders,bpath]])
When running this, it does image processing on one folder at a time in a loop instead of in parallel for many folders simultaneously. I don't understand what I'm doing wrong. Any help or suggestions to solve this will be very helpful.
Update: I tried answer given by Jan Wilamowski as below
def augment(image):
img = do_augmentation(image)
cv2.imwrite(img)
def main():
all_folders = os.walk(imagefolder)
all_images = chain(paths.list_images(folder) for folder in all_folders)
pool = Pool(4)
pool.map(augment,all_images)
I get error as below
Traceback (most recent call last):
File "aug_img.py", line 424, in
main()
File "aug_img.py", line 346, in main
pool.map(augment,all_images)
File "C:\Users\mathew\anaconda3\envs\retinanet\lib\multiprocessing\pool.py", line 364, in map return self._map_async(func, iterable, mapstar, chunksize).get()
File "C:\Users\mathew\anaconda3\envs\retinanet\lib\multiprocessing\pool.py", line 771, in get raise self._value
File "C:\Users\mathew\anaconda3\envs\retinanet\lib\multiprocessing\pool.py", line 537, in _handle_tasks put(task)
File "C:\Users\mathew\anaconda3\envs\retinanet\lib\multiprocessing\connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "C:\Users\mathew\anaconda3\envs\retinanet\lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj)
TypeError: cannot pickle 'generator' object