help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
medical-imaging
RSK World
medical-imaging
Medical Imaging Dataset - X-ray CT Scan MRI + Disease Detection + Computer-Aided Diagnosis + Medical AI
medical-imaging
  • __pycache__
  • data
  • scripts
  • .gitignore475 B
  • CONTRIBUTING.md1.7 KB
  • CT_MRI_LOCATION.md6 KB
  • DATASET_SUMMARY.md4.1 KB
  • DISCLAIMER.md2.1 KB
  • DOWNLOAD_INSTRUCTIONS.md7.5 KB
  • ERROR_CHECK_REPORT.md4.2 KB
  • FINAL_DATASET_SUMMARY.md5.8 KB
  • LICENSE784 B
  • PROJECT_IMAGE_NOTE.md1.2 KB
  • PROJECT_SUMMARY.md3.9 KB
  • QUICK_START.md2.9 KB
  • README.md4.3 KB
  • RELEASE_NOTES.md5 KB
  • create_directories.py1.5 KB
  • download_all_ct_mri.py12.2 KB
  • download_all_datasets.py8.9 KB
  • download_ct_mri_datasets.py10.1 KB
  • download_ct_mri_kaggle.bat1.5 KB
  • download_from_github.py8.1 KB
  • download_helper.py4.4 KB
  • download_kaggle_datasets.bat2.1 KB
  • download_public_datasets.py16.7 KB
  • download_summary.json211 B
  • example_usage.py2.7 KB
  • generate_sample_data.py15.9 KB
  • index.html43.2 KB
  • medical-imaging.zip2.1 MB
  • organize_medmnist.py1.3 KB
  • organize_mri_data.py584 B
  • project_info.json1.4 KB
  • requirements.txt492 B
  • setup.py2 KB
download_all_datasets.py
download_all_datasets.py
Raw Download
Find: Go to:
"""
Medical Imaging Dataset - Automatic Dataset Downloader
=======================================================

Project: Medical Imaging Dataset
Website: https://rskworld.in
Contact: help@rskworld.in, support@rskworld.in
Phone: +91 93305 39277
Founder: Molla Samser
Designer & Tester: Rima Khatun

This script automatically downloads publicly available medical imaging datasets.
"""

import os
import requests
import zipfile
import shutil
import json
from pathlib import Path
from urllib.parse import urlparse


