{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":10338,"databundleVersionId":862042,"sourceType":"competition"},{"sourceId":7607737,"sourceType":"datasetVersion","datasetId":4429614}],"dockerImageVersionId":30646,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import torch\nimport os\nimport pydicom\nfrom PIL import Image\nimport requests\nfrom pathlib import Path\nimport csv\n\n# Function to convert DICOM to PNG\ndef convert_dicom_to_png(dicom_path, output_path):\n    ds = pydicom.dcmread(dicom_path)\n    img = ds.pixel_array\n    img = Image.fromarray(img)\n    img.save(output_path, \"PNG\")\n\n# URL of the custom weights\nweights_url = 'https://github.com/Yurich3112/Pneumonia_detection/blob/main/best.pt?raw=true'\n\n# Download the weights and save to disk\nresponse = requests.get(weights_url)\nweights_path = '/kaggle/working/best.pt'\nwith open(weights_path, 'wb') as f:\n    f.write(response.content)\n\n# Load the YOLOv5 model with the custom weights\nmodel = torch.hub.load('ultralytics/yolov5', 'custom', path=weights_path, force_reload=True)\n\n# Ensure the model is in evaluation mode\nmodel.eval()\n\n# Directory containing your test DICOM images\ntest_dicom_dir = '/kaggle/input/rsna-pneumonia-detection-challenge/stage_2_test_images'\n# Directory where PNG images will be stored\noutput_png_dir = '/kaggle/working/output_png_images'\nos.makedirs(output_png_dir, exist_ok=True)\n\n# Convert the first 3000 DICOM to PNG\ndicom_files = list(Path(test_dicom_dir).glob('*.dcm'))[:3000]  # Limit to first 3000\nfor dicom_path in dicom_files:\n    png_output_path = Path(output_png_dir) / f\"{dicom_path.stem}.png\"\n    convert_dicom_to_png(dicom_path, png_output_path)\n\n# Perform inference on the PNG images and generate predictions\nsubmission_data = [['patientId', 'PredictionString']]\npng_files = list(Path(output_png_dir).glob('*.png'))\nfor image_path in png_files:\n    # Inference\n    results = model(image_path)\n    # Parse the results\n    prediction_string = ' '.join(\n        f'{x[4]} {x[0]} {x[1]} {x[2]-x[0]} {x[3]-x[1]}' for x in results.pred[0]\n    )\n    # Extract patient ID and append to submission data\n    patient_id = image_path.stem\n    submission_data.append([patient_id, prediction_string.strip()])\n\n# Write the submission data to a CSV file\nsubmission_file_path = '/kaggle/working/submission.csv'\nwith open(submission_file_path, 'w', newline='') as f:\n    writer = csv.writer(f)\n    writer.writerows(submission_data)\n\n# Clear the output directory\nfor file in Path(output_png_dir).iterdir():\n    file.unlink()\nPath(output_png_dir).rmdir()\n\nprint(f\"Submission file created: {submission_file_path}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-02-11T20:17:46.202279Z","iopub.execute_input":"2024-02-11T20:17:46.202859Z","iopub.status.idle":"2024-02-11T20:18:33.653679Z","shell.execute_reply.started":"2024-02-11T20:17:46.202820Z","shell.execute_reply":"2024-02-11T20:18:33.652528Z"},"trusted":true},"execution_count":null,"outputs":[]}]}