{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"!conda install -c conda-forge gdcm -y\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport pydicom as dicom\nfrom pydicom.data import get_testdata_files\n\nimport os\nfrom tqdm import tqdm\nimport glob","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def load_image(path):\n    ds=dicom.dcmread(path)\n    img = ds.pixel_array                                  # Now, img is pixel_array. it is input of our demo code\n                                                          # Convert pixel_array (img) to -> gray image (img_2d_scaled)\n    img_2d = img.astype(float)                            # Step 1. Convert to float to avoid overflow or underflow losses.\n    img = (np.maximum(img_2d,0) / img_2d.max()) * 255.0   # Step 2. Rescaling grey scale between 0-255\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_image(path):\n    ds=dicom.dcmread(path)\n    img = ds.pixel_array                                  # Now, img is pixel_array. it is input of our demo code\n                                                          # Convert pixel_array (img) to -> gray image (img_2d_scaled)\n    img_2d = img.astype(float)                            # Step 1. Convert to float to avoid overflow or underflow losses.\n    img_2d = img_2d - img_2d.min()\n    img = (img_2d / img_2d.max()) * 255.0   # Step 2. Rescaling grey scale between 0-255\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 胸を楕円と仮定.下記ラマヌジャンの近似式により胸囲を計算.\n# https://www.mathsisfun.com/geometry/ellipse-perimeter.html\n# - Approximation 2\ndef chest_circumference(a, b):\n    return np.pi*(3*(a + b) - np.sqrt((3*a+b) * (a+3*b)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# f, ax= plt.subplots(figsize=(6,6))\ncolumns = ['PatientID', 'Chest']\nchest_df = pd.DataFrame(index=[], columns=columns)\n\npath='../input/osic-pulmonary-fibrosis-progression/train/'\n\nimg_list = []\nfor patient in os.listdir(path):\n    path='../input/osic-pulmonary-fibrosis-progression/train/'\n    path = path + patient\n    # 胸のCT画像取得のため中間地点のdcmを取得\n    dcm_files = sorted(glob.glob(path+'/*.dcm'))\n    glob.glob(path+'/*.dcm')\n    filename = []\n    for dcm_file in dcm_files:\n        file = os.path.splitext(os.path.basename(dcm_file))[0]\n        filename.append(int(file))\n    chest_loc = int(max(filename) / 2)\n    img_path = os.path.join(path, str(chest_loc))\n    img_path = img_path + '.dcm' # このパスの画像に対して胸囲を計算する\n    ds = dicom.dcmread(img_path)\n    tag_list = ['PixelSpacing']\n    pixel_spacing = ds.PixelSpacing\n    rows = ds.Rows\n    cols = ds.Columns\n    img = ds.pixel_array                                \n\n    img = load_image(img_path)\n    ret2,img_thr = cv2.threshold(img.astype('uint8'), 0, 255, cv2.THRESH_OTSU)\n    #ret2,img_thr = cv2.threshold(img.astype('uint8'), 0, 255, cv2.THRESH_TRIANGLE)\n    #img_thr = cv2.threshold(img.astype('uint8'), 0, 255, 0)[1]\n    #img_d = np.where(img<140,0,img)\n    #img_r = np.where(img_d>170,0,img_d)\n    #img_thr = np.where(img_r<1,0,255)\n    \n    # CT画像全体の半分の位置のたて、横の値を取得\n    width = img_thr[int(rows / 2),:]\n    height = img_thr[:, int(cols / 2)]\n\n    width_white = np.where(width==255)[0] # CT画像の横の中心部分を抽出\n    height_white = np.where(height==255)[0]\n    \n    \n    if (len(width_white) != 0) & (len(height_white) != 0):\n        chest_half_height = (max(height_white) - min(height_white)) / 2\n        chest_half_height = chest_half_height * pixel_spacing[1] / 10\n        chest_half_width = (max(width_white) - min(width_white)) / 2 # 胸部の横の長さの半分を取得\n        chest_half_width = chest_half_width * pixel_spacing[0] / 10 # convert pixel to cm\n\n        chest = chest_circumference(chest_half_width, chest_half_height)    \n        chest_df = chest_df.append({'PatientID': patient, 'Chest': chest}, ignore_index=True)\n    else:\n        print(patient)\n        #print(width)\n        #print(np.unique(img_thr))\n        #print(np.unique(img))\n        #print(ret2)\n        #plt.imshow(img_thr)\n        #print(width)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"chest_df.to_csv(\"chest_df.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}