def download_file(url, output_path, description=""):
    """Download a file from URL."""
    print(f"Downloading {description}...")
    print(f"URL: {url}")
    
    try:
        response = requests.get(url, stream=True, timeout=60)
        if response.status_code == 200:
            total_size = int(response.headers.get('content-length', 0))
            downloaded = 0
            
            output_path.parent.mkdir(parents=True, exist_ok=True)
            
            with open(output_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
                        downloaded += len(chunk)
                        if total_size > 0:
                            percent = (downloaded / total_size) * 100
                            print(f"\rProgress: {percent:.1f}%", end='', flush=True)
            
            print(f"\nDownloaded: {output_path}")
            return True
        else:
            print(f"Error: HTTP {response.status_code}")
            return False
    except Exception as e:
        print(f"Error: {e}")
        return False


def download_covid_dataset():
    """Download COVID-19 chest X-ray dataset from GitHub."""
    print("=" * 60)
    print("Downloading COVID-19 Chest X-ray Dataset")
    print("=" * 60)
    print()
    
    # Try downloading the repository as ZIP
    url = "https://github.com/ieee8023/covid-chestxray-dataset/archive/refs/heads/master.zip"
    alt_url = "https://github.com/ieee8023/covid-chestxray-dataset/archive/refs/heads/main.zip"
    
    zip_path = Path("data/temp/covid_dataset.zip")
    
    # Try master branch first
    if not download_file(url, zip_path, "COVID-19 Dataset"):
        # Try main branch
        print("Trying main branch...")
        if not download_file(alt_url, zip_path, "COVID-19 Dataset"):
            print("Failed to download COVID-19 dataset")
            return False
    
    # Extract
    print("Extracting...")
    extract_dir = Path("data/temp/covid")
    extract_dir.mkdir(parents=True, exist_ok=True)
    
    try:
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(extract_dir)
        print(f"Extracted to: {extract_dir}")
    except Exception as e:
        print(f"Error extracting: {e}")
        return False
    
    # Organize images
    print("Organizing images...")
    source = extract_dir
    target_images = Path("data/xray/images")
    target_labels = Path("data/xray/labels")
    
    target_images.mkdir(parents=True, exist_ok=True)
    target_labels.mkdir(parents=True, exist_ok=True)
    
    # Find all image files
    image_extensions = ['.png', '.jpg', '.jpeg']
    image_count = 0
    
    for ext in image_extensions:
        for img_file in source.rglob(f'*{ext}'):
            if img_file.is_file():
                # Skip if already exists
                dest = target_images / img_file.name
                if not dest.exists():
                    try:
                        shutil.copy2(img_file, dest)
                        image_count += 1
                        
                        # Create label file
                        label_file = target_labels / f"{img_file.stem}.json"
                        if not label_file.exists():
                            label_data = {
                                "diagnosis": "COVID-19" if "covid" in img_file.name.lower() else "Normal",
                                "confidence": 0.90,
                                "date": "2024-01-15",
                                "modality": "X-ray",
                                "body_part": "Chest",
                                "source": "COVID-19 Chest X-ray Dataset (GitHub)",
                                "license": "MIT",
                                "annotations": {
                                    "findings": ["From public COVID-19 dataset"],
                                    "recommendations": ["Educational use only"]
                                },
                                "metadata": {
                                    "patient_id": "ANONYMIZED",
                                    "age": "N/A",
                                    "gender": "N/A",
                                    "technique": "Digital radiography"
                                }
                            }
                            with open(label_file, 'w') as f:
                                json.dump(label_data, f, indent=4)
                    except Exception as e:
                        print(f"Error copying {img_file}: {e}")
    
    print(f"Organized {image_count} images to data/xray/images/")
    return image_count > 0


def download_sample_images_from_medmnist():
    """Download sample images information (MedMNIST requires direct access)."""
    print("=" * 60)
    print("MedMNIST Dataset Information")
    print("=" * 60)
    print()
    print("MedMNIST is available at: https://medmnist.com/")
    print("You can download it directly from the website.")
    print("Or use Kaggle: kaggle datasets download -d andrewmvd/medical-mnist")
    print()


def create_download_summary():
    """Create a summary of downloaded datasets."""
    summary = {
        "downloaded_datasets": [],
        "total_images": 0,
        "xray_images": 0,
        "ct_images": 0,
        "mri_images": 0
    }
    
    # Count images
    xray_dir = Path("data/xray/images")
    ct_dir = Path("data/ct_scan/images")
    mri_dir = Path("data/mri/images")
    
    if xray_dir.exists():
        xray_count = len(list(xray_dir.glob("*.png")) + list(xray_dir.glob("*.jpg")) + list(xray_dir.glob("*.jpeg")))
        summary["xray_images"] = xray_count
        summary["total_images"] += xray_count
        if xray_count > 0:
            summary["downloaded_datasets"].append("X-ray images")
    
    if ct_dir.exists():
        ct_count = len(list(ct_dir.glob("*.png")) + list(ct_dir.glob("*.jpg")) + list(ct_dir.glob("*.jpeg")) + list(ct_dir.glob("*.dcm")))
        summary["ct_images"] = ct_count
        summary["total_images"] += ct_count
        if ct_count > 0:
            summary["downloaded_datasets"].append("CT scan images")
    
    if mri_dir.exists():
        mri_count = len(list(mri_dir.glob("*.png")) + list(mri_dir.glob("*.jpg")) + list(mri_dir.glob("*.jpeg")) + list(mri_dir.glob("*.dcm")))
        summary["mri_images"] = mri_count
        summary["total_images"] += mri_count
        if mri_count > 0:
            summary["downloaded_datasets"].append("MRI images")
    
    # Save summary
    with open("download_summary.json", 'w') as f:
        json.dump(summary, f, indent=4)
    
    return summary


def main():
    """Main function to download all available datasets."""
    print("=" * 60)
    print("Medical Imaging Dataset - Automatic Downloader")
    print("=" * 60)
    print()
    print("This script will download publicly available medical imaging datasets.")
    print()
    
    downloaded = False
    
    # Download COVID-19 dataset (easiest, no account needed)
    print("\n[1/1] Downloading COVID-19 Chest X-ray Dataset...")
    if download_covid_dataset():
        downloaded = True
        print("[OK] COVID-19 dataset downloaded successfully!")
    else:
        print("[WARNING] Could not download COVID-19 dataset")
    
    print()
    print("=" * 60)
    print("Download Summary")
    print("=" * 60)
    
    summary = create_download_summary()
    
    print(f"Total images: {summary['total_images']}")
    print(f"  - X-ray images: {summary['xray_images']}")
    print(f"  - CT scan images: {summary['ct_images']}")
    print(f"  - MRI images: {summary['mri_images']}")
    print()
    
    if summary['total_images'] > 0:
        print("Downloaded datasets:")
        for dataset in summary['downloaded_datasets']:
            print(f"  - {dataset}")
    else:
        print("No images downloaded yet.")
        print()
        print("To download more datasets:")
        print("1. Read DOWNLOAD_INSTRUCTIONS.md for detailed instructions")
        print("2. Use Kaggle API for larger datasets (requires free account)")
        print("3. Visit https://medmnist.com/ for MedMNIST dataset")
    
    print()
    print("=" * 60)
    print("Note: For more datasets, see DOWNLOAD_INSTRUCTIONS.md")
    print("=" * 60)


if __name__ == '__main__':
    main()

252 lines•8.9 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer