对这段代码也使用多线程:def get_image_files(folder): image_extensions = ['.jpg', '.jpeg', '.png'] # 定义图片扩展名 image_files = [] for root, dirs, files in os.walk(folder): for file in files: if os.path.splitext(file)[1].lower() in image_extensions: img_path = os.path.join(root, file) # 将每条数据保存到txt中 path_all_files = open('./all_files.txt','a') path_all_files.write(img_path+'\n') path_all_files.close() print(img_path) image_files.append(img_path) return image_files # 加载ONNX模型 ort_session = onnxruntime.InferenceSession('./best_weights.onnx') # 预处理输入图像 transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) # 创建线程池 executor = concurrent.futures.ThreadPoolExecutor() # 获取路径下所有图片 image_files = get_image_files('C:/Users/xyzhuge/Desktop/detect-mamaclouds-yolov5-v2/detect-mamaclouds-yolov5-linux-main/res/')
时间: 2024-04-14 13:29:58 浏览: 260
多线程图片加载
下面是对第二段代码使用多线程的示例:
```python
import concurrent.futures
def get_image_files(folder):
image_extensions = ['.jpg', '.jpeg', '.png'] # 定义图片扩展名
image_files = []
for root, dirs, files in os.walk(folder):
for file in files:
if os.path.splitext(file)[1].lower() in image_extensions:
img_path = os.path.join(root, file)
# 将每条数据保存到txt中
path_all_files = open('./all_files.txt','a')
path_all_files.write(img_path+'\n')
path_all_files.close()
print(img_path)
image_files.append(img_path)
return image_files
# 创建线程池
executor = concurrent.futures.ThreadPoolExecutor()
# 获取路径下所有图片
image_files = get_image_files('C:/Users/xyzhuge/Desktop/detect-mamaclouds-yolov5-v2/detect-mamaclouds-yolov5-linux-main/res/')
# 定义处理图片的函数
def process_image(image_file):
# 加载图片
image = Image.open(image_file)
# 预处理
input_data = transform(image).unsqueeze(0).numpy()
# 运行推理
ort_inputs = {ort_session.get_inputs()[0].name: input_data}
ort_outputs = ort_session.run(None, ort_inputs)
# 获取预测结果
predicted_class = np.argmax(ort_outputs[0])
print(f'Image: {image_file}')
print(f'Predicted class: {predicted_class}')
# 当为0时,删除图片
if predicted_class == 0:
# 将每条数据保存到txt中
path_all_files = open('./del_files.txt','a')
path_all_files.write(image_file+'\n')
path_all_files.close()
os.remove(image_file)
print('Deleted')
# 提交任务给线程池
for image_file in image_files:
executor.submit(process_image, image_file)
# 关闭线程池,等待所有任务完成
executor.shutdown()
```
这段代码与之前的示例类似,将每个图片的处理任务提交给线程池并行执行。注意在多线程环境下使用共享资源时需要进行适当的同步操作。同时,也请确保在适当的位置关闭文件和线程池,以避免资源泄漏。
阅读全文