File size: 12,727 Bytes
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
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/Cephalogram400
# Format (original): bm
# Format (HF): nii.gz
# ====================================


def convert_bmp_to_niigz(
    bmp_dir,
    niigz_dir,
    slice_dim_type,
    pseudo_voxel_size,
    slip_x=False,
    slip_y=False,
    swap_xy=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:
        in_dir (str): Input directory containing BMP files to convert
        out_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]
        swap_xy (bool, optional): If True, swap X and Y dimensions. Defaults to False.
        slip_x (bool, optional): If True, flip image along X axis. Defaults to False.
        slip_y (bool, optional): If True, flip image along Y axis. 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)
            height_orig, width_orig = img_2d.shape

            # Note: this is definitely correct, DO NOT SWAP the order of transformations
            if slip_x:
                img_2d = cv2.flip(img_2d, 0)  # 0 means flip vertically
            if slip_y:
                img_2d = cv2.flip(img_2d, 1)  # 1 means flip horizontally
            if swap_xy:  # 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 height_orig, width_orig


def process_landmarks_data(
    landmarks_txt_dir: str,
    landmarks_json_dir: str,
    n: int,
    height_width_orig,
    slip_x=False,
    slip_y=False,
    swap_xy=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")):
        result = {}
        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 definitely correct, DO NOT SWAP idx_dim1 and idx_dim2
                    # Assuming an image with height and width:
                    # - The data array read from bmp file is of size (height, width) -- dim1 is height, dim2 is width
                    # - The landmark coordinates are defined as the indices in width (coordinate 1) and height (coordinate 2) directions
                    idx_dim2, idx_dim1 = map(int, line.split(","))

                    # Apply transformations
                    # Note: this is definitely correct, DO NOT SWAP the order of transformations
                    if slip_x:
                        idx_dim1 = height_width_orig[0] - idx_dim1
                    if slip_y:
                        idx_dim2 = height_width_orig[1] - idx_dim2
                    if swap_xy:  # this line should be AFTER slip_x and slip_y
                        idx_dim1, idx_dim2 = idx_dim2, idx_dim1

                    result[f"P{i+1}"] = [1, idx_dim1, idx_dim2]

            # Save to JSON
            with open(json_path, "w") as f:
                json.dump(result, 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_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.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
    x_coords = []
    y_coords = []
    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]
            x_coords.append(coords[1])
            y_coords.append(coords[2])

    # Add landmarks and labels
    plt.scatter(
        x_coords,
        y_coords,
        facecolors="#18A727",
        edgecolors="black",
        marker="o",
        s=30,
        linewidth=1,
    )
    for i, (x, y) in enumerate(zip(x_coords, y_coords), 1):
        plt.annotate(
            f"{i}", (x, y), xytext=(2, 2), textcoords="offset points", color="#FE9100"
        )

    # Configure plot appearance
    plt.axis("on")
    plt.xlabel("Posterior to Anterior")
    plt.ylabel("Inferior to Superior")

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

    plt.close()


def plot_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_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
    height_orig, width_orig = convert_bmp_to_niigz(
        "Images-raw",
        "Images",
        slice_dim_type=0,
        pseudo_voxel_size=[0.1, 0.1, 0.1],
        slip_x=True,
        slip_y=False,
        swap_xy=True,
    )

    # Read landmark points from txt files and save as JSON
    process_landmarks_data(
        "400_senior",
        "Landmarks",
        19,
        height_width_orig=[height_orig, width_orig],
        slip_x=True,
        slip_y=False,
        swap_xy=True,
    )

    # Plot slices with landmarks
    plot_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)