File size: 5,348 Bytes
0c73046 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | import argparse
import cv2
import glob
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm
def process_image(img_path, root, check):
"""Обрабатывает одно изображение.
Args:
img_path (str): Путь к изображению.
root (str): Корневая папка для относительного пути.
check (bool): Проверять ли изображение на ошибки.
Returns:
tuple: (status, img_name, error_message) - status может быть 'ok', 'error', 'none'
"""
status = True
error_msg = None
if check:
# read the image once for check, as some images may have errors
try:
img = cv2.imread(img_path)
except (IOError, OSError) as error:
status = False
error_msg = f'Read {img_path} error: {error}'
if img is None:
status = False
error_msg = f'Img is None: {img_path}'
if status:
# get the relative path
img_name = os.path.relpath(img_path, root)
return ('ok', img_name, None)
else:
return ('error', None, error_msg)
def main(args):
# Загружаем существующие записи, если файл уже существует
existing_entries = set()
if os.path.exists(args.meta_info):
with open(args.meta_info, 'r') as f:
existing_entries = set(line.strip() for line in f if line.strip())
# Собираем все пути изображений
all_tasks = []
for folder, root in zip(args.input, args.root):
img_paths = sorted(glob.glob(os.path.join(folder, '*')))
for img_path in img_paths:
# Проверяем, есть ли уже запись для этого изображения
img_name = os.path.relpath(img_path, root)
if img_name in existing_entries:
continue
all_tasks.append((img_path, root, args.check))
if not all_tasks:
print('Все изображения уже обработаны или изображения не найдены')
return
# Обрабатываем изображения в потоках
results = []
errors = []
with ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = {
executor.submit(process_image, img_path, root, check): img_path
for img_path, root, check in all_tasks
}
with tqdm(total=len(all_tasks), desc='Генерация мета-информации', unit='img') as pbar:
for future in as_completed(futures):
try:
status, img_name, error_msg = future.result()
if status == 'ok':
results.append(img_name)
else:
errors.append(error_msg)
if error_msg:
tqdm.write(error_msg)
pbar.set_postfix({'обработано': len(results), 'ошибок': len(errors)})
except Exception as e:
path = futures[future]
error_msg = f'Ошибка при обработке {path}: {e}'
errors.append(error_msg)
tqdm.write(error_msg)
pbar.set_postfix({'обработано': len(results), 'ошибок': len(errors)})
finally:
pbar.update(1)
# Записываем результаты в файл
mode = 'a' if existing_entries else 'w'
with open(args.meta_info, mode) as txt_file:
for img_name in sorted(results):
txt_file.write(f'{img_name}\n')
print(f'Обработано: {len(results)}, ошибок: {len(errors)}')
if __name__ == '__main__':
"""Generate meta info (txt file) for only Ground-Truth images.
It can also generate meta info from several folders into one txt file.
Multithreaded version.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--input',
nargs='+',
default=['datasets/DF2K/DF2K_HR', 'datasets/DF2K/DF2K_multiscale'],
help='Input folder, can be a list')
parser.add_argument(
'--root',
nargs='+',
default=['datasets/DF2K', 'datasets/DF2K'],
help='Folder root, should have the length as input folders')
parser.add_argument(
'--meta_info',
type=str,
default='datasets/DF2K/meta_info/meta_info_DF2Kmultiscale.txt',
help='txt path for meta info')
parser.add_argument('--check', action='store_true', help='Read image to check whether it is ok')
parser.add_argument('--workers', type=int, default=None, help='Number of worker threads (default: CPU count)')
args = parser.parse_args()
assert len(args.input) == len(args.root), ('Input folder and folder root should have the same length, but got '
f'{len(args.input)} and {len(args.root)}.')
os.makedirs(os.path.dirname(args.meta_info), exist_ok=True)
if args.workers is None:
import multiprocessing
args.workers = multiprocessing.cpu_count()
main(args)
|