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_ct_mri_datasets.pysample_002.pngorganize_medmnist.pydownload_all_ct_mri.py
download_ct_mri_datasets.py
Raw Download
Find: Go to:
"""
Medical Imaging Dataset - CT Scan and MRI 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 downloads real CT scan and MRI datasets from public sources.
"""

import os
import requests
import zipfile
import shutil
import json
from pathlib import Path


def download_brain_mri_kaggle():
    """Instructions for downloading Brain MRI dataset from Kaggle."""
    print("=" * 60)
    print("Brain MRI Images for Brain Tumor Detection")
    print("=" * 60)
    print()
    print("Dataset: Brain MRI Images for Brain Tumor Detection")
    print("Source: Kaggle")
    print("URL: https://www.kaggle.com/datasets/navoneel/brain-mri-images-for-brain-tumor-detection")
    print("Size: ~300 MB")
    print("Images: ~3,000+ brain MRI images")
    print("License: CC BY 4.0")
    print()
    print("To download:")
    print("1. Install Kaggle API: pip install kaggle")
    print("2. Setup Kaggle credentials (see DOWNLOAD_INSTRUCTIONS.md)")
    print("3. Run: kaggle datasets download -d navoneel/brain-mri-images-for-brain-tumor-detection")
    print("4. Extract and organize to data/mri/images/")
    print()


def download_medical_mnist():
    """Instructions for downloading Medical MNIST (includes CT and MRI)."""
    print("=" * 60)
    print("Medical MNIST Dataset")
    print("=" * 60)
    print()
    print("Dataset: Medical MNIST")
    print("Source: Kaggle / Official Website")
    print("URL: https://www.kaggle.com/datasets/andrewmvd/medical-mnist")
    print("Official: https://medmnist.com/")
    print("Size: ~200 MB")
    print("Images: ~66,000 images across multiple modalities")
    print("Includes: CT, MRI, X-ray, Ultrasound, etc.")
    print("License: CC BY 4.0")
    print()
    print("To download:")
    print("Option 1 - Kaggle:")
    print("  kaggle datasets download -d andrewmvd/medical-mnist")
    print()
    print("Option 2 - Official Website:")
    print("  1. Visit: https://medmnist.com/")
    print("  2. Click 'Download' on desired dataset")
    print("  3. Extract and organize by modality")
    print()


def download_from_tcia():
    """Instructions for The Cancer Imaging Archive (TCIA)."""
    print("=" * 60)
    print("The Cancer Imaging Archive (TCIA)")
    print("=" * 60)
    print()
    print("Source: TCIA")
    print("URL: https://www.cancerimagingarchive.net/")
    print("Description: Open-access database of medical images for cancer research")
    print("Modalities: CT, MRI, PET scans")
    print("Access: Free registration required")
    print()
    print("To download:")
    print("1. Register at: https://www.cancerimagingarchive.net/")
    print("2. Browse collections by cancer type")
    print("3. Download via TCIA Data Portal or NBIA")
    print("4. Organize CT scans to data/ct_scan/images/")
    print("5. Organize MRI to data/mri/images/")
    print()


def download_from_radiopaedia():
    """Instructions for Radiopaedia."""
    print("=" * 60)
    print("Radiopaedia")
    print("=" * 60)
    print()
    print("Source: Radiopaedia")
    print("URL: https://radiopaedia.org/")
    print("Description: Educational radiology resource with case studies")
    print("Modalities: X-ray, CT, MRI, Ultrasound")
    print("Access: Free, educational use")
    print("License: CC BY-NC-SA")
    print()
    print("To download:")
    print("1. Visit: https://radiopaedia.org/")
    print("2. Browse cases by modality (CT, MRI)")
    print("3. Download images for educational purposes")
    print("4. Organize to appropriate directories")
    print()


def download_from_opennuro():
    """Instructions for OpenNeuro (MRI datasets)."""
    print("=" * 60)
    print("OpenNeuro")
    print("=" * 60)
    print()
    print("Source: OpenNeuro")
    print("URL: https://openneuro.org/")
    print("Description: Open-science database for brain imaging")
    print("Modalities: MRI, fMRI, EEG")
    print("Access: Free, open access")
    print()
    print("To download:")
    print("1. Visit: https://openneuro.org/")
    print("2. Browse datasets")
    print("3. Download via web interface or API")
    print("4. Data in BIDS format")
    print("5. Extract MRI images to data/mri/images/")
    print()


