1. '''
    2. author:tonyzhang
    3. function:transfrom img to size H W and save
    4. '''
    5. import cv2
    6. import os
    7. import glob
    8. dir_path = "F:/SPAQImage/*.jpg"
    9. save_path = "F:/SPAQImage224/"
    10. for i in glob.glob(dir_path):
    11. img = cv2.imread(i)
    12. print(i)
    13. img = cv2.resize(img,(224,224))
    14. cv2.imwrite(os.path.join(save_path,os.path.basename(i)),img)

    上面的单线程版本,太慢了
    下面搞了个多线程,快了很多,cpu利用率拉满

    1. '''
    2. author:tonyzhang
    3. function:transfrom img to size H W and save
    4. '''
    5. import cv2
    6. import os
    7. import glob
    8. import concurrent.futures
    9. from threading import Thread
    10. num_threads = 10
    11. dir_path = "T:/PARA/img_all/"
    12. save_path = "T:/PARA/img_all2/"
    13. def process_image(filelist):
    14. for filename in filelist:
    15. print(filename)
    16. file = os.path.join(dir_path,filename)
    17. img = cv2.imread(file)
    18. img = cv2.resize(img,(224,224))
    19. cv2.imwrite(os.path.join(save_path,filename),img)
    20. def multi_thread_process(dir_path):
    21. if num_threads == 1:
    22. process_image(os.listdir(dir_path))
    23. return
    24. filelist_total = os.listdir(dir_path)
    25. filenum = len(filelist_total)
    26. filenum_each_thread = int(filenum/num_threads)
    27. thread_list = []
    28. for i in range(num_threads-1):
    29. thread_list.append(Thread(target=process_image, args=(filelist_total[i*filenum_each_thread : (i+1)*filenum_each_thread],)))
    30. thread_list.append(Thread(target=process_image, args=(filelist_total[(num_threads-1)*filenum_each_thread :],)))
    31. for th in thread_list:
    32. th.start()
    33. for th in thread_list:
    34. th.join()
    35. multi_thread_process(dir_path)