File size: 13,690 Bytes
302878f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e55753f
302878f
 
 
 
 
 
 
 
 
 
52e62aa
 
 
302878f
 
 
 
 
 
52e62aa
 
302878f
 
 
 
 
52e62aa
 
 
302878f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e62aa
302878f
 
52e62aa
302878f
52e62aa
302878f
52e62aa
302878f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e62aa
302878f
 
324cb5f
302878f
 
 
 
52e62aa
 
 
 
302878f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e62aa
 
302878f
 
 
 
 
 
 
 
 
324cb5f
302878f
324cb5f
 
da10203
302878f
 
324cb5f
52e62aa
 
da10203
52e62aa
da10203
52e62aa
da10203
302878f
52e62aa
 
da10203
52e62aa
 
 
 
 
 
 
 
 
 
 
 
 
302878f
 
 
52e62aa
302878f
 
 
 
 
 
 
 
 
52e62aa
 
 
302878f
 
 
 
 
 
 
 
 
 
 
 
 
52e62aa
302878f
 
 
 
 
 
 
 
da10203
 
52e62aa
302878f
 
 
da10203
 
302878f
 
 
da10203
 
302878f
 
 
279b335
 
302878f
da10203
302878f
279b335
 
 
 
 
 
302878f
 
 
279b335
 
 
302878f
 
52e62aa
 
302878f
 
 
52e62aa
 
 
302878f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e62aa
302878f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e62aa
 
 
 
302878f
 
 
 
52e62aa
 
 
302878f
 
 
 
 
 
 
52e62aa
 
 
 
302878f
 
 
52e62aa
302878f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import os
import subprocess
import shutil
import nibabel as nib
import matplotlib.pyplot as plt
import glob
import json
import rarfile
import numpy as np
import cv2
from pathlib import Path
import argparse


# ====================================
# Dataset Info [!]
# ====================================
# Dataset: Cephalogram400
# Data (original): https://figshare.com/s/37ec464af8e81ae6ebbf
# Data (HF): https://huggingface.co/datasets/YongchengYAO/Ceph-Biometrics-400
# Format (original): bm
# Format (HF): nii.gz
# ====================================


def convert_bmp_to_niigz(
    bmp_dir,
    niigz_dir,
    slice_dim_type,
    pseudo_voxel_size,
    flip_dim0=False,
    flip_dim1=False,
    swap_dim01=False,
):
    """
    Convert BMP image files to NIfTI (.nii.gz) format.
    This function converts 2D BMP images to 3D NIfTI volumes with specified slice orientation.
    The output NIfTI files will have RAS+ orientation with specified voxel size.
    Args:
        bmp_dir (str): Input directory containing BMP files to convert
        niigz_dir (str): Output directory where NIfTI files will be saved
        slice_dim_type (int): Slice dimension/orientation type:
            0: Sagittal (YZ plane)
            1: Coronal (XZ plane)
            2: Axial (XY plane)
        pseudo_voxel_size (list): List of 3 floats specifying voxel dimensions in mm [x,y,z]
        flip_dim0 (bool, optional): If True, flip image along dimension 0. Defaults to False.
        flip_dim1 (bool, optional): If True, flip image along dimension 1. Defaults to False.
        swap_dim01 (bool, optional): If True, swap dimensions 0 and 1. Defaults to False.
    Returns:
        tuple: Original image dimensions (height, width) of the first converted BMP
    """

    # Validate slice_dim_type
    if slice_dim_type not in [0, 1, 2]:
        raise ValueError("slice_dim_type must be 0, 1, or 2")

    # Convert pseudo_voxel_size to list if it's not already
    pseudo_voxel_size = list(pseudo_voxel_size)

    # Create output directory
    Path(niigz_dir).mkdir(parents=True, exist_ok=True)

    # Get all BMP files
    bmp_files = list(Path(bmp_dir).glob("*.bmp"))
    print(f"Found {len(bmp_files)} .bmp files")

    for bmp_file in bmp_files:
        try:
            print(f"Converting {bmp_file.name}")

            # Read BMP image
            img_2d = cv2.imread(str(bmp_file), cv2.IMREAD_GRAYSCALE)
            img_size_dim0, img_size_dim1 = img_2d.shape

            # Note: this is definitely correct, DO NOT SWAP the order of transformations
            if flip_dim0:
                img_2d = cv2.flip(img_2d, 0)  # 0 means flip vertically
            if flip_dim1:
                img_2d = cv2.flip(img_2d, 1)  # 1 means flip horizontally
            if swap_dim01:  # this line should be AFTER slip_x and slip_y
                img_2d = np.swapaxes(img_2d, 0, 1)

            # Create 3D array based on slice_dim_type
            if slice_dim_type == 0:  # Sagittal (YZ plane)
                img_3d = np.zeros(
                    (1, img_2d.shape[0], img_2d.shape[1]), dtype=img_2d.dtype
                )
                img_3d[0, :, :] = img_2d
            elif slice_dim_type == 1:  # Coronal (XZ plane)
                img_3d = np.zeros(
                    (img_2d.shape[0], 1, img_2d.shape[1]), dtype=img_2d.dtype
                )
                img_3d[:, 0, :] = img_2d
            else:  # Axial (XY plane)
                img_3d = np.zeros(
                    (img_2d.shape[0], img_2d.shape[1], 1), dtype=img_2d.dtype
                )
                img_3d[:, :, 0] = img_2d

            # Create affine matrix for RAS+ orientation
            # Set voxel size to 0.1mm in all dimensions
            affine = np.diag(pseudo_voxel_size + [1])

            # Create NIfTI image
            nii_img = nib.Nifti1Image(img_3d, affine)

            # Set header information
            nii_img.header.set_zooms(pseudo_voxel_size)

            # Save as NIfTI file
            output_file = Path(niigz_dir) / f"{bmp_file.stem}.nii.gz"
            nib.save(nii_img, str(output_file))
            print(f"Saved to {output_file}")

        except Exception as e:
            print(f"Error converting {bmp_file.name}: {e}")

    return img_size_dim0, img_size_dim1



