Upload 2 files
Browse filesFiles changed (2)
- simnict_download.pyAdded+585
- simnict_generator.pyAdded+268
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SimNICT Dataset Batch Downloader
Download complete SimNICT datasets from Internet Archive
IMPORTANT: This downloader provides access to 8 out of 10 original SimNICT datasets.
AutoPET and HECKTOR22 are excluded from public release due to licensing restrictions.
Usage:
python download_simnict.py --datasets AMOS COVID_19_NY_SBU --output_dir ./data
python download_simnict.py --all --output_dir ./data
python download_simnict.py --list # Show available datasets
Author: TAMP Research Group
Version: 1.0
"""
import os
import sys
import argparse
import time
from pathlib import Path
from typing import List, Dict, Optional
import logging
try:
import internetarchive as ia
except ImportError:
print("❌ Error: internetarchive library not found")
print("Please install it using: pip install internetarchive")
sys.exit(1)
# =============================================================================
# Dataset Configuration
# =============================================================================
SIMNICT_DATASETS = {
"AMOS": {
"identifier": "simnict-amos",
"description": "Abdominal multi-organ segmentation dataset",
"volumes": 500,
"files": 504,
"size_gb": "~22 GB"
},
"COVID_19_NY_SBU": {
"identifier": "simnict-covid-19-ny-sbu",
"description": "COVID-19 NY-SBU chest CT dataset",
"volumes": 459,
"files": 463,
"size_gb": "~30 GB"
},
"CT_Images_COVID19": {
"identifier": "simnict-ct-images-in-covid-19",
"description": "CT Images in COVID-19 dataset",
"volumes": 771,
"files": 775,
"size_gb": "~13 GB"
},
"CT_COLONOGRAPHY": {
"identifier": "simnict-ct-colonography",
"description": "CT colonography screening dataset",
"volumes": 1730,
"files": 1734,
"size_gb": "~271 GB"
},
"LNDb": {
"identifier": "simnict-lndb",
"description": "Lung nodule database",
"volumes": 294,
"files": 298,
"size_gb": "~34 GB"
},
"LUNA": {
"identifier": "simnict-luna",
"description": "Lung nodule analysis dataset",
"volumes": 888,
"files": 892,
"size_gb": "~63 GB"
},
"MELA": {
"identifier": "simnict-mela",
"description": "Melanoma detection dataset",
"volumes": 1100,
"files": 1104,
"size_gb": "~147 GB"
},
"STOIC": {
"identifier": "simnict-stoic",
"description": "COVID-19 AI challenge dataset",
"volumes": 2000,
"files": 2004,
"size_gb": "~243 GB"
}
}
# =============================================================================
# Logging Configuration
# =============================================================================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('simnict_download.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# =============================================================================
# SimNICT Downloader Class
# =============================================================================
class SimNICTDownloader:
def __init__(self, output_dir: str = "./simnict_data",
max_retries: int = 3, chunk_size: int = 1024*1024):
"""
Initialize SimNICT downloader
Args:
output_dir: Directory to save downloaded datasets
max_retries: Maximum retry attempts for failed downloads
chunk_size: Download chunk size in bytes (default 1MB)
"""
self.output_dir = Path(output_dir)
self.max_retries = max_retries
self.chunk_size = chunk_size
# Create output directory
self.output_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"📁 Output directory: {self.output_dir.absolute()}")
def list_available_datasets(self) -> None:
"""Display all available SimNICT datasets"""
print("\n" + "="*80)
print("📋 Available SimNICT Datasets (8 out of 10 original datasets)")
print("="*80)
print("ℹ️ Note: AutoPET and HECKTOR22 excluded due to licensing restrictions")
print("="*80)
total_size = 0
total_volumes = 0
for name, info in SIMNICT_DATASETS.items():
print(f"\n🔹 {name}")
print(f" 📝 Description: {info['description']}")
print(f" 📊 Volumes: {info['volumes']:,}")
print(f" 📄 Files: {info['files']:,}")
print(f" 💾 Size: {info['size_gb']}")
print(f" 🏷️ ID: {info['identifier']}")
print(f" 🔗 URL: https://archive.org/details/{info['identifier']}")
total_volumes += info['volumes']
# Extract numeric size for total calculation
size_str = info['size_gb'].replace('~', '').replace(' GB', '')
try:
total_size += float(size_str)
except:
pass
print(f"\n📈 Total Statistics:")
print(f" 🗂️ Datasets: {len(SIMNICT_DATASETS)}")
print(f" 📊 Total Volumes: {total_volumes:,}")
print(f" 💾 Total Size: ~{total_size:.0f} GB")
print("="*80)
def check_dataset_exists(self, identifier: str) -> bool:
"""Check if dataset exists on Internet Archive"""
try:
item = ia.get_item(identifier)
return item.exists
except Exception as e:
logger.error(f"Error checking dataset {identifier}: {e}")
return False
def get_dataset_files(self, identifier: str) -> List[str]:
"""Get list of files in a dataset"""
try:
item = ia.get_item(identifier)
if not item.exists:
return []
files = []
for file_obj in item.files:
if isinstance(file_obj, dict) and 'name' in file_obj:
# Only include .nii.gz files (skip metadata)
filename = file_obj['name']
if filename.endswith('.nii.gz'):
files.append(filename)
return sorted(files)
except Exception as e:
logger.error(f"Error getting files for {identifier}: {e}")
return []
def download_dataset(self, dataset_name: str,
resume: bool = True,
verify_checksum: bool = True) -> bool:
"""
Download a specific SimNICT dataset
Args:
dataset_name: Name of dataset to download
resume: Whether to resume partial downloads
verify_checksum: Whether to verify file checksums
Returns:
True if download successful, False otherwise
"""
if dataset_name not in SIMNICT_DATASETS:
logger.error(f"❌ Unknown dataset: {dataset_name}")
logger.info(f"Available datasets: {list(SIMNICT_DATASETS.keys())}")
return False
dataset_info = SIMNICT_DATASETS[dataset_name]
identifier = dataset_info['identifier']
logger.info(f"\n{'='*60}")
logger.info(f"📤 Starting download: {dataset_name}")
logger.info(f"🏷️ Identifier: {identifier}")
logger.info(f"📊 Expected volumes: {dataset_info['volumes']}")
logger.info(f"💾 Estimated size: {dataset_info['size_gb']}")
logger.info(f"{'='*60}")
# Check if dataset exists
if not self.check_dataset_exists(identifier):
logger.error(f"❌ Dataset not found on Internet Archive: {identifier}")
return False
# Create dataset directory
dataset_dir = self.output_dir / dataset_name
dataset_dir.mkdir(exist_ok=True)
# Get files to download
files_to_download = self.get_dataset_files(identifier)
if not files_to_download:
logger.error(f"❌ No files found for dataset: {dataset_name}")
return False
logger.info(f"📋 Found {len(files_to_download)} files to download")
# Check existing files if resuming
existing_files = set()
if resume:
for file_path in dataset_dir.iterdir():
if file_path.is_file() and file_path.suffix == '.gz':
existing_files.add(file_path.name)
if existing_files:
logger.info(f"📂 Found {len(existing_files)} existing files (resume mode)")
# Download files
successful_downloads = 0
failed_downloads = 0
skipped_files = 0
for i, filename in enumerate(files_to_download, 1):
file_path = dataset_dir / filename
# Skip if file exists and resuming
if resume and filename in existing_files:
logger.info(f"⏭️ Skipping existing file [{i}/{len(files_to_download)}]: {filename}")
skipped_files += 1
continue
logger.info(f"📥 Downloading [{i}/{len(files_to_download)}]: {filename}")
success = self._download_file_with_retry(
identifier, filename, file_path, verify_checksum
)
if success:
successful_downloads += 1
logger.info(f"✅ Downloaded: {filename}")
else:
failed_downloads += 1
logger.error(f"❌ Failed: {filename}")
# Brief pause between downloads
time.sleep(0.5)
# Summary
logger.info(f"\n📊 Download Summary for {dataset_name}:")
logger.info(f" ✅ Successful: {successful_downloads}")
logger.info(f" ⏭️ Skipped: {skipped_files}")
logger.info(f" ❌ Failed: {failed_downloads}")
logger.info(f" 📁 Location: {dataset_dir.absolute()}")
return failed_downloads == 0
def _download_file_with_retry(self, identifier: str, filename: str,
file_path: Path, verify_checksum: bool) -> bool:
"""Download single file with retry logic"""
for attempt in range(self.max_retries):
try:
# Use internetarchive library to download
item = ia.get_item(identifier)
# Find the file object
file_obj = None
for f in item.files:
if isinstance(f, dict) and f.get('name') == filename:
file_obj = f
break
if not file_obj:
logger.error(f"File not found in item: {filename}")
return False
# Download the file
success = item.download(
files=[filename],
destdir=file_path.parent,
verify=verify_checksum,
verbose=False,
retries=1 # Handle retries at our level
)
if success and file_path.exists():
return True
else:
raise Exception("Download failed or file not created")
except Exception as e:
logger.warning(f"⚠️ Attempt {attempt + 1}/{self.max_retries} failed for {filename}: {e}")
if attempt < self.max_retries - 1:
wait_time = (attempt + 1) * 2 # Exponential backoff
logger.info(f"🔄 Retrying in {wait_time} seconds...")
time.sleep(wait_time)
else:
logger.error(f"💔 All {self.max_retries} attempts failed for {filename}")
return False
return False
def download_multiple_datasets(self, dataset_names: List[str],
resume: bool = True) -> Dict[str, bool]:
"""
Download multiple SimNICT datasets
Args:
dataset_names: List of dataset names to download
resume: Whether to resume partial downloads
Returns:
Dictionary mapping dataset names to success status
"""
if not dataset_names:
logger.error("❌ No datasets specified")
return {}
logger.info(f"\n🚀 Starting batch download of {len(dataset_names)} datasets")
logger.info(f"📋 Datasets: {', '.join(dataset_names)}")
results = {}
successful = 0
for i, dataset_name in enumerate(dataset_names, 1):
logger.info(f"\n{'🔄' * 20} Dataset {i}/{len(dataset_names)} {'🔄' * 20}")
success = self.download_dataset(dataset_name, resume=resume)
results[dataset_name] = success
if success:
successful += 1
logger.info(f"🎉 Successfully downloaded: {dataset_name}")
else:
logger.error(f"💔 Failed to download: {dataset_name}")
# Final summary
logger.info(f"\n{'=' * 80}")
logger.info(f"🏁 Batch Download Complete")
logger.info(f"{'=' * 80}")
logger.info(f"✅ Successful: {successful}/{len(dataset_names)}")
logger.info(f"❌ Failed: {len(dataset_names) - successful}")
for dataset_name, success in results.items():
status = "✅" if success else "❌"
logger.info(f" {status} {dataset_name}")
return results
def validate_downloads(self, dataset_names: List[str]) -> Dict[str, Dict]:
"""
Validate downloaded datasets
Args:
dataset_names: List of dataset names to validate
Returns:
Validation results for each dataset
"""
logger.info(f"\n🔍 Validating {len(dataset_names)} datasets...")
results = {}
for dataset_name in dataset_names:
if dataset_name not in SIMNICT_DATASETS:
continue
dataset_dir = self.output_dir / dataset_name
expected_info = SIMNICT_DATASETS[dataset_name]
if not dataset_dir.exists():
results[dataset_name] = {
"status": "missing",
"message": "Dataset directory not found"
}
continue
# Count downloaded files
nii_files = list(dataset_dir.glob("*.nii.gz"))
file_count = len(nii_files)
expected_files = expected_info['files']
completion_rate = (file_count / expected_files) * 100
if file_count == expected_files:
status = "complete"
message = f"All {file_count} files downloaded successfully"
elif file_count > 0:
status = "partial"
message = f"Partial download: {file_count}/{expected_files} files ({completion_rate:.1f}%)"
else:
status = "empty"
message = "No files found"
results[dataset_name] = {
"status": status,
"files_found": file_count,
"files_expected": expected_files,
"completion_rate": completion_rate,
"message": message
}
logger.info(f"📊 {dataset_name}: {message}")
return results
# =============================================================================
# Command Line Interface
# =============================================================================
def main():
parser = argparse.ArgumentParser(
description="Download SimNICT datasets from Internet Archive",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# List available datasets
python download_simnict.py --list
# Download specific datasets
python download_simnict.py --datasets AMOS COVID_19_NY_SBU --output_dir ./data
# Download all datasets
python download_simnict.py --all --output_dir ./data
# Resume interrupted downloads
python download_simnict.py --datasets STOIC --resume --output_dir ./data
# Validate existing downloads
python download_simnict.py --validate AMOS LUNA --output_dir ./data
"""
)
parser.add_argument(
"--datasets", nargs="+", metavar="DATASET",
help="List of datasets to download (e.g., AMOS LUNA STOIC)"
)
parser.add_argument(
"--all", action="store_true",
help="Download all available SimNICT datasets"
)
parser.add_argument(
"--list", action="store_true",
help="List available datasets and exit"
)
parser.add_argument(
"--validate", nargs="*", metavar="DATASET",
help="Validate downloaded datasets"
)
parser.add_argument(
"--output_dir", default="./simnict_data",
help="Output directory for downloads (default: ./simnict_data)"
)
parser.add_argument(
"--resume", action="store_true",
help="Resume interrupted downloads (skip existing files)"
)
parser.add_argument(
"--no-checksum", action="store_true",
help="Skip checksum verification (faster but less safe)"
)
parser.add_argument(
"--max-retries", type=int, default=3,
help="Maximum retry attempts for failed downloads (default: 3)"
)
args = parser.parse_args()
# Handle list command
if args.list:
downloader = SimNICTDownloader()
downloader.list_available_datasets()
return
# Handle validation
if args.validate is not None:
datasets_to_validate = args.validate if args.validate else list(SIMNICT_DATASETS.keys())
downloader = SimNICTDownloader(args.output_dir)
results = downloader.validate_downloads(datasets_to_validate)
return
# Determine datasets to download
if args.all:
datasets = list(SIMNICT_DATASETS.keys())
elif args.datasets:
datasets = args.datasets
else:
parser.error("Must specify --datasets, --all, --list, or --validate")
# Validate dataset names
invalid_datasets = [d for d in datasets if d not in SIMNICT_DATASETS]
if invalid_datasets:
logger.error(f"❌ Invalid dataset names: {invalid_datasets}")
logger.info(f"Available datasets: {list(SIMNICT_DATASETS.keys())}")
return
# Initialize downloader
downloader = SimNICTDownloader(
output_dir=args.output_dir,
max_retries=args.max_retries
)
# Show download plan
logger.info(f"\n📋 Download Plan:")
total_size = 0
for dataset in datasets:
info = SIMNICT_DATASETS[dataset]
logger.info(f" 🔹 {dataset}: {info['size_gb']} ({info['volumes']} volumes)")
# Extract size for total calculation
try:
size_num = float(info['size_gb'].replace('~', '').replace(' GB', ''))
total_size += size_num
except:
pass
logger.info(f" 💾 Total estimated size: ~{total_size:.0f} GB")
# Confirm download
try:
confirm = input(f"\nProceed with download? (y/N): ").strip().lower()
if confirm != 'y':
logger.info("❌ Download cancelled by user")
return
except KeyboardInterrupt:
logger.info("\n❌ Download cancelled by user")
return
# Start downloads
start_time = time.time()
results = downloader.download_multiple_datasets(datasets, resume=args.resume)
end_time = time.time()
# Final report
elapsed = end_time - start_time
logger.info(f"\n⏱️ Total time: {elapsed:.1f} seconds ({elapsed/60:.1f} minutes)")
# Validate downloads
if any(results.values()):
logger.info("\n🔍 Validating downloads...")
validation_results = downloader.validate_downloads(list(results.keys()))
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268# -*- coding = utf-8 -*-
"""
SimNICT Dataset Generator
Generates Non-Ideal measurement CT (NICT) simulations from preprocessed ICT data
This script creates three types of NICT simulations:
1. Sparse-View CT (SVCT): Limited projection views (15-360 views)
2. Limited-Angle CT (LACT): Restricted angular range (75°-270°)
3. Low-Dose CT (LDCT): Reduced photon dose (5%-75% of normal dose)
Usage:
python simnict_generator.py
Dependencies: numpy, torch, nibabel, odl, astra-toolbox, opencv-python, pillow
"""
from __future__ import absolute_import, print_function
import numpy as np
import time
import os
import nibabel as nib
import odl
import random
import astra
# Dataset configuration
DATASETS = ['AMOS', 'COVID_19_NY_SBU', 'CT Images in COVID-19', 'CT_COLONOGRAPHY', 'LNDb', 'LUNA', 'MELA', 'STOIC']
# Path configuration
INPUT_PATH = 'M:/' # Original ICT data path
OUTPUT_SVCT = 'K:/SpV/' # Sparse-view CT output path
OUTPUT_LACT = 'K:/LmV/' # Limited-angle CT output path
OUTPUT_LDCT = 'K:/LD/' # Low-dose CT output path
# Simulation parameter ranges
SVCT_VIEW_RANGE = (15, 360) # Number of projection views
LACT_ANGLE_RANGE = (75, 270) # Angular range in degrees
LDCT_DOSE_RANGE = (5, 75) # Dose percentage
def process_dataset(input_path, dataset_name):
"""
Process a complete dataset to generate NICT simulations
Args:
input_path (str): Path to input ICT data
dataset_name (str): Name of the dataset to process
"""
ict_path = os.path.join(input_path, dataset_name, "int16/")
if not os.path.exists(ict_path):
print(f"Warning: Path {ict_path} does not exist, skipping {dataset_name}")
return
# Create output directories
for output_path in [OUTPUT_SVCT, OUTPUT_LACT, OUTPUT_LDCT]:
os.makedirs(os.path.join(output_path, dataset_name, "int16/"), exist_ok=True)
files = os.listdir(ict_path)
num_files = len(files)
print(f"Processing {dataset_name}: {num_files} files")
for i, filename in enumerate(files):
print(f"Processing {dataset_name} - File {i+1}/{num_files}: {filename}")
# Load ICT volume
ict_file_path = os.path.join(ict_path, filename)
image_obj = nib.load(ict_file_path)
ict_volume = image_obj.get_fdata() + 1024 # Convert to [0, 4096] range
ict_volume[ict_volume < 0] = 0
L, W, S = ict_volume.shape
# Initialize output volumes
svct_volume = np.zeros((L, W, S), dtype=np.int16)
lact_volume = np.zeros((L, W, S), dtype=np.int16)
ldct_volume = np.zeros((L, W, S), dtype=np.int16)
# Process each slice
for slice_idx in range(S):
ict_slice = ict_volume[:, :, slice_idx]
# Generate SVCT with random view number
svct_views = random.randint(*SVCT_VIEW_RANGE)
svct_slice = create_sparse_view_ct(ict_slice, L, W, svct_views)
svct_volume[:, :, slice_idx] = svct_slice
# Generate LACT with random angular range
lact_angle = random.randint(*LACT_ANGLE_RANGE)
lact_slice = create_limited_angle_ct(ict_slice, L, W, lact_angle)
lact_volume[:, :, slice_idx] = lact_slice
# Generate LDCT with random dose level
ldct_dose = random.randint(*LDCT_DOSE_RANGE)
ldct_slice = create_low_dose_ct(ict_slice - 1024, L, W, ldct_dose) # Convert back to [-1024, 3072]
ldct_volume[:, :, slice_idx] = ldct_slice
# Save NICT volumes
save_nict_volume(svct_volume, OUTPUT_SVCT, dataset_name, filename, volume_type="SVCT")
save_nict_volume(lact_volume, OUTPUT_LACT, dataset_name, filename, volume_type="LACT")
save_nict_volume(ldct_volume, OUTPUT_LDCT, dataset_name, filename, volume_type="LDCT")
def save_nict_volume(volume, output_path, dataset_name, filename, volume_type):
"""Save NICT volume to NIfTI format"""
if volume_type in ["SVCT", "LACT"]:
# Convert from [0, 4096] to [-1024, 3072] range
volume_output = volume - 1024
volume_output[volume_output < -1024] = -1024
else: # LDCT
# Already in [-1024, 3072] range
volume_output = volume
volume_output[volume_output < -1024] = -1024
nifti_image = nib.Nifti1Image(volume_output, np.eye(4))
output_file = os.path.join(output_path, dataset_name, "int16/", filename)
nib.save(nifti_image, output_file)
def create_sparse_view_ct(ict_slice, height, width, num_views):
"""
Generate Sparse-View CT using ODL
Args:
ict_slice: Input ICT slice [0, 4096]
height, width: Image dimensions
num_views: Number of projection views
Returns:
Reconstructed sparse-view CT slice
"""
# Create reconstruction space
reco_space = odl.uniform_discr(
min_pt=[-height/4, -width/4],
max_pt=[height/4, width/4],
shape=[height, width],
dtype='float32'
)
# Define geometry with limited views
angle_partition = odl.uniform_partition(0, 2 * np.pi, num_views)
detector_partition = odl.uniform_partition(-360, 360, 1024)
geometry = odl.tomo.FanBeamGeometry(
angle_partition, detector_partition,
src_radius=1270, det_radius=870
)
# Create ray transform and reconstruct
ray_trafo = odl.tomo.RayTransform(reco_space, geometry)
projection = ray_trafo(ict_slice.astype('float32'))
fbp = odl.tomo.fbp_op(ray_trafo)
reconstruction = fbp(projection)
return reconstruction
def create_limited_angle_ct(ict_slice, height, width, angle_range):
"""
Generate Limited-Angle CT using ODL
Args:
ict_slice: Input ICT slice [0, 4096]
height, width: Image dimensions
angle_range: Angular range in degrees
Returns:
Reconstructed limited-angle CT slice
"""
# Create reconstruction space
reco_space = odl.uniform_discr(
min_pt=[-height/4, -width/4],
max_pt=[height/4, width/4],
shape=[height, width],
dtype='float32'
)
# Define geometry with limited angular range
angle_fraction = angle_range / 360
num_angles = int(720 * angle_fraction)
angle_partition = odl.uniform_partition(0, 2 * np.pi * angle_fraction, num_angles)
detector_partition = odl.uniform_partition(-360, 360, 1024)
geometry = odl.tomo.FanBeamGeometry(
angle_partition, detector_partition,
src_radius=1270, det_radius=870
)
# Create ray transform and reconstruct
ray_trafo = odl.tomo.RayTransform(reco_space, geometry)
projection = ray_trafo(ict_slice.astype('float32'))
fbp = odl.tomo.fbp_op(ray_trafo)
reconstruction = fbp(projection)
return reconstruction
def create_low_dose_ct(ict_slice, height, width, dose_percentage):
"""
Generate Low-Dose CT using ASTRA with Poisson noise simulation
Args:
ict_slice: Input ICT slice [-1024, 3072]
height, width: Image dimensions
dose_percentage: Dose level as percentage of normal dose
Returns:
Reconstructed low-dose CT slice
"""
dose_fraction = dose_percentage / 100.0
# Convert to attenuation coefficients
u = 0.0192 # Linear attenuation coefficient
attenuation_map = ict_slice * u / 1000.0 + u
# ASTRA geometry setup
vol_geom = astra.create_vol_geom([height, width])
angles = np.linspace(np.pi, -np.pi, 720)
proj_geom = astra.create_proj_geom(
'fanflat', 1.685839319229126, 1024, angles,
600.4500331878662, 485.1499423980713
)
# Create projector and forward project
proj_id = astra.create_projector('cuda', proj_geom, vol_geom)
operator = astra.OpTomo(proj_id)
# Forward projection
sinogram = operator * np.mat(attenuation_map) / 2
# Add Poisson noise based on dose level
noise = np.random.normal(0, 1, 720 * 1024)
noise_scaling = np.sqrt((1 - dose_fraction) / dose_fraction * (np.exp(sinogram) / 1e6))
noisy_sinogram = sinogram + noise * noise_scaling
# Reconstruct with FBP
noisy_sinogram_2d = np.reshape(noisy_sinogram, [720, -1])
reconstruction = operator.reconstruct('FBP_CUDA', noisy_sinogram_2d)
# Convert back to HU values
reconstruction = reconstruction.reshape((height, width))
return (reconstruction * 2 - u) / u * 1000
def main():
"""Main processing function"""
print('SimNICT Dataset Generator Started')
start_time = time.time()
# Process each dataset
for dataset_name in DATASETS:
print(f"\n{'='*50}")
print(f"Processing Dataset: {dataset_name}")
print(f"{'='*50}")
try:
process_dataset(INPUT_PATH, dataset_name)
duration = time.time() - start_time
print(f"Completed {dataset_name} in {duration:.1f} seconds")
except Exception as e:
print(f"Error processing {dataset_name}: {str(e)}")
continue
total_duration = time.time() - start_time
print(f"\nSimNICT Generation Complete - Total time: {total_duration/3600:.2f} hours")
if __name__ == "__main__":
main()
simnict_download.pyAdded+585
simnict_generator.pyAdded+268