Newer
Older
VolumeRendering_in_Unity / InitUnitySettings / main.py
from glob import glob
import pydicom
import json
import os.path as osp
import numpy as np
import argparse
from GUI import GUIController

parser = argparse.ArgumentParser()
parser.add_argument("--dicom_dir", type=str, required=True, help="DICOMファイルへのパス")
parser.add_argument("--output_dir", type=str, default="../Assets", help='モデルファイルの出力先を指定')
parser.add_argument("--resized_button_height", type=int, default=72, help="メニューボタンの高さ")
parser.add_argument("--resized_button_width", type=int, default=157, help="メニューボタンの幅")
parser.add_argument("--magnification_ratio", type=int, default=4, help='ダブルクリック時の拡大倍率(偶数のほうがいいかも)')
parser.add_argument("--window_low", type=float, default=-500.0, help="ウィンドウサイズの下限")
parser.add_argument("--window_high", type=float, default=500.0, help="ウィンドウサイズの上限")
parser.add_argument("--median_filter", action="store_true", help="メジアンフィルタを")
args = parser.parse_args()


def makePatientRowFile(args):
    dicom_file_list = glob(osp.join(args.dicom_dir, "*"))
    dicom_file_list = sorted(dicom_file_list, key=lambda x: float(pydicom.read_file(x).SliceLocation), reverse=False)
    sample_dcm1, sample_dcm2 = pydicom.read_file(dicom_file_list[0]), pydicom.read_file(dicom_file_list[1])

    height, width = pydicom.read_file(dicom_file_list[0]).pixel_array.shape
    depth = len(dicom_file_list)

    x_scale_f, y_scale_f = sample_dcm1.PixelSpacing
    z_scale_f = abs(sample_dcm1.ImagePositionPatient[2] - sample_dcm2.ImagePositionPatient[2])

    stack_img = np.stack(
        [np.fliplr(pydicom.read_file(x).pixel_array) + pydicom.read_file(x).RescaleIntercept for x in dicom_file_list], axis=2)
    row_format = stack_img.transpose((1, 0, 2)).reshape(-1, order="F")

    # ウィンドウ使うバージョン
    window_max = sample_dcm1.WindowCenter + sample_dcm1.WindowWidth
    window_min = sample_dcm1.WindowCenter - sample_dcm1.WindowWidth

    scaled_row = row_format.copy().astype(np.float)
    scaled_row[scaled_row < window_min] = window_min
    scaled_row[window_max < scaled_row] = window_max

    scaled_row -= np.mean(scaled_row)
    scaled_row = scaled_row / (np.max(np.abs(scaled_row)) + 1e-5) * (2 ** 16)
    scaled_row -= np.mean(scaled_row)
    scaled_row = np.clip(scaled_row, 0, 2 ** 16).astype(np.uint16)
    scaled_row.tofile(osp.join(args.output_dir, "3dmodel.raw"))

    to_json = {
        "x_scale": width * x_scale_f,
        "y_scale": height * y_scale_f,
        "z_scale": depth * z_scale_f
    }

    return to_json


if __name__ == "__main__":
    setting_json = makePatientRowFile(args)
    gui = GUIController(args, setting_json)
    gui.run()