def create_kaggle_download_script():
    """Create a script to download CT and MRI datasets from Kaggle."""
    script_content = """@echo off
REM Medical Imaging Dataset - CT and MRI Kaggle Downloader
REM ========================================================
REM 
REM Project: Medical Imaging Dataset
REM Website: https://rskworld.in
REM Contact: help@rskworld.in, support@rskworld.in
REM Phone: +91 93305 39277
REM Founder: Molla Samser
REM Designer & Tester: Rima Khatun

echo ========================================
echo CT Scan and MRI Dataset Downloader
echo ========================================
echo.

REM Check if kaggle is installed
python -c "import kaggle" 2>nul
if errorlevel 1 (
    echo Installing Kaggle API...
    pip install kaggle
)

echo.
echo Available datasets:
echo 1. Brain MRI Images for Brain Tumor Detection
echo 2. Medical MNIST (includes CT and MRI)
echo.

set /p choice="Enter dataset number (1-2): "

if "%choice%"=="1" (
    echo Downloading Brain MRI Images...
    kaggle datasets download -d navoneel/brain-mri-images-for-brain-tumor-detection
    echo Extracting...
    python -m zipfile -e brain-mri-images-for-brain-tumor-detection.zip data/temp/mri/
    echo Organizing MRI images...
    python organize_mri_data.py
    echo Dataset downloaded and organized!
)

if "%choice%"=="2" (
    echo Downloading Medical MNIST...
    kaggle datasets download -d andrewmvd/medical-mnist
    echo Extracting...
    python -m zipfile -e medical-mnist.zip data/temp/medmnist/
    echo Organizing by modality...
    python organize_medmnist.py
    echo Dataset downloaded and organized!
)

echo.
echo Download complete!
pause
"""
    
    with open('download_ct_mri_kaggle.bat', 'w') as f:
        f.write(script_content)
    
    print("Created: download_ct_mri_kaggle.bat")


def create_organize_scripts():
    """Create scripts to organize downloaded CT and MRI data."""
    
    # MRI organizer script
    mri_script = """\"\"\"
Organize Brain MRI Images
\"\"\"
import shutil
from pathlib import Path

source = Path("data/temp/mri")
target = Path("data/mri/images")
target.mkdir(parents=True, exist_ok=True)

# Find all image files
image_extensions = ['.png', '.jpg', '.jpeg', '.dcm']
count = 0

for ext in image_extensions:
    for img_file in source.rglob(f'*{ext}'):
        if img_file.is_file():
            dest = target / img_file.name
            if not dest.exists():
                shutil.copy2(img_file, dest)
                count += 1

print(f"Organized {count} MRI images")
"""
    
    with open('organize_mri_data.py', 'w') as f:
        f.write(mri_script)
    
    # MedMNIST organizer script
    medmnist_script = """\"\"\"
Organize Medical MNIST by Modality
\"\"\"
import shutil
from pathlib import Path

source = Path("data/temp/medmnist")
ct_target = Path("data/ct_scan/images")
mri_target = Path("data/mri/images")

ct_target.mkdir(parents=True, exist_ok=True)
mri_target.mkdir(parents=True, exist_ok=True)

# MedMNIST structure may vary, adjust based on actual structure
# This is a template - adjust based on actual dataset structure

image_extensions = ['.png', '.jpg', '.jpeg']
ct_count = 0
mri_count = 0

for ext in image_extensions:
    for img_file in source.rglob(f'*{ext}'):
        if img_file.is_file():
            name_lower = img_file.name.lower()
            # Adjust these conditions based on actual file naming
            if 'ct' in name_lower or 'ctscan' in name_lower:
                dest = ct_target / img_file.name
                if not dest.exists():
                    shutil.copy2(img_file, dest)
                    ct_count += 1
            elif 'mri' in name_lower or 'brain' in name_lower:
                dest = mri_target / img_file.name
                if not dest.exists():
                    shutil.copy2(img_file, dest)
                    mri_count += 1

print(f"Organized {ct_count} CT scan images")
print(f"Organized {mri_count} MRI images")
"""
    
    with open('organize_medmnist.py', 'w') as f:
        f.write(medmnist_script)
    
    print("Created: organize_mri_data.py")
    print("Created: organize_medmnist.py")


