本示例中与Python多线程实例之爬虫中的实质区别在于构建队列的方式,且本实例将使用图片处理的案例进行举例。
数据说明:有n张图片,分别存储在images目录下的不同二级子目录下,且部分图片存放在三级子目录下。
需求说明:
1、将图片顶部的去除一部分;
2、写入另一个盘中,目录层级及文件名不变;
import cv2 # 图片处理库
import os
import time
import threading # 线程库
from glob import glob
from collections import deque # 队列库
def fandle_function(image_path_queue):
# 循环从队列中获取file_path,直至队列为空
while len(image_path_queue) > 0 :
# 从队列中获取file path
img_path = image_path_queue.pop()
# 读取图片
img = cv2.imread(img_path)
# 处理存储路径
save_path = img_path.split("\\")
save_path = "E:\\" + "\\".join(save_path[1:-1])
# 判断存储路径是否存在,不存在则新建。
# 思考为什么要加try except?
try:
if not os.path.exists(save_path):
os.makedirs(save_path)
except:
pass
# 拼接文件存储名称及路径
save_path = os.path.join(save_path, img_path.split("\\")[-1])
# 将图片写入本地
cv2.imwrite(save_path, img[105:,:,:])
if __name__ == '__main__':
# D:\test\02\03
all_image_path = glob(pathname = r"D:\test\**\*.jpg", recursive=True)
# 将列表直接转换为队列
image_path_queue = deque(all_image_path)
all_thread = []
t1 = time.time()
for i in range(10):
t = threading.Thread(target=fandle_function, args=(image_path_queue,))
all_thread.append(t)
t.start()
print(time.time()-t1)
for j in all_thread:
j.join()