Repository navigation
Expand file tree
/
Copy pathpreprocess_qatacov.py
More file actions
140 lines (113 loc) · 5.08 KB
/
Copy pathpreprocess_qatacov.py
File metadata and controls
140 lines (113 loc) · 5.08 KB
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
140
import argparse
import os
import sys
import numpy as np
import pandas as pd
from PIL import Image
from tqdm import tqdm
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from datasets import DatasetFactory
from datasets.QaTaCovPreprocess import QaTaCov2DSet
from transforms import QaTaCov as QaTaCovTransforms
from types import SimpleNamespace
from config import Config
def build_config(root_path: str, image_size: list[int]):
return SimpleNamespace(
dataset={
'name': 'QaTaCovPreprocess',
'path': root_path,
'batch_size': 1,
'image_size': image_size,
}
)
def save_sample(sample, out_dir: str, split: str, index: int, preserve_filenames: bool):
image = sample['image']
label = sample['label']
image_path = sample.get('image_path', '')
label_path = sample.get('label_path', '')
image = image.squeeze(0).cpu().numpy()
label = label.squeeze(0).cpu().numpy()
#image = (image - image.min()) / (image.max() - image.min() + 1e-8)
image = (image).astype(np.uint8)
label = label.astype(np.uint8)
images_dir = os.path.join(out_dir, 'Images')
masks_dir = os.path.join(out_dir, 'Ground-truths')
os.makedirs(images_dir, exist_ok=True)
os.makedirs(masks_dir, exist_ok=True)
if preserve_filenames and image_path and label_path:
image_name = os.path.basename(image_path)
mask_name = f"mask_{image_name}"
else:
image_name = f"{index:06d}.png"
mask_name = f"mask_{image_name}"
image_path = os.path.join(images_dir, image_name)
mask_path = os.path.join(masks_dir, mask_name)
Image.fromarray(image).save(image_path)
Image.fromarray(label).save(mask_path)
return image_name
def append_metadata(rows, split: str, image_name: str, report: str):
rows.append({
'Image': image_name,
'Split': split,
'Report': report
})
def main():
parser = argparse.ArgumentParser(description='Offline preprocessing for QaTaCov')
parser.add_argument(
'--root',
type=str,
default=os.path.join(os.path.dirname(__file__), '..', 'QaTaCov19-v2', 'QaTa-COV19-v2'),
help='Path to QaTa-COV19-v2 dataset root'
)
parser.add_argument(
'--config',
type=str,
default=None,
help='Optional config JSON to load dataset settings (overrides --root/--image_size)'
)
parser.add_argument('--out', type=str, default=None, help='Output folder for preprocessed data')
parser.add_argument('--image_size', nargs=2, type=int, default=[224, 224])
parser.add_argument('--validation', action='store_true')
parser.add_argument('--max_items', type=int, default=None, help='Optional limit per split')
parser.add_argument('--use_test_transforms', action='store_true', help='Use test transforms for all splits')
parser.add_argument('--preserve_filenames', action='store_true', help='Preserve original filenames')
args = parser.parse_args()
if args.config:
config = Config(args.config)
args.root = config.dataset['path']
args.image_size = config.dataset.get('image_size', args.image_size)
if hasattr(config, 'preprocess'):
args.out = config.preprocess.get('output_path', args.out)
args.use_test_transforms = config.preprocess.get('use_test_transforms', args.use_test_transforms)
args.preserve_filenames = config.preprocess.get('preserve_filenames', args.preserve_filenames)
else:
config = build_config(args.root, args.image_size)
if not args.out:
raise ValueError("Output path not provided. Use --out or set preprocess.output_path in config.")
dataset = DatasetFactory.create_instance(config, args.validation)
if args.use_test_transforms:
image_size = args.image_size
test_transforms = QaTaCovTransforms(mode='test').transform(image_size=image_size)
train_text_map = dataset.train_set.text_map
test_text_map = dataset.test_set.text_map
dataset.train_set = QaTaCov2DSet(dataset.train_images, dataset.train_labels, train_text_map, test_transforms)
if args.validation:
dataset.val_set = QaTaCov2DSet(dataset.val_images, dataset.val_labels, train_text_map, test_transforms)
dataset.test_set = QaTaCov2DSet(dataset.test_images, dataset.test_labels, test_text_map, test_transforms)
metadata_rows = []
for split in ['train', 'val', 'test']:
if split == 'val' and not args.validation:
continue
data = getattr(dataset, f"{split}_set")
max_items = args.max_items or len(data)
for idx in tqdm(range(max_items), desc=f"Saving {split}"):
sample = data[idx]
image_name = save_sample(sample, args.out, split, idx, args.preserve_filenames)
report = sample.get('text', '')
append_metadata(metadata_rows, split, image_name, report)
if metadata_rows:
split_path = os.path.join(args.out, 'qatacov_split.xlsx')
df = pd.DataFrame(metadata_rows)
df.to_excel(split_path, index=False)
if __name__ == '__main__':
main()