def main():
    """Main function."""
    print("=" * 60)
    print("CT Scan and MRI Dataset Download Guide")
    print("=" * 60)
    print()
    print("Current status:")
    print("  - CT scan images: 5 (sample data)")
    print("  - MRI images: 5 (sample data)")
    print()
    print("To get REAL CT scan and MRI images:")
    print()
    
    # Show all options
    download_brain_mri_kaggle()
    download_medical_mnist()
    download_from_tcia()
    download_from_radiopaedia()
    download_from_opennuro()
    
    # Create helper scripts
    print("=" * 60)
    print("Creating helper scripts...")
    print("=" * 60)
    create_kaggle_download_script()
    create_organize_scripts()
    
    print()
    print("=" * 60)
    print("Summary")
    print("=" * 60)
    print()
    print("EASIEST OPTIONS:")
    print("1. Brain MRI (Kaggle): ~3,000+ images")
    print("   - Requires Kaggle account")
    print("   - Run: kaggle datasets download -d navoneel/brain-mri-images-for-brain-tumor-detection")
    print()
    print("2. Medical MNIST (Kaggle/Website): ~66,000 images")
    print("   - Includes CT, MRI, and other modalities")
    print("   - Visit: https://medmnist.com/")
    print()
    print("3. TCIA (Registration required)")
    print("   - Visit: https://www.cancerimagingarchive.net/")
    print("   - Large collection of CT and MRI scans")
    print()
    print("For detailed instructions, see: DOWNLOAD_INSTRUCTIONS.md")
    print()


if __name__ == '__main__':
    main()

329 lines•10.1 KB
python
organize_medmnist.py
Raw Download
Find: Go to:
"""
Organize Medical MNIST by Modality
"""
import shutil
from pathlib import Path

source = Path("data/temp/medmnist")
ct_target = Path("data/ct_scan/images")
mri_target = Path("data/mri/images")

ct_target.mkdir(parents=True, exist_ok=True)
mri_target.mkdir(parents=True, exist_ok=True)

# MedMNIST structure may vary, adjust based on actual structure
# This is a template - adjust based on actual dataset structure

image_extensions = ['.png', '.jpg', '.jpeg']
ct_count = 0
mri_count = 0

for ext in image_extensions:
    for img_file in source.rglob(f'*{ext}'):
        if img_file.is_file():
            name_lower = img_file.name.lower()
            # Adjust these conditions based on actual file naming
            if 'ct' in name_lower or 'ctscan' in name_lower:
                dest = ct_target / img_file.name
                if not dest.exists():
                    shutil.copy2(img_file, dest)
                    ct_count += 1
            elif 'mri' in name_lower or 'brain' in name_lower:
                dest = mri_target / img_file.name
                if not dest.exists():
                    shutil.copy2(img_file, dest)
                    mri_count += 1

print(f"Organized {ct_count} CT scan images")
print(f"Organized {mri_count} MRI images")
39 lines•1.3 KB
python
download_all_ct_mri.py
Raw Download
Find: Go to:
"""
Medical Imaging Dataset - Download All CT and MRI Datasets
===========================================================

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 attempts to download CT scan and MRI datasets from various sources.
"""

import os
import sys
import subprocess
import zipfile
import shutil
import json
from pathlib import Path


def check_kaggle_auth():
    """Check if Kaggle is authenticated."""
    try:
        result = subprocess.run(['kaggle', 'datasets', 'list', '--page-size', '1'], 
                              capture_output=True, text=True, timeout=10)
        return result.returncode == 0
    except:
        return False


