{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":24800,"datasetId":1042002,"databundleVersionId":1831594},{"sourceType":"datasetVersion","sourceId":11382644,"datasetId":7127269,"databundleVersionId":11815093}],"dockerImageVersionId":31011,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-04-30T22:03:59.996423Z","iopub.execute_input":"2025-04-30T22:03:59.996768Z","iopub.status.idle":"2025-04-30T22:04:12.599828Z","shell.execute_reply.started":"2025-04-30T22:03:59.996749Z","shell.execute_reply":"2025-04-30T22:04:12.598703Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from glob import glob\n\nfrom keras.applications.densenet import DenseNet121\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.models import load_model\n# Install required libraries (uncomment if needed)\n# !pip install pydicom opencv-python tensorflow\n\nimport pydicom\nimport numpy as np\nimport cv2\nfrom tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.applications.densenet import preprocess_input\n\n\n# --- Step 1: Load DICOM ---\ndef load_dicom(path):\n    ds = pydicom.dcmread(path)\n    image = ds.pixel_array.astype(np.float32)\n    image /= np.max(image)\n        \n    return image\n\ndef preprocess_dicom(image, mean, std):\n    # Convert to 3 channels if grayscale\n    if len(image.shape) == 2:\n        image = np.stack((image,) * 3, axis=-1)\n    \n    # Clip top and bottom 0.5% of pixel values\n    image = image.astype(np.float32)\n    low_val, high_val = np.percentile(image, [0.5, 99.5])\n    image = np.clip(image, low_val, high_val)\n    \n    # Normalize to [0, 1] range\n    image = (image - np.min(image)) / (np.max(image) - np.min(image))\n    # Apply model's mean/std normalization\n    image = (image - mean) / std\n    \n    # Resize to target size\n    image = cv2.resize(image, (320, 320))\n    \n    return image\n\n# --- Step 3: Load Model and Predict ---\n# Load pretrained DenseNet121\nclf = DenseNet121(\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    input_shape=None,\n)\n\n\nx = clf.output\n\n# add a global spatial average pooling layer\nx = GlobalAveragePooling2D()(x)\n\n# and a logistic layer\npredictions = Dense(14, activation=\"sigmoid\")(x)\nfor layer in clf.layers:\n    layer.trainable = False\nclf = Model(inputs=clf.input, outputs=predictions)\n\n\n\nclf.load_weights('/kaggle/input/bisho-mo3edo-3medo/xray_class_weights.best.hdf5')\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T22:04:54.779482Z","iopub.execute_input":"2025-04-30T22:04:54.779809Z","iopub.status.idle":"2025-04-30T22:05:03.248692Z","shell.execute_reply.started":"2025-04-30T22:04:54.779754Z","shell.execute_reply":"2025-04-30T22:05:03.248135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\n\n\n# 2. Function to load and preprocess images\ndef load_and_preprocess_image(filepath):\n    img = cv2.imread(filepath)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert to RGB\n    img = cv2.resize(img, input_size)  # Resize to model input size\n    img = img.astype(np.float32) / 255.0  # Normalize to [0,1]\n    return img\n\nmean = np.array([0.52625063, 0.52625063, 0.52625063])\nstd = np.array([0.25296255, 0.25296255, 0.25296255])\nprint(mean, std)\n\n\n# Predict\ndicom_path = \"/kaggle/input/vinbigdata-chest-xray-abnormalities-detection/train/321c111713c3ee5385db0effb54ff568.dicom\"  # <- CHANGE THIS\n\n# Load and preprocess\ndicom_image = load_dicom(dicom_path)\nprocessed_image = preprocess_dicom(dicom_image, mean, std)  # Shape: (320, 320, 3)\ninput_array = np.expand_dims(processed_image, axis=0)\nprint(input_array.shape)\n\nprediction = clf.predict(input_array)\nprint(\"Prediction shape:\", prediction.shape)  \nprint(prediction)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T22:05:27.376979Z","iopub.execute_input":"2025-04-30T22:05:27.377703Z","iopub.status.idle":"2025-04-30T22:05:41.852321Z","shell.execute_reply.started":"2025-04-30T22:05:27.377677Z","shell.execute_reply":"2025-04-30T22:05:41.851664Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"threshold = 0.5\nbinary_predictions = (prediction > threshold).astype(int)\n\n# Get the specific disease predictions (convert from 1-based to 0-based indices)\ndisease_indices = {\n    'Emphysema': 3,  # 3 (0-based)\n    'Hernia': 4,     # 4 (0-based)\n    'Edema': 6,      # 6 (0-based)\n    'Pneumonia': 7   # 7 (0-based)\n}\n\n# Extract and print the specific predictions\nprint(\"Thresholded predictions for specific diseases:\")\nfor disease, idx in disease_indices.items():\n    pred = binary_predictions[0, idx]  # [0] because prediction shape is (1, 14)\n    print(f\"{disease}: {'Positive' if pred == 1 else 'Negative'} (Probability: {prediction[0, idx]:.4f})\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-30T22:06:43.65517Z","iopub.execute_input":"2025-04-30T22:06:43.655914Z","iopub.status.idle":"2025-04-30T22:06:43.662257Z","shell.execute_reply.started":"2025-04-30T22:06:43.655882Z","shell.execute_reply":"2025-04-30T22:06:43.6614Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}