CoolFace
Apppublic

pepperumo/MVTec_Website

sourceHugging Facemitupdated 2y agoView on Hugging Face
3likes
app.py760 linesDownload Raw Back to root
1import streamlit as st2import pandas as pd3import torch4 5import plotly.express as px6import plotly.graph_objects as go7import numpy as np8from PIL import Image9import os10import pickle11import joblib12import cv213from data_processing import (14    dataset_statistics, dataset_distribution_chart, load_dataset, 15    plot_bgr_pixel_densities, plot_pair_plots16)17from metrics_calculation import (18        load_evaluation_metrics,19        plot_roc_curve,20        plot_confusion_matrix21    )22 23from prediction import (24    run_inference_autoencoder, load_model_autoencoder, run_inference_knn, load_model_knn25)26 27 28# Overview Page29def overview_page():30    col1, col2, col3 = st.columns([1, 6, 1])31    32    st.title("🚀 Beyond Normal:  Unveiling Image Anomalies with AI")33    st.markdown("---")34 35    try:36        st.image("images/overview_image.png", use_container_width=True, 37                 caption="Normal vs. Anomalous Samples with Segmentation Masks")38    except FileNotFoundError:39        st.error("⚠️ Image file not found. Please check if 'images/overview_image.png' exists.")40 41    # Create three columns for key metrics42    col1, col2, col3 = st.columns(3)43    with col1:44        st.markdown("""45            <div>46                <h2>5,450</h2>47                <p>High-Resolution Images</p>48            </div>49        """, unsafe_allow_html=True)50    with col2:51        st.markdown("""52            <div>53                <h2>15</h2>54                <p>Object Categories</p>55            </div>56        """, unsafe_allow_html=True)57    with col3:58        st.markdown("""59            <div>60                <h2>70+</h2>61                <p>Defect Types</p>62            </div>63        """, unsafe_allow_html=True)64 65    st.markdown("---")66    67    68    st.header("🔍 What is Anomaly Detection?")69    st.write("""70        Imagine a world where machines can **spot defects** in products just like human inspectors—but **faster and with higher accuracy**!  71        This is exactly what **MVTec AD**, a powerful dataset, helps us achieve. It is designed for **automated quality control** in manufacturing by detecting **flaws** such as scratches, dents, and missing parts in different objects and textures.72        73        - 🖼️ **5,450 high-resolution images** across **15 object and texture categories**74        - ✅ **Training set**: Only contains **defect-free** images  75        - 🐞 **Test set**: Includes images with **over 70 different types of defects**  76        - 🎯 **Goal**: Automatically **detect and highlight anomalies** with **pixel-precise segmentation**77    """)78 79    st.subheader("🧐 **How Does Anomaly Detection Work?**")80    st.write("""81        The AI model learns what a **perfect product** looks like by studying thousands of **defect-free images**.  82        When it sees a **new image**, it checks:83        84        1️⃣ **Does this image match what I’ve seen before?**  85        2️⃣ **If not, where is the defect?**  86 87        The result? A **heatmap** showing the suspicious areas, along with a **segmentation mask** to pinpoint the defect.88    """)89 90    st.subheader("✨ **Bringing Anomalies to Light**: Real-World Examples")91    st.write("""92        Below are **three real examples** of AI-powered anomaly detection.         93    """)94 95    # Display anomaly detection images directly without additional data processing96    st.image("images/anomaly_visual_example_1.png", use_container_width=True, caption="Defective Wood - Liquid Stain")97    st.image("images/anomaly_visual_example_2.png", use_container_width=True, caption="Hazelnut - Hole Defect")98    st.image("images/anomaly_visual_example_3.png", use_container_width=True, caption="Leather - Cut Defect")99 100    st.write("""101         **First Column**: 102        - Original object with an anomaly  103             104        **The Heatmap (Second Column)**:  105        - AI scans the object and **highlights unusual areas** in **red/yellow**, indicating anomaly.  106 107        **Segmentation Map (Third Column)**:  108        - Shows the **exact shape** of the detected anomaly, crucial for precise localization.109 110        **Ground Truth (Fourth Column)**:  111        - The manually labeled anomaly **used for AI validation**.112 113        This technology helps manufacturers **automate anomaly detection, reduce waste, and ensure top-tier product quality** at an industrial scale. 🚀  114    """)115 116 117# Dataset Page118def dataset_page():119    st.title("📊 Dataset Analysis & Exploratory Data")120    121    tab1, tab2 = st.tabs(["📈 Dataset Overview", "🎨 Feature Analysis"])122    123    with tab1:124        st.subheader("Dataset Structure")125        complete_df = load_dataset()126        if complete_df is not None:127            st.markdown("""128                <div>129                    <ul>130                        <li>Total Samples: {}</li>131                        <li>Categories: {}</li>132                    </ul>133                </div>134            """.format(135                len(complete_df),136                len(complete_df['category'].unique())137            ), unsafe_allow_html=True)138            139            with st.expander("🔍 View Full Dataset"):140                st.dataframe(complete_df, use_container_width=True)141        else:142            st.error("❌ Error: Dataset could not be loaded.")143    144        145        st.subheader("Statistical Analysis")146        df = dataset_statistics()147        if df is not None:148                        149            dataset_distribution_chart(df)150            151            with st.expander("📊 Detailed Statistics"):152                st.dataframe(df, use_container_width=True)153        else:154            st.error("❌ Error: Statistics could not be computed.")155 156    with tab2:157        st.subheader("Feature Engineering & Analysis")158        159        st.markdown("""160            <div>161                <h3>🔄 Dimensionality Reduction (PCA)</h3>162                <p>Our feature extraction pipeline includes:</p>163                <ul>164                    <li>Image preprocessing and normalization</li>165                    <li>Feature extraction using ResNet50</li>166                    <li>PCA transformation preserving 95% variance</li>167                </ul>168            </div>169        """, unsafe_allow_html=True)170        171        complete_df = load_dataset()172        if complete_df is not None:173            selected_category = st.selectbox("Select a Category", 174                                     complete_df['category'].unique(), index=list(complete_df['category'].unique()).index('wood'))175            176            col1, col2 = st.columns(2)177            with col1:178                plot_bgr_pixel_densities(179                    complete_df[complete_df['category'] == selected_category],180                    pixel_columns=['num_pixels_b', 'num_pixels_g', 'num_pixels_r']181                )182            with col2:183                plot_pair_plots(complete_df[complete_df['category'] == selected_category])184        st.write("""185        **Key Takeaways from Feature Relationships:**186        187        **Strong Correlations:**  188        - The BGR pixel values exhibit **strong linear relationships**, which is expected as they represent color intensity.189        - **Perceived brightness** also shows a linear trend, confirming its dependence on RGB values.190 191        **Separation of Normal vs. Anomalous Data:**  192        - Some categories, like `Hazelnut` and `Tile`, show **clear separation** between normal (blue) and anomalous (red) points, indicating that anomalies have **distinct feature distributions**.193        - Other categories, such as `Screw` and `Transistor`, show **more overlap**, meaning their anomalies are harder to distinguish based only on pixel values.194 195        **Density Distributions:**  196        - Categories like `Carpet` and `Capsule` show **multi-modal distributions**, meaning that anomalies have **different types of defects**.197        - Categories like `Leather` and `Metal Nut` show anomalies with **different brightness levels**, suggesting that brightness-based anomaly detection could be effective.198 199        Overall, this analysis helps us understand which **features are useful for distinguishing anomalies** and which categories might need **additional feature engineering**.200        """)201 202        st.success("✅ Using PCA, BGR pixel distributions, and feature relationships, we ensure that the dataset is **optimized for training accurate anomaly detection models**.")203 204        205 206def synthetic_data_page():207    st.title("🔬 Data Enhancement Techniques")208    209    tab1, tab2 = st.tabs(["🧪 Synthetic Data", "🔄 Data Augmentation"])210    211    with tab1:212        st.header("Synthetic Data Generation")213        214        st.info("""215            🔍 **Synthetic Data** refers to artificially generated images that simulate anomalies 216            by modifying normal samples. Unlike data augmentation, synthetic data aims to create 217            new, realistic defect patterns that weren't present in the original dataset.218        """)219        st.write("""220        #### 🔍 Why Do We Need Synthetic Data?221        The **MVTec Anomaly Detection Dataset** contains **15 object categories**, but for each category:222        223        - The dataset is relatively **small**.224        - There are **far fewer anomaly images** than normal images.225        - Splitting test data for validation would leave even **less data** to train the model.226 227        To solve this problem, **we create additional "fake" anomaly images** to train the model better.  228        Instead of taking images of real defective objects (which are limited), we **manipulate normal images** by adding synthetic defects, such as **twisting, distorting, or overlaying textures**.229        230        """)231        st.image(232            "images/synthetic_example.png",233            caption="Synthetic Anomaly"234        )235        col1, col2 = st.columns(2)236        with col1:237            st.markdown("""238                <div>239                    <h4>Synthetic Anomaly Generation</h4>240                    <ol>241                        <li><strong>Base Selection:</strong> Choose a normal image as base</li>242                        <li><strong>Defect Injection:</strong> Apply artificial defects:243                            <ul>244                                <li>Scratch patterns</li>245                                <li>Surface contamination</li>246                                <li>Structural deformations</li>247                                <li>Missing components</li>248                            </ul>249                        </li>250                        <li><strong>Validation:</strong> Ensure defect realism</li>251                        <li><strong>Integration:</strong> Add to validation dataset</li>252                    </ol>253                </div>254            """, unsafe_allow_html=True)255            256            st.success("""257                ✨ **Benefits of Synthetic Data**258                - Creates diverse anomaly patterns259                - Controls defect characteristics260                - Balances class distribution261                - Reduces data collection costs262            """)263        264        with col2:265                        266            st.warning("""267                ⚠️ **Important Considerations**268                - Synthetic defects must be realistic269                - Validation against real defects is crucial270                - Balance between synthetic and real data needed271            """)272    273    with tab2:274        st.header("Data Augmentation Techniques")275        276        st.info("""277            🔄 **Data Augmentation** applies label-preserving transformations to existing images278            to increase dataset variety and prevent overfitting. Unlike synthetic data, augmentation279            doesn't create new defect types but enhances model robustness through variations.280        """)281 282        st.write("""283        **Augmented data** is different from synthetic data. Instead of creating **new artificial images**, we **modify existing images** by applying **small transformations** like flipping, rotating, and resizing.  284 285        #### 🔍 Why Do We Need Data Augmentation?286        Even with synthetic data, **our dataset is still small** compared to what is needed for deep learning.  287        If we train a model on a **limited number of images**, the model might **memorize** the training data instead of **learning general patterns**. This is called **overfitting**.288 289        **To prevent overfitting, we increase the dataset size by applying transformations to images.**  290        """)291        292        col1, col2, col3 = st.columns(3)293        with col1:294            st.markdown("""295            <div>296                <h5>🔲 Basic Transformations</h5>297                <ul>298                <li><strong>Resizing</strong>: Fixed 224×224 pixels</li>299                <li><strong>Horizontal Flip</strong>: 50% probability</li>300                <li><strong>Impact</strong>: Standardized input size</li>301                </ul>302            </div>303            """, unsafe_allow_html=True)304        with col2:305            st.markdown("""306            <div>307                <h5>🎨 Geometric Operations</h5>308                <ul>309                <li><strong>Rotation</strong>: 75% prob. (-90°, 90°, 180°)</li>310                <li><strong>Scaling & Translation</strong>: 75% probability</li>311                <li><strong>Impact</strong>: Position invariance</li>312                </ul>313            </div>314            """, unsafe_allow_html=True)315        with col3:316            st.markdown("""317            <div>318                <h5>🔄 Advanced Processing</h5>319                <ul>320                <li><strong>Gaussian Blur</strong>: Kernel size 3</li>321                <li><strong>Sigma Range</strong>: 0.01-0.05</li>322                <li><strong>Final Step</strong>: Tensor conversion</li>323                </ul>324            </div>325            """, unsafe_allow_html=True)326        327        st.markdown("### 📈 Augmentation examples")328        col1, col2 = st.columns(2)329        with col1:330            st.image(331                "images/augmented_example.png",332                caption="Augmented Images Examples",333                use_container_width=True334            )335        with col2:336            st.image(337                "images/original_example.png",338                caption="Original Images Examples",339                use_container_width=True340            )341        342        st.success("""343            ✨ **Benefits of Data Augmentation**344            - Prevents overfitting345            - Improves model generalization346            - Increases effective dataset size347            - Maintains label validity348        """)349 350def resnet50_page():351    st.title("🔍 ResNet50 Feature Extraction")352    col1, col2= st.columns([3, 2])353    with col1:354        st.markdown("""355        ### Why Use a Pretrained Model (Transfer Learning)? 🧠356        Instead of starting from scratch, we take advantage of **ResNet50**, 357        a popular neural network that has already been trained on a large image dataset (ImageNet). 358        Because ResNet50 has “seen” many kinds of shapes, objects, and patterns,359        it has learned to recognize important features in images.360 361        By using these **pretrained features**, we:362        1. ⏱️ Save time and resources (no need to train a big model from zero).363        2. 🖼️ Gain access to a representation that already captures key visual patterns.364        3. 🎯 Focus on fine-tuning the model for our specific task (anomaly detection).365        """)366 367    with col2:368        st.image("images/resnet50.png", caption="Resnet50 Latent features extraction", use_container_width=True)369 370    st.markdown("""371        372        ### How We Extract Features from ResNet50373        We focus on two parts (or “blocks”) of ResNet50 and gather their outputs:374        - **Block 1**: Produces 512 features.375        - **Block 2**: Produces 1024 features.376 377        We then **combine** (concatenate) these for a total of **(512 + 1024) = 1536** features. 378        These numbers come from the internal layers of ResNet50.379 380        Essentially, these **1536 features** act like a summary of the image’s most important elements. 📝381 382        """)383    st.image("images/internal_features.png", caption="ResNet50 Block 1 & 2, random internal features", use_container_width=True)384    385def models_page():386    st.title("🤖 Anomaly Detection Models")387 388    tab1, tab2 = st.tabs(["KNN", "Autoencoder"])389    390    with tab1:391        st.header("KNN for Anomaly Detection") 392        col1, col2 = st.columns([2.5,2])393        with col1:394            st.markdown("""395        KNN (K-Nearest Neighbors) is a simple method that checks how "close" a new sample is 396        to existing samples. Here's the idea:397        1. We first collect "normal" images and extract their 1536 features. 398           We call this collection our **memory bank** of normal features. 🏦399        2. When a **test** image comes in:400           - ⚙️ We **extract** its 1536 features with the exact same process (ResNet blocks).401           - 📏 We measure its **distance** to each normal feature vector in the memory bank.402           - 🔎 We pick the **1 closest** neighbor (because k=1) and calculate the **average distance**.403             - If this average distance is **small**, it is likely "normal." ✅404             - If this average distance is **large**, it might be "anomalous" or unusual. 🐞405        """)406            st.image("images/k-nearest-neighbors-algorithm.png", caption="Visualizing the K-Nearest Neighbors approach")407        with col2:408            st.image("images/KNN_Pipeline.png", caption="KNN Anomaly Detection Pipeline")409 410  411 412    with tab2:413        st.header("Autoencoder for Anomaly Detection")414        col1, col2 = st.columns([2.5,2])415        with col1: 416            st.write("""417            Deep learning models have demonstrated remarkable performance in anomaly detection tasks, 418            particularly in complex scenarios where traditional methods often struggle. 419            These models can automatically learn intricate patterns and features from data, 420            making them highly effective at identifying subtle anomalies.421            """)422 423            st.write("""424            ### What is an autoencoder?425 426            An autoencoder is a specialized type of neural network designed to compress and reconstruct input images. 427            When applied to anomaly detection, the model is trained exclusively on normal images to learn the typical characteristics of the dataset.428            """)429 430            st.write("""431            ### Anomaly Detection Workflow432 433            #### 1. Feature Extraction434            - Collect a set of normal images.435            - Extract 1,536 features from each image using a **ResNet50** model.436 437            #### 2. Training Process438            - Train the autoencoder exclusively on normal data.439            - The autoencoder learns to efficiently encode and decode normal patterns.440            - The model optimizes its reconstruction error using normal samples.441 442            #### 3. Anomaly Detection443            - A new test image is passed through the trained autoencoder.444            - The reconstructed output is compared to the original input.445            - A high reconstruction error suggests an anomaly.446            - A low reconstruction error indicates that the sample is likely normal.447            """)448 449        st.success("""450        ## Key Advantages451        - **Fully Unsupervised Learning** – No need for labeled anomaly data.452        - **Ability to Capture Complex Normal Patterns** – The model generalizes well to unseen normal variations.453        - **Effective for High-Dimensional Image Data** – Works well with large and detailed datasets.454        """)455        st.warning("""456        ## Limitations457        - **Computationally Intensive Training** – Training deep autoencoders requires significant computational resources.458        - **Performance Sensitivity to Model Architecture** – The effectiveness depends heavily on model design.459        - **Difficulty Detecting Subtle Anomalies** – If anomalies resemble normal patterns closely, they may be overlooked.460        """)461 462        with col2:463            st.image("images/Autoencoder_Pipeline.png", caption="Autoencoder Anomaly Detection Pipeline", use_container_width=True)464            st.image("images/encoder_decoder.png", caption="Autoencoder structure", use_container_width=True)465 466def analysis_page():467    st.title("📊 Model Performance Analysis")468    469    # Move category selection outside of tabs470    selected_category = st.selectbox(471        "Select Category",472        ["bottle", "cable", "capsule", "carpet", "grid", 473            "hazelnut", "leather", "metal_nut", "pill", "screw",474            "tile", "toothbrush", "transistor", "wood", "zipper"],475        index=1  # Default to 'cable'476    )477    478    # Create two columns479    col1, col2 = st.columns(2)480    481    with col1:482        st.subheader("KNN Model")483        try:484            confusion_matrices, roc_curves, auc_scores, f1_scores = load_evaluation_metrics('models/evaluation_metrics_knn.pkl')485            486            # Display ROC curve with unique key487            roc_fig = plot_roc_curve(selected_category, roc_curves, auc_scores)488            st.plotly_chart(roc_fig, use_container_width=True, key="knn_roc")489 490            # Display confusion matrix with unique key491            cm_fig = plot_confusion_matrix(selected_category, confusion_matrices, f1_scores)492            st.plotly_chart(cm_fig, use_container_width=True, key="knn_cm")493            494        except FileNotFoundError:495            st.error("KNN evaluation metrics file not found. Please run model evaluation first.") 496        except Exception as e:497            st.error(f"Error loading KNN metrics: {str(e)}")498 499    with col2:500        st.subheader("Autoencoder Model")501        try:502            confusion_matrices, roc_curves, auc_scores, f1_scores = load_evaluation_metrics('models/evaluation_metrics_autoencoder.pkl')503            504            # Display ROC curve with unique key505            roc_fig = plot_roc_curve(selected_category, roc_curves, auc_scores)506            st.plotly_chart(roc_fig, use_container_width=True, key="ae_roc")507 508            # Display confusion matrix with unique key509            cm_fig = plot_confusion_matrix(selected_category, confusion_matrices, f1_scores)510            st.plotly_chart(cm_fig, use_container_width=True, key="ae_cm")511            512        except FileNotFoundError:513            st.error("Autoencoder evaluation metrics file not found. Please run model evaluation first.")514        except Exception as e:515            st.error(f"Error loading Autoencoder metrics: {e}")516 517 518 519def prediction_page():520    """521    Streamlit page to view anomaly detection images.522    """523    st.title("🔍 Anomaly Detection - Image Viewer")524 525    st.info("Select a category and image to view the anomaly detection result.")526 527    # Select a category528    selected_category = st.selectbox(529        "Select a Category",530        ["bottle", "cable", "capsule", "carpet", "grid", 531         "hazelnut", "leather", "metal_nut", "pill", "screw",532         "tile", "toothbrush", "transistor", "wood", "zipper"],533        key="shared_category"  # Unique key for each selectbox534    )535 536    # List available images in the selected category537    category_dir_knn = os.path.join("images/Dataset_knn", selected_category)538    category_dir_autoencoder = os.path.join("images/Dataset_autoencoder", selected_category)539 540    available_images_knn = []541    if os.path.exists(category_dir_knn):542        available_images_knn = [f for f in os.listdir(category_dir_knn) if os.path.isfile(os.path.join(category_dir_knn, f))]543    544    available_images_autoencoder = []545    if os.path.exists(category_dir_autoencoder):546        available_images_autoencoder = [f for f in os.listdir(category_dir_autoencoder) if os.path.isfile(os.path.join(category_dir_autoencoder, f))]547 548    # Find common images549    available_images = list(set(available_images_knn) & set(available_images_autoencoder))550 551    selected_image = st.selectbox(552        "Select an Image", 553        available_images,554        key="shared_image"  # Unique key for each selectbox555    )556 557    run_prediction = st.button("Run Prediction")558 559    tab1, tab2 = st.tabs(["KNN", "Autoencoder"])560 561    with tab1:562        st.subheader("KNN Model")563        if run_prediction:564            display_image("knn", selected_category, selected_image)565 566    with tab2:567        st.subheader("Autoencoder Model")568        if run_prediction:569            display_image("autoencoder", selected_category, selected_image)570 571def display_image(model_type, selected_category, selected_image):572    """573    Helper function to display a single image based on the selected model type.574    """575    if selected_image:576        # Construct file paths577        image_path = os.path.join(f"images/Dataset_{model_type}", selected_category, selected_image)578 579        # Display image580        if os.path.exists(image_path):581            try:582                image = Image.open(image_path)583                st.image(image, use_container_width=True)584            except Exception as e:585                st.error(f"Error displaying {model_type} image: {e}")586        else:587            st.error(f"{model_type} Image not found: {image_path}")588    589    st.markdown("""590    ### Explanation of the displayed image:591    592    1️⃣ **Top Left: Original Image**593    - This is the raw image from the dataset.594    - The object is analyzed to detect potential anomalies.595    596    2️⃣ **Top Right: Heatmap**597    - The heatmap represents the anomaly score distribution.598    - Color Legend:599        - 🔴 Red/Yellow: High anomaly score (defective region).600        - 🔵 Blue: Normal areas with low anomaly probability.601    - The defect region is highlighted based on the anomaly model’s prediction.602    603    3️⃣ **Bottom Left: Segmentation Map**604    - This is a binary mask that highlights the detected defect areas.605    - White pixels represent anomalous regions identified by the model.606    - It is created by thresholding the heatmap to localize defects.607    608    4️⃣ **Bottom Right: Ground Truth**609    - The ground truth mask is a manually labeled reference.610    - It defines the true defective areas for validation.611    - The segmentation map should ideally match this mask for accurate detection.612    """)613 614 615 616def conclusion_and_improvements_page():617    st.title("🏁 Conclusion and Future Improvements")618 619    st.write("""620    ## Conclusion621 622    Throughout the project, several Machine Learning and Deep Learning models have been applied to the available image data. We compared different models and approaches in data preparation to optimize anomaly detection performance.623 624    The evaluation shows that the Convolutional Autoencoder and the KNN approach significantly outperform other models, and both yield better results using the deep feature extraction approach.625 626    ### Key Takeaways627 628    - **Deep Feature Extraction**: Significantly outperforms manual extracted features, as seen in the consistently better performance of ResNet50-based methods.629    - **ResNet50 Block Performance**: Two evaluated deep feature extraction approaches, one using ResNet50 blocks 1 and 2, the other using block 3, both seem similarly suitable on average over all categories. However, within single categories, one often showed significantly better performance than the other.630    - **KNN Approach**: Leverages memory-based similarity comparisons, providing a robust alternative to parametric models.631    - **Autoencoder Approach**: Deep learning using an autoencoder provides strong reconstruction-based anomaly detection, ensuring comprehensive feature learning.632    - **Synthetic Validation Data**: Introduced diversity and improved cross-validation but also posed challenges, as some anomalies may not perfectly mimic real-world defects.633 634    ## Future Improvements635 636    - **Data Augmentation Refinement**: Exploring more advanced augmentation techniques, such as generative models (e.g., GANs), could enhance training diversity.637    - **Model Ensembling**: Combining multiple anomaly detection models could improve robustness and generalization.638    - **Hyperparameter Optimization**: Fine-tuning model hyperparameters further, using techniques like Bayesian optimization, could boost performance.639    - **Alternative Architectures**: Exploring transformer-based architectures or vision encoders like ViTs for anomaly detection could yield even better results.640    - **Better Synthetic Data**: Refining the process of synthetic anomaly generation to better align with real-world defects.641 642    Overall, the introduced approaches provide a solid foundation for industrial anomaly detection tasks. Further optimizations and explorations in feature extraction and model selection could push performance even higher in future studies.643    """)644 645# Bibliography Page646def bibliography_page():647    st.title("📚 Bibliography & References")648    649    st.markdown("""650        ### Core Papers & Methods651        652        1. Liu, J., Xie, G., Wang, J., Li, S., Wang, C., Zheng, F., & Jin, Y. (2023). 653        _Deep Industrial Image Anomaly Detection: A Survey_. Springer Nature.  654        [arXiv:2301.11514](https://arxiv.org/abs/2301.11514)655 656        2. Yang, J., Shi, Y., & Qi, Z. (2020).657        _DFR: Deep Feature Reconstruction for Unsupervised Anomaly Segmentation_.  658        [arXiv:2012.07122](https://arxiv.org/abs/2012.07122)659 660        3. Bühler, J., Fehrenbach, J., Steinmann, L., Nauck, C., & Koulakis, M. (2024).661        _Domain-independent detection of known anomalies_. Karlsruhe Institute of Technology (KIT) & preML GmbH.  662        [arXiv:2407.02910](https://arxiv.org/abs/2407.02910)663 664        4. Heckler, L., & König, R. (2024).665        _Feature Selection for Unsupervised Anomaly Detection and Localization Using Synthetic Defects_.666        MVTec Software GmbH & Technical University of Munich.667        In Proceedings of the 19th International Joint Conference on Computer Vision, Imaging and Computer Graphics Theory and Applications (VISIGRAPP 2024), 154-165.  668        [DOI: 10.5220/0012385500003660](https://doi.org/10.5220/0012385500003660)669 670        5. Rippel, O., Mertens, P., & Merhof, D. (2020).671        _Modeling the Distribution of Normal Data in Pre-Trained Deep Features for Anomaly Detection_.672        RWTH Aachen University.  673        [arXiv:2005.14140](https://arxiv.org/abs/2005.14140)674 675        6. Bergmann, P., Fauser, M., Sattlegger, D., & Steger, C. (2019).676        _MVTec AD – A Comprehensive Real-World Dataset for Unsupervised Anomaly Detection_.677        MVTec Software GmbH.  678        [MVTec AD Dataset](https://www.mvtec.com/company/research/datasets/mvtec-ad)679 680        7. Roth, K., Pemula, L., Zepeda, J., Schölkopf, B., Brox, T., & Gehler, P. (2022).681        _Towards Total Recall in Industrial Anomaly Detection_.682        University of Tübingen & Amazon AWS.  683        [arXiv:2106.08265](https://arxiv.org/abs/2106.08265)684 685        8. Zheng, Y., Wang, X., Qi, Y., Li, W., & Wu, L. (2022).686        _Benchmarking Unsupervised Anomaly Detection and Localization_.687        University of Chinese Academy of Sciences, SenseTime Research, & Tsinghua University.  688        [arXiv:2205.14852](https://arxiv.org/abs/2205.14852)689    """)690 691def main():692    with st.sidebar:693        st.image("images/logo.png", width=100)  # Add your logo here694        st.title("Navigation")695        696        697        selection = st.radio(698            "Select a Section",699            ["Overview", 700             "Dataset & EDM",701             "Synthetic Data & Augmentation",702             "Transfer Learning - Resnet50",703             "Models",704             "Analysis",705             "Prediction",706             "Conclusion and Improvements",707             "Bibliography"],708            format_func=lambda x: f" {x}"709        )710        st.markdown("---")711        st.markdown("""712            <div style='text-align: center; color: #666;'>713            714            <div style='margin: 10px 0;'>715            This app is maintained by:<br>716            <a href="https://www.linkedin.com/in/giuseppe-rumore-b2599961" target="_blank">Giuseppe Rumore</a> |717            <a href="https://www.linkedin.com/in/micaela-w%C3%BCnsche-9baaa710b/" target="_blank">Micaela Wünsche</a> |718            <a href="https://www.linkedin.com/in/majid-jafari-62909071/" target="_blank">Majid Jafari</a>719            </div>720            </a>721            <img src="https://content.linkedin.com/content/dam/me/business/en-us/amp/brand-site/v2/bg/LI-Logo.svg.original.svg" 722             width="80" 723             alt="LinkedIn"724             style="margin-top: 10px;">725            </a>726            <br>727            <a href="https://github.com/pepperumo/MVTEC-anomaly-detection" target="_blank">728            <img src="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"729             width="40"730             alt="GitHub"731             style="margin-top: 10px; border-radius: 50%;">732            </a>733            <div style='text-align: center; color: #666;'>734            <small>Version 1.0.0</small><br>735            <small>© 2025 MVTec Anomaly Detection</small><br>736            </div>737        """, unsafe_allow_html=True)738        739    if selection == "Overview":740        overview_page()741    elif selection == "Dataset & EDM":742        dataset_page()743    elif selection == "Synthetic Data & Augmentation":744        synthetic_data_page()745    elif selection == "Transfer Learning - Resnet50":746        resnet50_page()747    elif selection == "Models":748        models_page()749    elif selection == "Analysis":750        analysis_page()751    elif selection == "Prediction":752        prediction_page()753    elif selection == "Conclusion and Improvements":754        conclusion_and_improvements_page()755    elif selection == "Bibliography":756        bibliography_page()757 758if __name__ == "__main__":759    main()760