def process_landmarks_data(
    landmarks_txt_dir: str,
    landmarks_json_dir: str,
    n: int,
    img_sizes,
    flip_dim0=False,
    flip_dim1=False,
    swap_dim01=False,
) -> None:
    """
    Read landmark points from all txt files in a directory and save as JSON files.

    Args:
        in_dir (str): Directory containing the txt files
        out_dir (str): Directory where JSON files will be saved
        n (int): Number of lines to read from each file
        height_width_orig: Original height and width of the image
        swap_xy (bool): Whether to swap x and y coordinates
        slip_x (bool): Whether to flip coordinates along x-axis
        slip_y (bool): Whether to flip coordinates along y-axis
    """
    (
        os.makedirs(landmarks_json_dir, exist_ok=True)
        if not os.path.exists(landmarks_json_dir)
        else None
    )

    for txt_file in glob.glob(os.path.join(landmarks_txt_dir, "*.txt")):

        landmarks = {}
        filename = os.path.basename(txt_file)
        json_path = os.path.join(landmarks_json_dir, filename.replace(".txt", ".json"))

        try:
            with open(txt_file, "r") as f:
                for i in range(n):
                    line = f.readline().strip()
                    if not line:
                        break
                    # Note: this is correct, DO NOT SWAP idx_dim0 and idx_dim1
                    # Assuming an image with height and width:
                    # - The data array read from bmp file is of size (height, width) -- dim0 is height, dim1 is width
                    # - The landmark coordinates are defined as the indices in width (dim1) and height (dim0) directions
                    idx_dim1, idx_dim0 = map(int, line.split(","))

                    # Apply transformations
                    # Note: this is correct
                    # DO NOT SWAP the order of transformations
                    if flip_dim0:
                        idx_dim0 = img_sizes[0] - idx_dim0
                    if flip_dim1:
                        idx_dim1 = img_sizes[1] - idx_dim1
                    if swap_dim01:  # this line should be AFTER slip_x and slip_y
                        idx_dim0, idx_dim1 = idx_dim1, idx_dim0

                    # Save landmark coordinates in 0-based indices
                    landmarks[f"P{i+1}"] = [
                        coord - 1 for coord in [1, idx_dim0, idx_dim1]
                    ]

            # This data structure is designed to be compatible with biometric data constructed from segmentation masks
            json_dict = {
                "slice_landmarks_x": [
                    {
                        "slice_idx": 1,
                        "landmarks": landmarks,
                    },
                ],
                "slice_landmarks_y": [],
                "slice_landmarks_z": [],
            }

            # Save to JSON
            with open(json_path, "w") as f:
                json.dump(json_dict, f, indent=4)

        except FileNotFoundError:
            print(f"Error: File {txt_file} not found")
        except ValueError:
            print(f"Error: Invalid format in file {txt_file}")
        except Exception as e:
            print(f"Error reading file {txt_file}: {str(e)}")


def plot_sagittal_slice_with_landmarks(
    nii_path: str, json_path: str, fig_path: str = None
):
    """Plot first slice from NIfTI file and overlay landmarks from JSON file.

    Args:
        nii_path (str): Path to .nii.gz file
        json_path (str): Path to landmarks JSON file
        fig_path (str, optional): Path to save the plot. If None, displays plot
    """
    # Load NIfTI image and extract first slice
    nii_img = nib.load(nii_path)
    slice_data = nii_img.get_fdata()[0, :, :]

    # Load landmark coordinates from JSON
    with open(json_path, "r") as f:
        landmarks_json = json.load(f)

    # Setup visualization
    plt.figure(figsize=(12, 12))
    plt.imshow(
        slice_data.T, cmap="gray", origin="lower"
    )  # the transpose is necessary only for visualization

    # Extract and plot landmark coordinates
    coords_dim0 = []
    coords_dim1 = []
    landmarks = landmarks_json["slice_landmarks_x"][0]["landmarks"]
    for point_id, coords in landmarks.items():
        if len(coords) == 3:  # Check for valid [1, x, y] format
            # Note: this is definitely correct, DO NOT SWAP coords[1] and coords[2]
            coords_dim0.append(coords[1])
            coords_dim1.append(coords[2])

    # Add landmarks and labels
    plt.scatter(
        coords_dim0,
        coords_dim1,
        facecolors="#18A727",
        edgecolors="black",
        marker="o",
        s=80,
        linewidth=1.5,
    )
    for i, (x, y) in enumerate(zip(coords_dim0, coords_dim1), 1):
        plt.annotate(
            f"$\\mathbf{{{i}}}$",
            (x, y),
            xytext=(2, 2),
            textcoords="offset points",
            color="#FE9100",
            fontsize=14,
        )

    # Configure plot appearance
    plt.xlabel("Anterior →", fontsize=14)
    plt.ylabel("Superior →", fontsize=14)
    plt.margins(0)

    # Save or display the plot
    plt.savefig(fig_path, bbox_inches="tight", dpi=300)
    print(f"Plot saved to: {fig_path}")
    plt.close()


