### Start Development Server Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/README.md Starts the development server for the SAM-VMNet website. Access the site at http://localhost:5173. ```bash npm run dev ``` -------------------------------- ### Install SAM-VMNet Dependencies Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Commands to clone the repository and install necessary Python packages. ```bash # Clone the repository git clone https://github.com/qimingfan10/SAM-VMNet.git cd SAM-VMNet # Install Python dependencies pip install -r requirements.txt # Install additional required packages (download .whl files from sources) # mamba_ssm: https://github.com/state-spaces/mamba # causal_conv1d: https://github.com/Dao-AILab/causal-conv1d ``` -------------------------------- ### Install Dependencies Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/README.md Installs project dependencies using npm. Run this command in the project's root directory. ```bash npm install ``` -------------------------------- ### Install dependencies Source: https://github.com/qimingfan10/sam-vmnet/blob/main/README.md Install required Python packages from the requirements file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Deploy to Netlify using CLI Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Install the Netlify CLI and deploy the production build to Netlify. Ensure you are in the website directory and specify the 'dist' folder as the production directory. ```bash npm install -g netlify-cli cd website netlify deploy --prod --dir=dist ``` -------------------------------- ### Deploy to Vercel using CLI Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Install the Vercel CLI and deploy the project to Vercel. The CLI will automatically detect the project and its build settings. ```bash npm install -g vercel cd website vercel --prod ``` -------------------------------- ### Initialize and Run SAMVMNet Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Setup the SAMVMNet model which requires both input images and pre-extracted MedSAM features. ```python from models.vmunet.samvmnet import SAMVMNet import torch # Initialize SAM-VMNet model model = SAMVMNet( num_classes=1, input_channels=3, depths=[2, 2, 2, 2], depths_decoder=[2, 2, 2, 1], drop_path_rate=0.2, load_ckpt_path='./pre_trained_weights/vmamba_tiny_e292.pth' ) model.load_from() device = torch.device('cuda:0') model = model.to(device) # Forward pass requires both image and MedSAM features input_image = torch.randn(4, 3, 256, 256).to(device) medsam_features = torch.randn(4, 256, 64, 64).to(device) # Pre-extracted features output_mask = model(input_image, medsam_features) print(f"SAMVMNet output shape: {output_mask.shape}") # [4, 1, 256, 256] ``` -------------------------------- ### Initialize and Run VMUNet Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Setup the VMUNet model for binary vessel segmentation and perform a forward pass. ```python from models.vmunet.vmunet import VMUNet import torch # Initialize the VMUNet model model = VMUNet( num_classes=1, # Binary segmentation (vessel vs background) input_channels=3, # RGB input images depths=[2, 2, 2, 2], # Encoder layer depths depths_decoder=[2, 2, 2, 1], # Decoder layer depths drop_path_rate=0.2, # Stochastic depth rate load_ckpt_path='./pre_trained_weights/vmamba_tiny_e292.pth' ) # Load pre-trained weights model.load_from() # Move to GPU device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') model = model.to(device) # Forward pass with a batch of images input_image = torch.randn(4, 3, 256, 256).to(device) # Batch of 4 images output_mask = model(input_image) # Returns sigmoid-activated output [4, 1, 256, 256] print(f"Output shape: {output_mask.shape}") print(f"Output range: [{output_mask.min():.3f}, {output_mask.max():.3f}]") ``` -------------------------------- ### DNS Configuration Example Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Example DNS records for configuring a custom domain. This includes an A record for the root domain and a CNAME record for the 'www' subdomain. ```dns A @ 192.0.2.1 CNAME www your-site.netlify.app ``` -------------------------------- ### Install gh-pages for GitHub Pages Deployment Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Install the 'gh-pages' package as a development dependency in your website's package.json. ```bash cd website npm install -D gh-pages ``` -------------------------------- ### Clear Node Modules and Reinstall Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Troubleshoot build failures by removing the 'node_modules' directory and reinstalling dependencies. This ensures a clean installation. ```bash rm -rf node_modules && npm install ``` -------------------------------- ### Clone the repository Source: https://github.com/qimingfan10/sam-vmnet/blob/main/README.md Initial step to download the project source code. ```bash git clone https://github.com/qimingfan10/SAM-VMNet.git cd SAM-VMNet ``` -------------------------------- ### Build for Production Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/README.md Builds the SAM-VMNet website for production. The output will be placed in the 'dist/' directory. ```bash npm run build ``` -------------------------------- ### Serve Website using npx serve Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Serve the 'dist' folder using the 'serve' package via npx. This is a quick way to host static files locally. ```bash npx serve dist ``` -------------------------------- ### Preview Production Build Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/README.md Previews the production build of the SAM-VMNet website. This command is useful for testing the production version locally before deployment. ```bash npm run preview ``` -------------------------------- ### Run training and testing scripts Source: https://github.com/qimingfan10/sam-vmnet/blob/main/README.md Commands to execute training and testing phases for the model branches. ```bash bash train.sh ``` ```bash bash test.sh ``` -------------------------------- ### Configure System Environment Source: https://github.com/qimingfan10/sam-vmnet/blob/main/QUICK_START_STENOSIS.md Add MATLAB to the system PATH if the command is not found. ```bash export PATH="/path/to/MATLAB/bin:$PATH" ``` -------------------------------- ### Serve Website using PHP Built-in Server Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Serve the 'dist' folder locally using PHP's built-in web server. Ensure you are in the 'dist' directory. ```bash cd website/dist php -S localhost:8000 ``` -------------------------------- ### Serve Website using Python HTTP Server Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Serve the 'dist' folder locally using Python's built-in HTTP server. Navigate to the 'dist' directory and run the command. ```bash cd website/dist python -m http.server 8000 ``` -------------------------------- ### Configure and Run Manually in MATLAB Source: https://github.com/qimingfan10/sam-vmnet/blob/main/QUICK_START_STENOSIS.md Manually set image paths in the main script and execute it within the MATLAB environment. ```matlab Im = imread("path/to/your_image.jpg"); % 第4行:原始图像路径 im = imread("path/to/your_mask.png"); % 第7行:掩码图像路径 ``` ```matlab cd stenosis_detection maskjiance1016 ``` -------------------------------- ### List required pre-trained weights Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Directory structure for organizing model checkpoints. ```bash # Required weights (download from Google Drive links in README) ./pre_trained_weights/ ├── vmamba_tiny_e292.pth # VMamba backbone weights ├── vmamba_small_e238_ema.pth # VMamba small variant ├── medsam_vit_b.pth # MedSAM image encoder ├── MedSAM_model.pth # Full MedSAM model ├── best-epoch142-loss0.3230.pth # Trained Branch 1 weights └── best-epoch142-loss0.3488.pth # Trained Branch 2 weights ``` -------------------------------- ### Programmatic Training of Branch 1 Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Configure and initiate training for Branch 1 programmatically. Ensure all necessary parameters like batch size, epochs, and paths are set in the config object. ```python # Programmatic training example from train_branch1 import main, parse_args from configs.config_setting import setting_config # Configure training parameters config = setting_config config.batch_size = 4 config.epochs = 100 config.gpu_id = '0' config.data_path = './data/vessel/' config.work_dir = './work_dir/branch1' # Training outputs: # - Checkpoints saved to: ./work_dir/branch1/checkpoints/ # - Best model: best-epoch{N}-loss{L}.pth # - Training logs: ./work_dir/branch1/log/ # - TensorBoard: ./work_dir/branch1/summary/ ``` -------------------------------- ### Run Stenosis Detection in MATLAB Source: https://github.com/qimingfan10/sam-vmnet/blob/main/README.md Navigate to the 'stenosis_detection' directory and execute the main script. ```bash cd stenosis_detection maskjiance1016 ``` -------------------------------- ### Preprocess Grey and RGB Images Source: https://github.com/qimingfan10/sam-vmnet/blob/main/med_sam/utils/README.md Execute the preprocessing script for grey-scale and RGB images. This involves intensity normalization and resampling. Ensure the correct folder path and modality information are set. ```bash python pre_grey_rgb.py ``` -------------------------------- ### Load Datasets for Training Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Configure DataLoaders for both Branch 1 (images/masks) and Branch 2 (images/masks/features) training pipelines. ```python from dataset import Branch1_datasets, Branch2_datasets from torch.utils.data import DataLoader from configs.config_setting import setting_config # Branch 1 dataset (images + masks only) train_dataset = Branch1_datasets( path_Data='./data/vessel/', config=setting_config, train=True, test=False ) train_loader = DataLoader( train_dataset, batch_size=4, shuffle=True, num_workers=4, pin_memory=True ) # Iterate through batches for images, masks in train_loader: print(f"Images shape: {images.shape}") # [batch, 3, 256, 256] print(f"Masks shape: {masks.shape}") # [batch, 1, 256, 256] break # Branch 2 dataset (images + masks + MedSAM features) train_dataset_b2 = Branch2_datasets( path_Data='./data/vessel/', config=setting_config, train=True, test=False ) for images, masks, features in DataLoader(train_dataset_b2, batch_size=4): print(f"Images: {images.shape}, Masks: {masks.shape}, Features: {features.shape}") # Features shape: [batch, 256, 64, 64] break ``` -------------------------------- ### MATLAB Script Execution (Old vs. New) Source: https://github.com/qimingfan10/sam-vmnet/blob/main/CHANGELOG_STENOSIS.md Demonstrates the backward compatibility and recommended usage patterns for the stenosis detection MATLAB scripts after refactoring. The new method uses startup scripts for a streamlined experience. ```matlab % In the root directory maskjiance1016 ``` ```bash # Using the startup script ./run_stenosis_detection.sh image.jpg mask.png ``` ```matlab % Change to the module directory cd stenosis_detection maskjiance1016 ``` -------------------------------- ### Configure Training Hyperparameters in Python Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Utilize the setting_config class to manage all training hyperparameters, including model architecture, optimizer, and scheduler settings. Modify parameters like batch size, epochs, and learning rate. ```python from configs.config_setting import setting_config # Model configuration config = setting_config print(f"Network: {config.network}") print(f"Model config: {config.model_config}") # {'num_classes': 1, 'input_channels': 3, 'depths': [2,2,2,2], ...} # Training parameters config.batch_size = 4 config.epochs = 300 config.input_size_h = 256 config.input_size_w = 256 config.seed = 42 config.threshold = 0.5 # Binarization threshold # Optimizer: AdamW with cosine annealing config.opt = 'AdamW' config.lr = 0.001 config.weight_decay = 1e-2 config.betas = (0.9, 0.999) # Scheduler config.sch = 'CosineAnnealingLR' config.T_max = 50 config.eta_min = 0.00001 # Data paths config.data_path = './data/vessel/' config.medsam_path = './pre_trained_weights/medsam_vit_b.pth' ``` -------------------------------- ### Run Stenosis Detection via Scripts Source: https://github.com/qimingfan10/sam-vmnet/blob/main/QUICK_START_STENOSIS.md Use the provided shell or Python scripts to execute the detection process with image and mask paths. ```bash # 1. 赋予脚本执行权限(仅第一次需要) chmod +x run_stenosis_detection.sh # 2. 运行狭窄检测 ./run_stenosis_detection.sh path/to/image.jpg path/to/mask.png ``` ```python # 使用 Python 脚本 python run_stenosis_detection.py path/to/image.jpg path/to/mask.png ``` ```bash # 假设你的图像在 data 目录下 ./run_stenosis_detection.sh data/vessel.jpg data/vessel_mask.png # 或使用 Python python run_stenosis_detection.py data/vessel.jpg data/vessel_mask.png ``` -------------------------------- ### Run stenosis detection Source: https://github.com/qimingfan10/sam-vmnet/blob/main/README.md Execute the stenosis detection module using either bash or Python wrappers. ```bash ./run_stenosis_detection.sh [original_image_path] [mask_image_path] ``` ```bash python run_stenosis_detection.py [original_image_path] [mask_image_path] ``` ```bash # With image paths ./run_stenosis_detection.sh data/test.jpg data/test_mask.png # Or run with default images (need to edit maskjiance1016.m first) ./run_stenosis_detection.sh ``` -------------------------------- ### Test Model with Pre-trained Weights Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Run inference on test images using pre-trained model weights. Specify the data path, path to the pre-trained weights, device, and output directory. ```bash python test.py \ --data_path ./data/vessel/ \ --pretrained_weight ./pre_trained_weights/best-epoch142-loss0.3230.pth \ --device cuda:0 \ --output_dir ./test_results ``` -------------------------------- ### Train Branch 1 Model Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Use this command to train the first branch of the SAM-VMNet model. Specify batch size, epochs, GPU ID, data path, and working directory. ```bash python train_branch1.py \ --batch_size 4 \ --epochs 100 \ --gpu_id 0 \ --data_path ./data/vessel/ \ --work_dir ./work_dir/branch1 ``` -------------------------------- ### Manual Testing with Pre-trained Weights Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Perform manual inference using pre-trained weights. This involves loading the model, its state dictionary, and then running predictions on sample data. ```python from test import test_with_pretrained from models.vmunet.vmunet import VMUNet from configs.config_setting import setting_config import torch # Manual testing example device = torch.device('cuda:0') # Load model model_cfg = setting_config.model_config model = VMUNet( num_classes=model_cfg['num_classes'], input_channels=model_cfg['input_channels'], depths=model_cfg['depths'], depths_decoder=model_cfg['depths_decoder'], drop_path_rate=model_cfg['drop_path_rate'], load_ckpt_path=model_cfg['load_ckpt_path'], ) # Load trained weights checkpoint = torch.load('./pre_trained_weights/best-epoch142-loss0.3230.pth', map_location='cpu') model.load_state_dict(checkpoint, strict=False) model = model.to(device) model.eval() # Run inference with torch.no_grad(): test_image = torch.randn(1, 3, 256, 256).to(device) prediction = model(test_image) binary_mask = (prediction > 0.5).float() print(f"Prediction shape: {binary_mask.shape}") ``` -------------------------------- ### Train Branch 2 Model (SAM-VMNet) Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Train the SAM-VMNet model by combining VM-UNet with MedSAM features. This requires pre-trained Branch 1 weights and a MedSAM model. Specify paths for both. ```bash python train_branch2.py \ --batch_size 4 \ --epochs 100 \ --gpu_id 0 \ --data_path ./data/vessel/ \ --work_dir ./work_dir/branch2 \ --medsam_path ./pre_trained_weights/medsam_vit_b.pth \ --branch1_model_path ./work_dir/branch1/checkpoints/best.pth ``` -------------------------------- ### Run Data Splitting Script Source: https://github.com/qimingfan10/sam-vmnet/blob/main/med_sam/utils/README.md Execute the data splitting script to divide datasets into training, validation, and testing sets. Ensure the data path is correctly set within the script. ```bash python split.py ``` -------------------------------- ### Dataset Directory Structure Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Organize your dataset according to the specified directory structure for training and testing. This includes separate folders for images, masks, and auto-generated features. ```text ./data/vessel/ ├── train/ │ ├── images/ │ │ ├── image_001.png │ │ ├── image_002.png │ │ └── ... │ ├── masks/ │ │ ├── mask_001.png │ │ ├── mask_002.png │ │ └── ... │ └── feature/ # Auto-generated by process_images() │ ├── 0.pt │ ├── 1.pt │ └── ... ├── val/ │ ├── images/ │ ├── masks/ │ └── feature/ └── test/ ├── images/ ├── masks/ ├── pred_masks/ # Branch 1 predictions (for Branch 2 training) └── feature/ ``` -------------------------------- ### Configure Image Paths in MATLAB Source: https://github.com/qimingfan10/sam-vmnet/blob/main/stenosis_detection/README_stenosis.md Set the file paths for the original angiographic image and the segmented binary mask before running the detection script. ```matlab Im = imread("path/to/your_original_image.jpg"); im = imread("path/to/your_segmented_mask.png"); ``` -------------------------------- ### Convert Checkpoint Format Source: https://github.com/qimingfan10/sam-vmnet/blob/main/med_sam/utils/README.md Use this script to convert model checkpoints trained with multiple GPUs to a format suitable for single-GPU inference. Ensure `sam_ckpt_path`, `medsam_ckpt_path`, and `save_path` are set correctly before execution. ```bash python ckpt_convert.py ``` -------------------------------- ### Verify pre-trained weights Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Loads and inspects model checkpoints to ensure correct file paths and parameter keys. ```python # Load and verify weights import torch # Check VMamba weights vmamba_ckpt = torch.load('./pre_trained_weights/vmamba_tiny_e292.pth') print(f"VMamba keys: {list(vmamba_ckpt.keys())[:5]}") # Check MedSAM weights medsam_ckpt = torch.load('./pre_trained_weights/medsam_vit_b.pth') print(f"MedSAM keys: {list(medsam_ckpt.keys())[:5]}") # Load trained model trained_weights = torch.load('./pre_trained_weights/best-epoch142-loss0.3230.pth') print(f"Trained model keys: {len(trained_weights)} parameters") ``` -------------------------------- ### Define dataset structure Source: https://github.com/qimingfan10/sam-vmnet/blob/main/README.md Expected directory structure for training, validation, and test datasets. ```text - './data/vessel/' - train - images - .png - masks - .png - val - images - .png - masks - .png - test - images - .png - masks - .png ``` -------------------------------- ### Run Stenosis Detection (Python) Source: https://github.com/qimingfan10/sam-vmnet/blob/main/CHANGELOG_STENOSIS.md Python script for cross-platform execution of the stenosis detection module. It handles MATLAB environment detection, temporary file generation, and cleanup. Supports command-line arguments for image paths. ```python python run_stenosis_detection.py original_image.jpg mask_image.png ``` ```python python run_stenosis_detection.py ``` -------------------------------- ### Execute Detection Script Source: https://github.com/qimingfan10/sam-vmnet/blob/main/stenosis_detection/README_stenosis.md Run the stenosis detection process using either the MATLAB environment or the provided shell script. ```matlab cd stenosis_detection maskjiance1016 ``` ```bash ./run_stenosis_detection.sh ``` -------------------------------- ### Configure package.json for GitHub Pages Deployment Source: https://github.com/qimingfan10/sam-vmnet/blob/main/website/DEPLOYMENT.md Add a 'deploy' script to your package.json to automate the deployment process using gh-pages. This script will deploy the contents of the 'dist' folder. ```json "deploy": "gh-pages -d dist" ``` -------------------------------- ### Preprocess CT/MR Images Source: https://github.com/qimingfan10/sam-vmnet/blob/main/med_sam/utils/README.md Run the preprocessing script specifically for CT and MR images. This includes adjusting window levels and widths, and resampling to a standard size. ```bash python pre_CT_MR.py ``` -------------------------------- ### Run Stenosis Detection (Bash) Source: https://github.com/qimingfan10/sam-vmnet/blob/main/CHANGELOG_STENOSIS.md Bash script for Linux/Mac to run the stenosis detection module. Supports command-line arguments for image paths and provides colored terminal output. Ensure MATLAB is in your system's PATH. ```bash ./run_stenosis_detection.sh original_image.jpg mask_image.png ``` ```bash ./run_stenosis_detection.sh ``` -------------------------------- ### Evaluate 3D volumes Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Performs slice-by-slice evaluation on 3D volumes using the test_single_volume utility. ```python # Batch evaluation during testing from utils import test_single_volume # For 3D volumes (slice-by-slice processing) # image: [D, H, W], label: [D, H, W] image = torch.randn(1, 50, 256, 256) # 50 slices label = torch.randint(0, 2, (1, 50, 256, 256)) metric_list = test_single_volume( image, label, model, classes=2, patch_size=[256, 256], test_save_path='./results/', case='patient_001' ) ``` -------------------------------- ### Manual Stenosis Detection in MATLAB Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Perform quantitative analysis of vessel narrowing using MATLAB. Load original images and segmented masks, then run the main detection script. Results are visualized in figures and accessible via variables. ```matlab % Manual MATLAB usage cd stenosis_detection % Load images Im = imread("path/to/original_image.jpg"); % Original angiogram Im = imresize(Im, [800 600]); im = imread("path/to/segmented_mask.png"); % Binary mask from SAM-VMNet im = imresize(im, [800 600]); if size(im, 3) == 3 im = rgb2gray(im); end % Run detection maskjiance1016 % Main script % Output figures: % Figure 1: Centerline extraction (red dots on mask) % Figure 2: Segmentation points (bifurcation detection) % Figure 3: Stenosis detection results with color-coded severity: % - Red circles: Severe stenosis (>75%) % - Green circles: Moderate stenosis (50-75%) % - Blue circles: Mild stenosis (25-50%) % Access detection results disp('Stenosis points:'); disp(allStenosisPoints); % [x, y] coordinates disp('Stenosis degrees:'); disp(allStenosisDegrees); % Severity values (0-1 scale) ``` -------------------------------- ### Citation BibTeX Source: https://github.com/qimingfan10/sam-vmnet/blob/main/stenosis_detection/README_stenosis.md Use this BibTeX entry to cite the research paper associated with this module. ```bibtex @article{https://doi.org/10.1002/mp.17970, author = {Huang, Baixiang and Luo, Yu and Wei, Guangyu and He, Songyan and Shao, Yushuang and Zeng, Xueying and Zhang, Qing}, title = {Deep learning model for coronary artery segmentation and quantitative stenosis detection in angiographic images}, journal = {Medical Physics}, volume = {52}, number = {7}, pages = {e17970}, doi = {https://doi.org/10.1002/mp.17970}, year = {2025} } ``` -------------------------------- ### Pre-process Images for Branch 2 Training Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Extract MedSAM features from images to be used during Branch 2 training. This process automatically creates feature files (.pt) in the specified data path. ```python # Feature extraction happens automatically during Branch 2 training from feature_processor import process_images # Pre-process images to extract MedSAM features # This creates .pt files in data/vessel/{split}/feature/ process_images( data_path='./data/vessel/', model_path='./pre_trained_weights/medsam_vit_b.pth' ) # Features are saved as: # ./data/vessel/train/feature/0.pt # ./data/vessel/train/feature/1.pt # ... ``` -------------------------------- ### Calculate Segmentation Metrics in Python Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Compute Dice coefficient and Hausdorff distance for segmentation evaluation using the calculate_metric_percase utility. This function requires binary prediction and ground truth masks. ```python from utils import calculate_metric_percase import numpy as np # Binary prediction and ground truth pred = np.random.randint(0, 2, (256, 256)) gt = np.random.randint(0, 2, (256, 256)) ``` -------------------------------- ### BceDiceLoss for Segmentation Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Combines Binary Cross-Entropy and Dice Loss for training segmentation models. Weights can be adjusted to balance precision and recall. Use individual components if needed. ```python from utils import BceDiceLoss, BCELoss, DiceLoss import torch # Combined BCE + Dice Loss (default) criterion = BceDiceLoss(wb=1, wd=1) # Equal weights # Example usage pred = torch.sigmoid(torch.randn(4, 1, 256, 256)) # Predictions [0, 1] target = torch.randint(0, 2, (4, 1, 256, 256)).float() # Binary ground truth loss = criterion(pred, target) print(f"Combined loss: {loss.item():.4f}") # Individual loss components bce_loss = BCELoss()(pred, target) dice_loss = DiceLoss()(pred, target) print(f"BCE: {bce_loss.item():.4f}, Dice: {dice_loss.item():.4f}") ``` -------------------------------- ### Handle Paths with Spaces Source: https://github.com/qimingfan10/sam-vmnet/blob/main/QUICK_START_STENOSIS.md Use quotes when passing file paths containing spaces to the shell script. ```bash ./run_stenosis_detection.sh "path/with spaces/image.jpg" "path/with spaces/mask.png" ``` -------------------------------- ### Adjust Stenosis Detection Parameters in MATLAB Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Fine-tune the sensitivity of stenosis detection by modifying key parameters within the maskjiance1016.m script. Adjust thresholds for radius search, point filtering, and stenosis degree. ```matlab % Key parameters in maskjiance1016.m % Line 43: Radius search range for MoM calculation r = 110; % Increase for larger vessels, decrease for smaller % Line 76: Distance threshold for filtering nearby segmentation points if distMatrix(i, j) < 8 % Increase to merge more bifurcation points keepPoints(j) = false; end % Line 115: Stenosis detection thresholds if nn > 0.25 && average_R > 4 % nn: stenosis degree threshold (0.25 = 25% narrowing) % average_R: minimum average radius threshold % Decrease 0.25 to detect milder stenosis % Decrease 4 to detect stenosis in thinner vessels end % Example: More sensitive detection if nn > 0.20 && average_R > 3 xiazhaichengdu = [xiazhaichengdu; nn]; middlePoints = [middlePoints; queue(i, :)]; end ``` -------------------------------- ### Adjust Detection Parameters Source: https://github.com/qimingfan10/sam-vmnet/blob/main/stenosis_detection/README_stenosis.md Modify these variables in maskjiance1016.m to tune the sensitivity and thresholds of the stenosis detection algorithm. ```matlab r = 110; % 半径检索范围 (Radius search range) distThreshold = 8; % 分段点距离阈值 (Segmentation point distance threshold) stenosisThreshold = 0.25; % 狭窄检测阈值 (Stenosis detection threshold) averageRThreshold = 4; % 平均半径阈值 (Average radius threshold) ``` -------------------------------- ### Data Augmentation Transforms Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Custom transforms for medical image augmentation including normalization, flipping, and rotation. Use 'train_transformer' for training and 'test_transformer' for testing. ```python from utils import myNormalize, myToTensor, myResize, myRandomHorizontalFlip, myRandomVerticalFlip, myRandomRotation from torchvision import transforms import numpy as np # Training transforms with augmentation train_transformer = transforms.Compose([ myNormalize('vessel', train=True), # Normalize to training statistics myToTensor(), # Convert to tensor myRandomHorizontalFlip(p=0.5), # 50% horizontal flip myRandomVerticalFlip(p=0.5), # 50% vertical flip myRandomRotation(p=0.5, degree=[0, 360]), # Random rotation myResize(256, 256) # Resize to 256x256 ]) # Test transforms (no augmentation) test_transformer = transforms.Compose([ myNormalize('vessel', train=False), myToTensor(), myResize(256, 256) ]) # Apply transforms image = np.random.rand(512, 512, 3) * 255 # HWC format mask = np.random.randint(0, 2, (512, 512, 1)) # HWC format image_tensor, mask_tensor = train_transformer((image, mask)) print(f"Transformed image: {image_tensor.shape}") # [3, 256, 256] print(f"Transformed mask: {mask_tensor.shape}") # [1, 256, 256] ``` -------------------------------- ### Adjust Detection Sensitivity Source: https://github.com/qimingfan10/sam-vmnet/blob/main/QUICK_START_STENOSIS.md Modify parameters in maskjiance1016.m to tune detection sensitivity and filtering. ```matlab % 第43行:检索半径(越大检测范围越广) r = 110; % 第76行:分段点距离阈值 if distMatrix(i, j) < 8 % 改为更大值:分段点过滤更严格 % 第115行:狭窄检测阈值 if nn > 0.25 && average_R > 4 % 调整这两个值 ``` -------------------------------- ### Extract MedSAM Features in Python Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Extract MedSAM image encoder features for Branch 2 training using point prompts from mask boundaries. This can be done in batch or for single images, with options to save and load features. ```python from med_sam.medsam_point import medsam_point from feature_processor import process_images import torch # Batch process all images process_images( data_path='./data/vessel/', model_path='./pre_trained_weights/medsam_vit_b.pth' ) # Single image feature extraction features = medsam_point( image_path='./data/vessel/train/images/001.png', mask_path='./data/vessel/train/masks/001.png', model_path='./pre_trained_weights/medsam_vit_b.pth' ) print(f"Extracted features shape: {features.shape}") # [256, 64, 64] # Save features torch.save(features, './data/vessel/train/feature/0.pt') # Load features loaded_features = torch.load('./data/vessel/train/feature/0.pt', map_location='cpu') ``` -------------------------------- ### Calculate segmentation metrics Source: https://context7.com/qimingfan10/sam-vmnet/llms.txt Computes Dice coefficient and 95% Hausdorff distance for model predictions against ground truth. ```python # Calculate metrics dice, hd95 = calculate_metric_percase(pred, gt) print(f"Dice coefficient: {dice:.4f}") print(f"Hausdorff distance (95%): {hd95:.2f} pixels") ``` -------------------------------- ### Modify Image Paths in MATLAB Source: https://github.com/qimingfan10/sam-vmnet/blob/main/README.md Update the paths for the original image and segmented mask within the MATLAB script. ```matlab Im = imread("your_original_image.jpg"); im = imread("your_segmented_mask.png"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.