Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 17, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 17, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 17, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 17, 2025

      Microsoft’s allegiance isn’t to OpenAI’s pricey models — Satya Nadella’s focus is selling any AI customers want for maximum profits

      May 17, 2025

      If you think you can do better than Xbox or PlayStation in the Console Wars, you may just want to try out this card game

      May 17, 2025

      Surviving a 10 year stint in dev hell, this retro-styled hack n’ slash has finally arrived on Xbox

      May 17, 2025

      Save $400 on the best Samsung TVs, laptops, tablets, and more when you sign up for Verizon 5G Home or Home Internet

      May 17, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      NodeSource N|Solid Runtime Release – May 2025: Performance, Stability & the Final Update for v18

      May 17, 2025
      Recent

      NodeSource N|Solid Runtime Release – May 2025: Performance, Stability & the Final Update for v18

      May 17, 2025

      Big Changes at Meteor Software: Our Next Chapter

      May 17, 2025

      Apps in Generative AI – Transforming the Digital Experience

      May 17, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft’s allegiance isn’t to OpenAI’s pricey models — Satya Nadella’s focus is selling any AI customers want for maximum profits

      May 17, 2025
      Recent

      Microsoft’s allegiance isn’t to OpenAI’s pricey models — Satya Nadella’s focus is selling any AI customers want for maximum profits

      May 17, 2025

      If you think you can do better than Xbox or PlayStation in the Console Wars, you may just want to try out this card game

      May 17, 2025

      Surviving a 10 year stint in dev hell, this retro-styled hack n’ slash has finally arrived on Xbox

      May 17, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»How to Build a Prototype X-ray Judgment Tool (Open Source Medical Inference System) Using TorchXRayVision, Gradio, and PyTorch

    How to Build a Prototype X-ray Judgment Tool (Open Source Medical Inference System) Using TorchXRayVision, Gradio, and PyTorch

    March 31, 2025

    In this tutorial, we demonstrate how to build a prototype X-ray judgment tool using open-source libraries in Google Colab. By leveraging the power of TorchXRayVision for loading pre-trained DenseNet models and Gradio for creating an interactive user interface, we show how to process and classify chest X-ray images with minimal setup. This notebook guides you through image preprocessing, model inference, and result interpretation, all designed to run seamlessly on Colab without requiring external API keys or logins. Please note that this demo is intended for educational purposes only and should not be used as a substitute for professional clinical diagnosis.

    Copy CodeCopiedUse a different Browser
    !pip install torchxrayvision gradio

    First, we install the torchxrayvision library for X-ray analysis and Gradio to create an interactive interface.

    Copy CodeCopiedUse a different Browser
    import torch
    import torchxrayvision as xrv
    import torchvision.transforms as transforms
    import gradio as gr

    We import PyTorch for deep learning operations, TorchXRayVision for X‑ray analysis, torchvision’s transforms for image preprocessing, and Gradio for building an interactive UI.

    Copy CodeCopiedUse a different Browser
    model = xrv.models.DenseNet(weights="densenet121-res224-all")
    model.eval()  

    Then, we load a pre-trained DenseNet model using the “densenet121-res224-all” weights and set it to evaluation mode for inference.

    Copy CodeCopiedUse a different Browser
    try:
        pathology_labels = model.meta["labels"]
        print("Retrieved pathology labels from model.meta.")
    except Exception as e:
        print("Could not retrieve labels from model.meta. Using fallback labels.")
        pathology_labels = [
             "Atelectasis", "Cardiomegaly", "Consolidation", "Edema",
             "Emphysema", "Fibrosis", "Hernia", "Infiltration", "Mass",
             "Nodule", "Pleural Effusion", "Pneumonia", "Pneumothorax", "No Finding"
        ]
    

    Now, we attempt to retrieve pathology labels from the model’s metadata and fall back to a predefined list if the retrieval fails.

    Copy CodeCopiedUse a different Browser
    def classify_xray(image):
        try:
            transform = transforms.Compose([
                transforms.Resize((224, 224)),
                transforms.Grayscale(num_output_channels=1),
                transforms.ToTensor()
            ])
            input_tensor = transform(image).unsqueeze(0)  # add batch dimension
    
    
            with torch.no_grad():
                preds = model(input_tensor)
           
            pathology_scores = preds[0].detach().numpy()
            results = {}
            for idx, label in enumerate(pathology_labels):
                results[label] = float(pathology_scores[idx])
           
            sorted_results = sorted(results.items(), key=lambda x: x[1], reverse=True)
            top_label, top_score = sorted_results[0]
           
            judgement = (
                f"Prediction: {top_label} (score: {top_score:.2f})nn"
                f"Full Scores:n{results}"
            )
            return judgement
        except Exception as e:
            return f"Error during inference: {str(e)}"

    Here, with this function, we preprocess an input X-ray image, run inference using the pre-trained model, extract pathology scores, and return a formatted summary of the top prediction and all scores while handling errors gracefully.

    Copy CodeCopiedUse a different Browser
    iface = gr.Interface(
        fn=classify_xray,
        inputs=gr.Image(type="pil"),
        outputs="text",
        title="X-ray Judgement Tool (Prototype)",
        description=(
            "Upload a chest X-ray image to receive a classification judgement. "
            "This demo is for educational purposes only and is not intended for clinical use."
        )
    )
    
    
    iface.launch()
    

    Finally, we build and launch a Gradio interface that lets users upload a chest X-ray image. The classify_xray function processes the image to output a diagnostic judgment.

    Gradio Interface for the tool

    Through this tutorial, we’ve explored the development of an interactive X-ray judgment tool that integrates advanced deep learning techniques with a user-friendly interface. Despite the inherent limitations, such as the model not being fine-tuned for clinical diagnostics, this prototype serves as a valuable starting point for experimenting with medical imaging applications. We encourage you to build upon this foundation, considering the importance of rigorous validation and adherence to medical standards for real-world use.


    Here is the Colab Notebook. Also, don’t forget to follow us on Twitter and join our Telegram Channel and LinkedIn Group. Don’t Forget to join our 85k+ ML SubReddit.

    The post How to Build a Prototype X-ray Judgment Tool (Open Source Medical Inference System) Using TorchXRayVision, Gradio, and PyTorch appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleBest Free and Open Source Software: March 2025 Updates
    Next Article This AI Paper Introduces Diversified DPO and ORPO: Post-Training Methods to Boost Output Diversity in Creative Writing with LLMs

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    May 17, 2025
    Machine Learning

    Do Large Language Models Have an English Accent? Evaluating and Improving the Naturalness of Multilingual LLMs

    May 17, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Boldly Redefining Design

    Development

    screenFetch – Bash information tool

    Development

    Modern battlefields have become a breeding ground for experimental AI weaponry

    Artificial Intelligence

    Storm-1977 Hits Education Clouds with AzureChecker, Deploys 200+ Crypto Mining Containers

    Development

    Highlights

    Development

    Researchers from Sakana AI Introduce NAMMs: Optimized Memory Management for Efficient and High-Performance Transformer Models

    December 17, 2024

    Transformers have become the backbone of deep learning models for tasks requiring sequential data processing,…

    Creating a Mega Menu using Acquia Site Studio

    January 21, 2025

    Kodeco Podcast: How to Read Code – Podcast V2, S3 E1 [FREE]

    November 25, 2024

    Dead Rising Deluxe Remaster is coming to Xbox Series X|S and Windows PC — here’s when you can play it

    July 1, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.