def plot_sagittal_slice_with_landmarks_batch(
    image_dir: str, landmark_dir: str, fig_dir: str
):
    """Plot all cases from given directories.

    Args:
        image_dir (str): Directory containing .nii.gz files
        landmark_dir (str): Directory containing landmark JSON files
        fig_dir (str): Directory to save output figures

    """
    # Create output directory if it doesn't exist
    os.makedirs(fig_dir, exist_ok=True)

    # Process each .nii.gz file
    for nii_path in glob.glob(os.path.join(image_dir, "*.nii.gz")):
        base_name = os.path.splitext(os.path.splitext(os.path.basename(nii_path))[0])[0]
        json_path = os.path.join(landmark_dir, f"{base_name}.json")
        fig_path = os.path.join(fig_dir, f"{base_name}.png")

        # Plot and save
        if os.path.exists(json_path):
            plot_sagittal_slice_with_landmarks(nii_path, json_path, fig_path)
        else:
            print(f"Warning: No landmark file found for {base_name}")


def download_and_extract(dataset_dir, dataset_name):
    # Download files
    print(f"Downloading {dataset_name} dataset to {dataset_dir}...")

    # ====================================
    # Add download logic here [!]
    # ====================================
    # Download the file using curl
    url = "https://figshare.com/ndownloader/articles/3471833?private_link=37ec464af8e81ae6ebbf"
    output_file = "Cephalogram400.zip"
    subprocess.run(["curl", url, "-o", output_file], check=True)

    # Extract the ZIP file
    print("Extracting ZIP file...")
    subprocess.run(["unzip", output_file], check=True)

    # Find and extract all RAR files
    print("Extracting RAR files...")
    for file in os.listdir("."):
        if file.endswith(".rar"):
            with rarfile.RarFile(file) as rf:
                rf.extractall()

    # Create the Images-raw directory
    os.makedirs("Images-raw", exist_ok=True)

    # Move all BMP files from RawImage to Images-raw using glob
    for src_path in glob.glob(f"RawImage/**/*.bmp", recursive=True):
        shutil.move(src_path, os.path.join("Images-raw", os.path.basename(src_path)))

    # Convert BMP files to 3D nii.gz
    Flag_flip_dim0 = True
    Flag_flip_dim1 = False
    Flag_swap_dim01 = True
    img_size_dim0, img_size_dim1 = convert_bmp_to_niigz(
        "Images-raw",
        "Images",
        slice_dim_type=0,
        pseudo_voxel_size=[0.1, 0.1, 0.1],
        flip_dim0=Flag_flip_dim0,
        flip_dim1=Flag_flip_dim1,
        swap_dim01=Flag_swap_dim01,
    )

    # Read landmark points from txt files and save as JSON
    process_landmarks_data(
        "400_senior",
        "Landmarks",
        19,
        img_sizes=[img_size_dim0, img_size_dim1],
        flip_dim0=Flag_flip_dim0,
        flip_dim1=Flag_flip_dim1,
        swap_dim01=Flag_swap_dim01,
    )

    # Plot slices with landmarks
    plot_sagittal_slice_with_landmarks_batch("Images", "Landmarks", "Landmarks-fig")

    # Clean up
    for dir_name in [
        "RawImage",
        "400_junior",
        "400_senior",
        "Images-raw",
        "EvaluationCode",
    ]:
        shutil.rmtree(dir_name, ignore_errors=True)
    for file in os.listdir("."):
        if file.endswith((".rar", ".zip")):
            os.remove(file)
    # ====================================

    print(f"Download and extraction completed for {dataset_name}")


if __name__ == "__main__":
    # Set up argument parser
    parser = argparse.ArgumentParser(description="Download and extract dataset")
    parser.add_argument(
        "-d",
        "--dir_datasets_data",
        help="Directory path where datasets will be stored",
        required=True,
    )
    parser.add_argument(
        "-n",
        "--dataset_name",
        help="Name of the dataset",
        required=True,
    )
    args = parser.parse_args()

    # Create dataset directory
    dataset_dir = os.path.join(args.dir_datasets_data, args.dataset_name)
    os.makedirs(dataset_dir, exist_ok=True)

    # Change to dataset directory
    os.chdir(dataset_dir)

    # Download and extract dataset
    download_and_extract(dataset_dir, args.dataset_name)