def download_brain_mri():
    """Download Brain MRI dataset from Kaggle."""
    print("=" * 60)
    print("Downloading Brain MRI Images for Brain Tumor Detection")
    print("=" * 60)
    print()
    
    dataset = "navoneel/brain-mri-images-for-brain-tumor-detection"
    output_dir = Path("data/temp/mri")
    output_dir.mkdir(parents=True, exist_ok=True)
    
    try:
        print(f"Downloading dataset: {dataset}")
        print("This may take a few minutes...")
        
        result = subprocess.run(
            ['kaggle', 'datasets', 'download', '-d', dataset, '-p', str(output_dir)],
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0:
            print("Download successful!")
            
            # Find and extract zip file
            zip_files = list(output_dir.glob("*.zip"))
            if zip_files:
                zip_path = zip_files[0]
                print(f"Extracting {zip_path.name}...")
                
                extract_dir = output_dir / "extracted"
                extract_dir.mkdir(exist_ok=True)
                
                with zipfile.ZipFile(zip_path, 'r') as zip_ref:
                    zip_ref.extractall(extract_dir)
                
                # Organize images
                organize_mri_images(extract_dir)
                return True
            else:
                print("Warning: No zip file found after download")
                return False
        else:
            print(f"Error: {result.stderr}")
            if "401" in result.stderr or "authentication" in result.stderr.lower():
                print("\nKaggle authentication required!")
                print("Please:")
                print("1. Create a free account at https://www.kaggle.com")
                print("2. Go to Account Settings → API")
                print("3. Click 'Create New API Token'")
                print("4. Download kaggle.json")
                print(f"5. Place it in: {Path.home()}\\.kaggle\\kaggle.json")
            return False
            
    except FileNotFoundError:
        print("Error: Kaggle CLI not found. Please install: pip install kaggle")
        return False
    except Exception as e:
        print(f"Error downloading: {e}")
        return False


def organize_mri_images(source_dir):
    """Organize MRI images into the project structure."""
    print("Organizing MRI images...")
    
    source = Path(source_dir)
    target_images = Path("data/mri/images")
    target_labels = Path("data/mri/labels")
    
    target_images.mkdir(parents=True, exist_ok=True)
    target_labels.mkdir(parents=True, exist_ok=True)
    
    image_extensions = ['.png', '.jpg', '.jpeg', '.dcm']
    image_count = 0
    
    for ext in image_extensions:
        for img_file in source.rglob(f'*{ext}'):
            if img_file.is_file():
                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": "Brain MRI",
                                "confidence": 0.90,
                                "date": "2024-01-15",
                                "modality": "MRI",
                                "body_part": "Brain",
                                "source": "Brain MRI Images for Brain Tumor Detection (Kaggle)",
                                "license": "CC BY 4.0",
                                "annotations": {
                                    "findings": ["From public Brain MRI dataset"],
                                    "recommendations": ["Educational use only"]
                                },
                                "metadata": {
                                    "patient_id": "ANONYMIZED",
                                    "age": "N/A",
                                    "gender": "N/A",
                                    "technique": "MRI"
                                }
                            }
                            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} MRI images to data/mri/images/")
    return image_count


