详解Python如何批量检查图像是否可用
作者:SpikeKing 时间:2021-10-03 13:42:07
数据集中的图像,一般不可用在以下3个方面:
1.图像过小
2.无法打开
3.“Premature end of JPEG file”
这些图像可能会导致模型的学习异常,因此,使用多进程检查数据集中的每张图像,是很有必要的。
具体逻辑如下:
遍历文件夹,多进程处理每一张图像
判断图像是否可读,是否支持resize尺寸,边长是否满足
判断JPG图像是否Premature end
删除错误图像
脚本如下:
#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2020. All rights reserved.
Created by C. L. Wang on 10.11.20
"""
import argparse
import os
from multiprocessing import Pool
import cv2
def traverse_dir_files(root_dir, ext=None):
"""
列出文件夹中的文件, 深度遍历
:param root_dir: 根目录
:param ext: 后缀名
:return: [文件路径列表, 文件名称列表]
"""
names_list = []
paths_list = []
for parent, _, fileNames in os.walk(root_dir):
for name in fileNames:
if name.startswith('.'): # 去除隐藏文件
continue
if ext: # 根据后缀名搜索
if name.endswith(tuple(ext)):
names_list.append(name)
paths_list.append(os.path.join(parent, name))
else:
names_list.append(name)
paths_list.append(os.path.join(parent, name))
return paths_list, names_list
def check_img(path, size):
"""
检查图像
"""
is_good = True
try:
img_bgr = cv2.imread(path)
h, w, _ = img_bgr.shape
if h < size or w < size:
is_good = False
_ = cv2.resize(img_bgr, (size, size))
except Exception as e:
is_good = False
if path.endswith("jpg"):
with open(path, 'rb') as f:
check_chars = f.read()[-2:]
if check_chars != b'\xff\xd9':
print('[Info] Not complete jpg image')
is_good = False
if not is_good:
print('[Info] error path: {}'.format(path))
os.remove(path)
def check_error(img_dir, n_prc, size):
"""
检查错误图像的数量
"""
print('[Info] 处理文件夹路径: {}'.format(img_dir))
paths_list, names_list = traverse_dir_files(img_dir)
print('[Info] 数据总量: {}'.format(len(paths_list)))
pool = Pool(processes=n_prc) # 多线程下载
for idx, path in enumerate(paths_list):
pool.apply_async(check_img, (path, size))
if (idx+1) % 1000 == 0:
print('[Info] idx: {}'.format(idx+1))
pool.close()
pool.join()
print('[Info] 数据处理完成: {}'.format(img_dir))
def parse_args():
"""
处理脚本参数,支持相对路径
:return: in_folder 输入文件夹, size 尺寸, n_prc 进程数
"""
parser = argparse.ArgumentParser(description='检查图片脚本')
parser.add_argument('-i', dest='in_folder', required=True, help='输入文件夹', type=str)
parser.add_argument('-p', dest='n_prc', required=False, default=100, help='进程数', type=str)
parser.add_argument('-s', dest='size', required=False, default=50, help='最小边长', type=str)
args = parser.parse_args()
in_folder = args.in_folder
size = int(args.size)
n_prc = int(args.n_prc)
print("[Info] 文件路径:{}".format(in_folder))
print("[Info] 进程数: {}".format(n_prc))
print("[Info] 边长: {}".format(size))
return in_folder, n_prc, size
def main():
arg_in, n_prc, size = parse_args()
check_error(arg_in, n_prc, size)
if __name__ == '__main__':
main()
来源:https://blog.csdn.net/caroline_wendy/article/details/120282256
标签:Python,批量,检查,图像
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现压缩文件夹与解压缩zip文件的方法
2023-07-31 20:43:09
网页特效文字之—银箔字
2013-08-07 00:21:39
![](https://img.aspxhome.com/file/UploadPic/20072/20072311613309s.jpg)
如何获取机器的网络配置属性?
2009-11-23 20:44:00
WEB界面设计五种特征
2010-03-16 12:34:00
Python3 列表list合并的4种方法
2021-03-28 13:29:43
MySQL安全性指南(3)(转)
2010-07-26 13:07:00
较完善的日历组件js源码(兼容)
2010-08-08 08:43:00
利用Python开发实现简单的记事本
2023-07-02 13:27:27
![](https://img.aspxhome.com/file/2023/4/59654_0s.png)
PHP7正式版测试,性能惊艳!
2023-09-12 07:41:43
![](https://img.aspxhome.com/file/2023/4/55634_0s.png)
Python NumPy中的随机数及ufuncs函数使用示例详解
2021-09-22 15:29:08
![](https://img.aspxhome.com/file/2023/8/93588_0s.png)
Softmax函数原理及Python实现过程解析
2022-12-15 02:18:24
![](https://img.aspxhome.com/file/2023/8/66318_0s.png)
Go语言sort包函数使用示例
2023-10-15 03:29:59
初学者快看,Python下划线的五个作用介绍
2023-03-03 18:23:40
![](https://img.aspxhome.com/file/2023/7/68297_0s.jpg)
python2和python3在处理字符串上的区别详解
2021-10-07 03:29:31
python 用pandas实现数据透视表功能
2022-04-23 02:49:40
![](https://img.aspxhome.com/file/2023/7/65217_0s.png)
Python中文件的写入读取以及附加文字方法
2021-03-03 12:05:15
如何将anaconda安装配置的mmdetection环境离线拷贝到另一台电脑
2022-12-16 00:48:47
![](https://img.aspxhome.com/file/2023/2/82922_0s.png)
详解python连接telnet和ssh的两种方式
2023-02-10 01:27:14
python读取图片任意范围区域
2023-07-16 06:26:21
![](https://img.aspxhome.com/file/2023/3/95193_0s.jpg)
ORACLE常见错误代码的分析与解决三
2010-07-26 13:28:00