|
|
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: |
|
|
|
|
|
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: |
|
|
|
|
|
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) |
|
|
|
|
|
|