Newer
Older
VolumeRendering_in_Unity / .ipynb_checkpoints / Untitled-checkpoint.ipynb
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-16T07:13:56.559086Z",
     "start_time": "2021-03-16T07:13:39.464085Z"
    }
   },
   "outputs": [],
   "source": [
    "from glob import glob\n",
    "import pydicom\n",
    "import os.path as osp\n",
    "import numpy as np\n",
    "\n",
    "out_name = \"3D.raw\"\n",
    "out_base_path = \"./Assets/\"\n",
    "dicom_dir = \"D:3Dsyokudo/\"\n",
    "dicom_file_list = glob(osp.join(dicom_dir, \"*\"))\n",
    "dicom_file_list = sorted(dicom_file_list, key=lambda x: float(pydicom.read_file(x).SliceLocation), reverse=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-16T07:09:08.808051Z",
     "start_time": "2021-03-16T07:09:07.881746Z"
    }
   },
   "outputs": [],
   "source": [
    "height, width = pydicom.read_file(dicom_file_list[0]).pixel_array.shape\n",
    "depth = len(dicom_file_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-14T13:56:53.161775Z",
     "start_time": "2021-03-14T13:56:46.536770Z"
    }
   },
   "outputs": [],
   "source": [
    "stack_img = np.stack([pydicom.read_file(x).pixel_array + pydicom.read_file(x).RescaleIntercept for x in dicom_file_list], axis=2)\n",
    "row_format = stack_img.transpose(1, 0, 2).reshape(-1, order=\"F\")\n",
    "\n",
    "# ウィンドウ使うバージョン2\n",
    "window_max = 330\n",
    "window_min = -270\n",
    "\n",
    "scaled_row = row_format.copy().astype(np.float)\n",
    "scaled_row[scaled_row < window_min] = window_min\n",
    "scaled_row[window_max < scaled_row] = window_max\n",
    "\n",
    "scaled_row -= np.mean(scaled_row)\n",
    "scaled_row = scaled_row / (np.max(np.abs(scaled_row)) + 1e-5) * (2 ** 16)\n",
    "scaled_row -= np.mean(scaled_row)\n",
    "scaled_row = np.clip(scaled_row, 0, 2 ** 16).astype(np.uint16)\n",
    "scaled_row.tofile(osp.join(out_base_path, out_name))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}