{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# common packages \nimport numpy as np \nimport os\nimport copy\nfrom math import *\nimport matplotlib.pyplot as plt\nimport imageio.v2 as imageio\nfrom functools import reduce\nfrom glob import glob\n\nimport cv2\nimport numpy as np\n\n# reading in dicom files\nimport pydicom\n\n# skimage image processing packages\nfrom skimage import measure, morphology\nfrom skimage.morphology import ball, binary_closing\nfrom skimage.measure import label, regionprops\n\n# scipy linear algebra functions \nfrom scipy.linalg import norm\nimport scipy.ndimage\n\n# ipywidgets for some interactive plots\nfrom ipywidgets.widgets import * \nimport ipywidgets as widgets\n\nimport plotly\nfrom plotly.graph_objs import *\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-09-14T15:21:12.96922Z","iopub.execute_input":"2026-09-14T15:21:12.969546Z","iopub.status.idle":"2026-09-14T15:21:13.047293Z","shell.execute_reply.started":"2026-09-14T15:21:12.969519Z","shell.execute_reply":"2026-09-14T15:21:13.046151Z"},"_kg_hide-output":true,"_kg_hide-input":false},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\npatient_id = '857c0f7e-c11'\npatient_folder = f'/kaggle/input/competitions/rsna-knee-abnormality-detection/test_series/1.2.826.0.1.3680043.8.498.10047035057544427318018579121635276191/'\ndata_paths = glob(patient_folder + '/*/*.dcm')\n\n# Print out the first 5 file names to verify we're in the right folder.\nprint (f'Total of {len(data_paths)} DICOM images.\\nFirst 5 filenames:' )\ndata_paths[:5]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-14T16:27:11.089873Z","iopub.execute_input":"2026-09-14T16:27:11.090238Z","iopub.status.idle":"2026-09-14T16:27:11.118216Z","shell.execute_reply.started":"2026-09-14T16:27:11.090209Z","shell.execute_reply":"2026-09-14T16:27:11.11728Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\"HIỂN THỊ BẰNG PYDICOM\"\n\n# gọi lại 5 cái vừa lấy trên kia\ntop_5_paths = data_paths[:5]\n\n# tạo 5 cột\nfig, axes = plt.subplots(1, 5, figsize=(20, 4))\n\n# duyệt tuần tự\nfor index, path in enumerate(top_5_paths):\n\n    dicom_dataset = pydicom.dcmread(path)\n    img_matrix = dicom_dataset.pixel_array\n   \n    axes[index].imshow(img_matrix, cmap='gray')\n    axes[index].set_title(f'Slice {index + 1}')\n    axes[index].axis('off')\n\n# hiển thị full\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-14T15:21:13.065756Z","iopub.execute_input":"2026-09-14T15:21:13.066524Z","iopub.status.idle":"2026-09-14T15:21:14.288404Z","shell.execute_reply.started":"2026-09-14T15:21:13.066492Z","shell.execute_reply":"2026-09-14T15:21:14.287537Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\"HIỂN THỊ BẰNG IMAGEIO\"\n\n# tạo cột\nfig, axes = plt.subplots(1, 5, figsize=(20, 4))\n\nfor index, path in enumerate(top_5_paths):\n    \n    img_matrix = imageio.imread(path)\n    \n    axes[index].imshow(img_matrix, cmap='gray')\n    axes[index].set_title(f'Slice {index + 1}')\n    axes[index].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-14T15:21:14.29033Z","iopub.execute_input":"2026-09-14T15:21:14.290662Z","iopub.status.idle":"2026-09-14T15:21:15.518492Z","shell.execute_reply.started":"2026-09-14T15:21:14.290632Z","shell.execute_reply":"2026-09-14T15:21:15.517623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\"cv2\"\n\n#lại tạo cột\nfig, axes = plt.subplots(1, 5, figsize=(20, 4))\n\nfor index, path in enumerate(top_5_paths):\n    \n    raw_matrix = pydicom.dcmread(path).pixel_array\n    normalized_matrix = cv2.normalize(raw_matrix, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)\n    img_8bit = np.uint8(normalized_matrix)\n    \n    axes[index].imshow(img_8bit, cmap='gray')\n    axes[index].set_title(f'Lát cắt {index + 1}')\n    axes[index].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-14T15:39:31.751136Z","iopub.execute_input":"2026-09-14T15:39:31.751996Z","iopub.status.idle":"2026-09-14T15:39:31.790219Z","shell.execute_reply.started":"2026-09-14T15:39:31.751964Z","shell.execute_reply":"2026-09-14T15:39:31.789312Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\"GET METADATA\"\n\nsample_path = data_paths[0]\n\n# đọc file dicom\ndicom_dataset = pydicom.dcmread(sample_path)\n\n# get hết data\nprint(dicom_dataset)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-14T16:20:16.232753Z","iopub.execute_input":"2026-09-14T16:20:16.233175Z","iopub.status.idle":"2026-09-14T16:20:16.251018Z","shell.execute_reply.started":"2026-09-14T16:20:16.233143Z","shell.execute_reply":"2026-09-14T16:20:16.250035Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"DATAMETA TAG EXPLAINING\n\n- Image Type: phân loại tệp (Original: thu trực tiếp từ máy quét; Primary: - dữ liệu không gian cơ bản)\n- SOP Class/Instance UID: mã định danh cho tệp MRI Storage/ mã ID duy nhất của chính slice đấy\n\n- Modality: phương pháp chẩn đoán hình ảnh (MR: Cộng hưởng từ)\n- Manufacturer: hãng sản xuất thiết bị\n- Series Description: mô tả chuỗi chụp\n- Manufacturer's Model Name: tên dòng máy quét\n- Patient ID: mã số định danh bệnh nhân\n- Patient's Sex: giới tính bệnh nhân\n- Contrast/Bolus Agent: thuốc đối quang từ (trống: ca chụp không tiêm thuốc)\n- Body Part Examined: bộ phận cơ thể được chụp\n- Scanning Sequence: cấu hình chuỗi xung vô tuyến (GR: Gradient Recalled)\n- Sequence Variant: cấu hình biến thể của chuỗi xung\n- Scan Options: các tùy chọn quét bổ sung\n- MR Acquisition Type: kiểu thu nhận dữ liệu không gian\n- Sequence Name: tên chuỗi xung kỹ thuậ\n- Slice Thickness: độ dày vật lý của lát cắt\n- Repetition Time: thời gian lặp lại giữa hai xung vô tuyến kích thích\n- Echo Time: thời gian thu nhận tín hiệu dội\n- Inversion Time: thời gian đảo ngược vector từ hóa (None: không sử dụng)\n- Number of Averages: số lần trung bình hóa tín hiệu\n- Imaging Frequency: tần số vô tuyến phát ra\n- Echo Number(s): số thứ tự của tín hiệu dội\n- Magnetic Field Strength: cường độ từ trường máy \n- Number of Phase Encoding Steps: số bước mã hóa pha, định hình độ phân giải một trục\n- Echo Train Length: chiều dài chuỗi tín hiệu dội thu được\n- Percent Sampling: tỷ lệ lấy mẫu tín hiệu\n- Percent Phase Field of View: tỷ lệ trường nhìn theo chiều mã hóa pha \n- Pixel Bandwidth: băng thông thu nhận tín hiệu trên mỗi pixel\n- Software Versions: phiên bản phần mềm điều khiển máy chụp\n- Receive Coil Name: tên cuộn cảm nhận tín hiệu\n- Transmit Coil Name: tên cuộn cảm phát xung\n- Acquisition Matrix: ma trận thu nhận tín hiệu gốc (0 x 320 x 384)\n- In-plane Phase Encoding Direction: hướng mã hóa pha trong mặt phẳng (ROW: theo hàng)\n- Flip Angle: góc lật của vector từ hóa \n- Variable Flip Angle Flag: cờ báo góc lật thay đổi (N: Không)\n- Patient Position: tư thế nằm trên bàn chụp (FFS: đưa chân vào trước, nằm ngửa)\n\n- Study Instance UID: mã ID duy nhất của toàn bộ ca khám bệnh\n- Series Instance UID: mã ID duy nhất của toàn bộ chuỗi chụp này\n- Series Number: số thứ tự của chuỗi chụp trong ca khám\n- Acquisition Number: số lần thực hiện thu nhận tín hiệu\n- Instance Number: số thứ tự của lát cắt trong chuỗi \n- Image Position (Patient): tọa độ 3D (x, y, z) của góc ảnh so với tâm máy\n- Image Orientation (Patient): vector định hướng mặt phẳng cắt trong không gian\n- Frame of Reference UID: mã ID hệ quy chiếu không gian chung\n- Laterality: bên giải phẫu được chụp \n- Number of Temporal Positions: số lượng khung hình theo thời gian\n- Slice Location: tọa độ vật lý của lát cắt trên trục Z\n- Samples per Pixel: số lượng kênh màu (1: ảnh đơn sắc)\n- Photometric Interpretation: không gian màu của ảnh (MONOCHROME2: hiển thị dải xám, điểm giá trị cao là màu trắng)\n- Rows: độ phân giải ảnh theo chiều dọc \n- Columns: độ phân giải ảnh theo chiều ngang \n- Pixel Spacing: kích thước vật lý thực tế của 1 pixel \n- Bits Allocated: bộ nhớ máy tính cấp phát cho 1 pixel \n- Bits Stored: lượng bộ nhớ thực tế dùng để lưu dữ liệu\n- High Bit: vị trí của bit cao nhất mang dữ liệu\n- Pixel Representation: kiểu lưu trữ số nguyên (0: số không dấu)\n- Window Center: mức xám trung tâm, dùng để điều chỉnh độ sáng trực quan\n- Window Width: độ rộng dải xám, dùng để điều chỉnh độ tương phản\n- Rescale Intercept: hằng số (b) trong phương trình tuyến tính để chuẩn hóa giá trị điểm ảnh\n- Rescale Slope: hệ số góc (a) trong phương trình tuyến tính chuẩn hóa\n- Pixel Data: mảng dữ liệu nhị phân chứa cường độ tín hiệu của toàn bộ 1.638.400 điểm ảnh","metadata":{}},{"cell_type":"code","source":"\n# tạo matrix từ biến sample_path trước đó\ndicom_dataset = pydicom.dcmread(sample_path)\npixel_matrix = dicom_dataset.pixel_array\n\n# flattern 2D -> 1D\nflat_pixels = pixel_matrix.flatten()\n\n# lọc bỏ vùng đen\ntissue_pixels = flat_pixels[flat_pixels > 0]\n\n\nplt.figure(figsize=(10, 5))\n\nplt.hist(tissue_pixels, bins=256, color='blue', edgecolor='black', alpha=0.7)\n\nplt.title('Intensity histogram', fontweight='bold')\nplt.xlabel('Cường độ tín hiệu bức xạ (Pixel Value)')\nplt.ylabel('Tần suất (Frequency)')\nplt.grid(axis='y', alpha=0.3)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-14T17:14:42.607778Z","iopub.execute_input":"2026-09-14T17:14:42.608156Z","iopub.status.idle":"2026-09-14T17:14:43.079401Z","shell.execute_reply.started":"2026-09-14T17:14:42.608125Z","shell.execute_reply":"2026-09-14T17:14:43.077918Z"}},"outputs":[],"execution_count":null}]}