def download_medical_mnist():
    """Download Medical MNIST dataset from Kaggle."""
    print("=" * 60)
    print("Downloading Medical MNIST Dataset")
    print("=" * 60)
    print()
    
    dataset = "andrewmvd/medical-mnist"
    output_dir = Path("data/temp/medmnist")
    output_dir.mkdir(parents=True, exist_ok=True)
    
    try:
        print(f"Downloading dataset: {dataset}")
        print("This may take a few minutes...")
        
        result = subprocess.run(
            ['kaggle', 'datasets', 'download', '-d', dataset, '-p', str(output_dir)],
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0:
            print("Download successful!")
            
            # Find and extract zip file
            zip_files = list(output_dir.glob("*.zip"))
            if zip_files:
                zip_path = zip_files[0]
                print(f"Extracting {zip_path.name}...")
                
                extract_dir = output_dir / "extracted"
                extract_dir.mkdir(exist_ok=True)
                
                with zipfile.ZipFile(zip_path, 'r') as zip_ref:
                    zip_ref.extractall(extract_dir)
                
                # Organize by modality
                organize_medmnist(extract_dir)
                return True
            else:
                print("Warning: No zip file found after download")
                return False
        else:
            print(f"Error: {result.stderr}")
            if "401" in result.stderr or "authentication" in result.stderr.lower():
                print("\nKaggle authentication required!")
                print_authentication_instructions()
            return False
            
    except Exception as e:
        print(f"Error downloading: {e}")
        return False


def organize_medmnist(source_dir):
    """Organize Medical MNIST by modality."""
    print("Organizing Medical MNIST by modality...")
    
    source = Path(source_dir)
    ct_target = Path("data/ct_scan/images")
    mri_target = Path("data/mri/images")
    
    ct_target.mkdir(parents=True, exist_ok=True)
    mri_target.mkdir(parents=True, exist_ok=True)
    
    image_extensions = ['.png', '.jpg', '.jpeg']
    ct_count = 0
    mri_count = 0
    
    # Medical MNIST structure: usually organized in folders
    for ext in image_extensions:
        for img_file in source.rglob(f'*{ext}'):
            if img_file.is_file():
                name_lower = img_file.name.lower()
                path_lower = str(img_file).lower()
                
                # Check folder names and file names for modality
                if 'ct' in path_lower or 'ctscan' in path_lower or 'ct_scan' in path_lower:
                    dest = ct_target / img_file.name
                    if not dest.exists():
                        try:
                            shutil.copy2(img_file, dest)
                            ct_count += 1
                        except:
                            pass
                elif 'mri' in path_lower or 'brain' in path_lower:
                    dest = mri_target / img_file.name
                    if not dest.exists():
                        try:
                            shutil.copy2(img_file, dest)
                            mri_count += 1
                        except:
                            pass
    
    print(f"Organized {ct_count} CT scan images")
    print(f"Organized {mri_count} MRI images")
    return ct_count + mri_count


def print_authentication_instructions():
    """Print instructions for Kaggle authentication."""
    print("\n" + "=" * 60)
    print("Kaggle Authentication Required")
    print("=" * 60)
    print()
    print("To download datasets from Kaggle, you need to:")
    print()
    print("1. Create a FREE Kaggle account:")
    print("   https://www.kaggle.com/account/register")
    print()
    print("2. Get your API credentials:")
    print("   - Go to: https://www.kaggle.com/account")
    print("   - Scroll to 'API' section")
    print("   - Click 'Create New API Token'")
    print("   - Download kaggle.json file")
    print()
    print("3. Place kaggle.json in:")
    print(f"   Windows: {Path.home()}\\.kaggle\\kaggle.json")
    print(f"   Linux/Mac: ~/.kaggle/kaggle.json")
    print()
    print("4. Set permissions (Linux/Mac only):")
    print("   chmod 600 ~/.kaggle/kaggle.json")
    print()
    print("5. Run this script again")
    print()
    print("=" * 60)


def main():
    """Main function to download all CT and MRI datasets."""
    print("=" * 60)
    print("Medical Imaging Dataset - Download All CT & MRI")
    print("=" * 60)
    print()
    
    # Check Kaggle authentication
    print("Checking Kaggle authentication...")
    if not check_kaggle_auth():
        print("Kaggle authentication not configured.")
        print_authentication_instructions()
        print()
        print("Attempting downloads anyway (may fail without credentials)...")
        print()
    
    downloaded = False
    
    # Try to download Brain MRI
    print("\n[1/2] Attempting to download Brain MRI dataset...")
    if download_brain_mri():
        downloaded = True
        print("[OK] Brain MRI dataset downloaded!")
    else:
        print("[SKIPPED] Brain MRI dataset - authentication may be required")
    
    # Try to download Medical MNIST
    print("\n[2/2] Attempting to download Medical MNIST dataset...")
    if download_medical_mnist():
        downloaded = True
        print("[OK] Medical MNIST dataset downloaded!")
    else:
        print("[SKIPPED] Medical MNIST dataset - authentication may be required")
    
    # Summary
    print()
    print("=" * 60)
    print("Download Summary")
    print("=" * 60)
    
    from scripts.load_data import MedicalImagingDataset
    dataset = MedicalImagingDataset(data_path='./data')
    info = dataset.get_dataset_info()
    
    print(f"Current dataset status:")
    print(f"  X-ray images: {info['xray_count']}")
    print(f"  CT scan images: {info['ct_count']}")
    print(f"  MRI images: {info['mri_count']}")
    print(f"  Total images: {info['total_images']}")
    print()
    
    if not downloaded:
        print("No datasets were downloaded.")
        print("This is likely because Kaggle authentication is required.")
        print()
        print("To download real CT and MRI images:")
        print("1. Follow the authentication instructions above")
        print("2. Or visit: https://medmnist.com/ (no account needed)")
        print("3. Or use other sources listed in CT_MRI_LOCATION.md")
    else:
        print("Datasets downloaded successfully!")
    
    print()
    print("=" * 60)


if __name__ == '__main__':
    main()

347 lines•12.2 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

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