python多线程记录

在这里插入图片描述
线程是进程的基本单位。利用多线程进行执行代码,可以加快文件的处理速度,这里主要是利用多线程对若干图片进行裁剪操作。废话不多说,直接上代码!

import os
from PIL import Image
import time
from multiprocessing.pool import ThreadPool


def crop_mid(img,output_path,roots):
    root, name = os.path.split(roots)
    w,h = img.size
    if w<=h:
        img_f1 = img.crop((0,(h-w)//2,w,(h+w)//2))
    else:
        img_f1 = img.crop(((w-h)//2,0,(w+h)//2,h))

    img_f1.save(os.path.join(output_path,"crop_mid","default", name[:-4] + '_m.jpg'))


def crop_img_thread(img,output_path,roots,num_processes, Async = True):
    pool = ThreadPool(processes=num_processes)
    if Async:
        pool.apply_async(func=crop_mid, args=(img, output_path, roots))  #异步
    else:
        pool.apply(func=crop_mid, args=(img, output_path, roots))  #同步
    pool.close()
    pool.join()


def main():
    file_path = r'C:\Users\E14\Desktop\rotation_code/test_list.txt'
    output_path = r'C:\Users\E14\Desktop\test\data'
    with open(file_path) as f:
        file_list = f.readlines()
    for num,lis in enumerate(file_list):
        roots,cls = lis.strip().split(" ")
        img = Image.open(roots)
        trc = time.time()
        crop_img_thread(img, output_path, roots, num_processes=10)
        print("hello kitty!",num, "The time cost:", time.time()-trc, "s")

if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/WYKB_Mr_Q/article/details/118392255