import streamlit as st import numpy as np import cv2 from PIL import Image import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd from datetime import datetime import json import os from collections import Counter import base64 from io import BytesIO # Page configuration st.set_page_config( page_title="CompositeDefect AI - NDT Analysis System", page_icon="๐Ÿ”ฌ", layout="wide", initial_sidebar_state="expanded" ) # Custom CSS for black/white/grey/blue/purple theme st.markdown(""" """, unsafe_allow_html=True) # Initialize session state if 'analysis_history' not in st.session_state: st.session_state.analysis_history = [] if 'current_analysis' not in st.session_state: st.session_state.current_analysis = None # Sidebar configuration with st.sidebar: st.markdown("""

๐Ÿ”ฌ CompositeDefect AI

NDT Analysis System

""", unsafe_allow_html=True) st.markdown("---") # NDT Method Selection st.markdown("### ๐Ÿ“ก NDT Method") ndt_method = st.selectbox( "Select Testing Method", [ "Visual Testing (VT)", "Ultrasonic Testing (UT)", "Magnetic Particle Testing (MPT)", "Radiographic Testing (RT)", "Liquid Penetrant Testing (LPT)", "Eddy Current Testing (ECT)", "Thermal/Infrared Testing (IRT)", "Microwave NDT", "Vibration Analysis" ], help="Choose the non-destructive testing method used" ) st.markdown("---") # Material Selection st.markdown("### ๐Ÿงช Material Type") material_type = st.selectbox( "Select Composite Material", [ "Carbon Fibre Reinforced Polymer (CFRP)", "Glass Fibre Reinforced Polymer (GFRP)", "Aramid Fibre Reinforced Polymer (AFRP)", "Hybrid Composite" ], help="Select the composite material being analyzed" ) st.markdown("---") # Analysis Parameters st.markdown("### โš™๏ธ Analysis Parameters") sensitivity = st.slider( "Detection Sensitivity", min_value=0.1, max_value=1.0, value=0.75, step=0.05, help="Adjust the sensitivity of defect detection" ) confidence_threshold = st.slider( "Confidence Threshold", min_value=0.5, max_value=0.95, value=0.70, step=0.05, help="Minimum confidence level for defect classification" ) st.markdown("---") # Defect Types to Detect st.markdown("### ๐ŸŽฏ Target Defects") detect_delamination = st.checkbox("Delamination", value=True) detect_cracks = st.checkbox("Cracks", value=True) detect_voids = st.checkbox("Voids", value=True) detect_fibre_misalignment = st.checkbox("Fibre Misalignment", value=True) detect_resin_issues = st.checkbox("Resin Rich/Starved Areas", value=True) st.markdown("---") # About section with st.expander("โ„น๏ธ About"): st.markdown(""" **CompositeDefect AI** uses advanced machine learning algorithms to detect and analyze defects in composite materials. **Supported NDT Methods:** - Visual Testing - Ultrasonic Testing - Radiography - Thermal/Infrared - And more... **Version:** 2.0.0 """) # Main content area col_header1, col_header2 = st.columns([3, 1]) with col_header1: st.title("๐Ÿ”ฌ CompositeDefect AI") st.markdown("""

Advanced Machine Learning-Based Defect Detection & Analysis for Composite Materials

""", unsafe_allow_html=True) with col_header2: st.markdown(f"""
{ndt_method.split('(')[0].strip()}
{material_type.split('(')[0].strip()}
""", unsafe_allow_html=True) st.markdown("---") # Create tabs for different sections tab_upload, tab_analysis, tab_results, tab_history = st.tabs([ "๐Ÿ“ค Upload & Analyze", "๐Ÿ” Detection Results", "๐Ÿ“Š Detailed Analysis", "๐Ÿ“œ History" ]) # Simulated ML Model for Defect Detection class DefectDetectionModel: def __init__(self): self.defect_types = { 'delamination': {'color': (255, 0, 0), 'severity_weights': [0.3, 0.5, 0.7, 0.9]}, 'crack': {'color': (0, 255, 0), 'severity_weights': [0.4, 0.6, 0.8, 1.0]}, 'void': {'color': (0, 0, 255), 'severity_weights': [0.2, 0.4, 0.6, 0.8]}, 'fibre_misalignment': {'color': (255, 255, 0), 'severity_weights': [0.2, 0.3, 0.5, 0.7]}, 'resin_rich': {'color': (255, 0, 255), 'severity_weights': [0.1, 0.2, 0.4, 0.6]}, 'resin_starved': {'color': (0, 255, 255), 'severity_weights': [0.2, 0.4, 0.6, 0.8]} } def preprocess_image(self, image, ndt_method): """Preprocess image based on NDT method""" img_array = np.array(image) if ndt_method == "Ultrasonic Testing (UT)": # Enhance contrast for ultrasonic C-scan if len(img_array.shape) == 3: gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY) else: gray = img_array enhanced = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8)).apply(gray) return cv2.cvtColor(enhanced, cv2.COLOR_GRAY2RGB) elif ndt_method == "Thermal/Infrared Testing (IRT)": # Apply colormap for thermal images if len(img_array.shape) == 3: gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY) else: gray = img_array thermal = cv2.applyColorMap(gray, cv2.COLORMAP_JET) return cv2.cvtColor(thermal, cv2.COLOR_BGR2RGB) elif ndt_method == "Radiographic Testing (RT)": # Enhance radiographic images if len(img_array.shape) == 3: gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY) else: gray = img_array enhanced = cv2.equalizeHist(gray) return cv2.cvtColor(enhanced, cv2.COLOR_GRAY2RGB) else: return img_array def detect_defects(self, image, ndt_method, material_type, sensitivity, confidence_threshold, active_defects): """Simulate defect detection with ML model""" np.random.seed(42) img_array = np.array(image) height, width = img_array.shape[:2] detected_defects = [] annotated_image = img_array.copy() # Simulate defect detection based on image characteristics for defect_type, config in self.defect_types.items(): if defect_type not in active_defects: continue # Simulate detection probability based on sensitivity num_defects = np.random.poisson(2 * sensitivity) for i in range(num_defects): # Random position x = np.random.randint(50, width - 50) y = np.random.randint(50, height - 50) # Random size based on defect type if defect_type == 'delamination': w, h = np.random.randint(30, 100), np.random.randint(30, 100) elif defect_type == 'crack': w, h = np.random.randint(5, 15), np.random.randint(40, 150) elif defect_type == 'void': w, h = np.random.randint(10, 40), np.random.randint(10, 40) else: w, h = np.random.randint(20, 80), np.random.randint(20, 80) # Calculate confidence confidence = np.random.uniform(confidence_threshold, 0.98) # Determine severity severity_idx = np.random.choice(4, p=config['severity_weights']) severity_levels = ['Low', 'Medium', 'High', 'Critical'] severity = severity_levels[severity_idx] # Calculate area area_mm2 = (w * h) * 0.01 # Simulated conversion to mmยฒ defect_info = { 'type': defect_type.replace('_', ' ').title(), 'confidence': confidence, 'severity': severity, 'position': (x, y, w, h), 'area_mm2': round(area_mm2, 2), 'ndt_method': ndt_method } detected_defects.append(defect_info) # Draw bounding box on annotated image color = config['color'] cv2.rectangle(annotated_image, (x, y), (x+w, y+h), color, 2) cv2.putText(annotated_image, f"{defect_type[:3].upper()} {confidence:.2f}", (x, y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1) # Sort by confidence detected_defects.sort(key=lambda x: x['confidence'], reverse=True) return detected_defects, Image.fromarray(annotated_image) def analyze_defect_characteristics(self, defects): """Analyze defect characteristics for reporting""" if not defects: return {} analysis = { 'total_defects': len(defects), 'defect_types': Counter([d['type'] for d in defects]), 'severity_distribution': Counter([d['severity'] for d in defects]), 'avg_confidence': np.mean([d['confidence'] for d in defects]), 'critical_defects': len([d for d in defects if d['severity'] == 'Critical']), 'high_defects': len([d for d in defects if d['severity'] == 'High']), 'total_area': sum([d['area_mm2'] for d in defects]) } return analysis # Initialize model model = DefectDetectionModel() # Tab 1: Upload & Analyze with tab_upload: st.markdown("""

๐Ÿ“ค Upload NDT Test Results

Upload your NDT inspection images for AI-powered defect detection and analysis. Supports JPG, PNG, TIFF, and BMP formats.

""", unsafe_allow_html=True) col1, col2 = st.columns([1, 1]) with col1: uploaded_file = st.file_uploader( "Choose an image file", type=['jpg', 'jpeg', 'png', 'tiff', 'bmp'], help="Upload NDT inspection image" ) if uploaded_file is not None: image = Image.open(uploaded_file) st.session_state.uploaded_image = image st.markdown("""

๐Ÿ“‹ Image Information

""", unsafe_allow_html=True) info_col1, info_col2, info_col3 = st.columns(3) with info_col1: st.metric("Width", f"{image.size[0]} px") with info_col2: st.metric("Height", f"{image.size[1]} px") with info_col3: st.metric("Mode", image.mode) with col2: if uploaded_file is not None: st.markdown("""

๐Ÿ–ผ๏ธ Preview

""", unsafe_allow_html=True) st.image(image, use_container_width=True) if uploaded_file is not None: st.markdown("---") if st.button("๐Ÿ” Start AI Analysis", use_container_width=True): with st.spinner("๐Ÿค– AI Model is analyzing the image..."): # Progress bar progress_bar = st.progress(0) # Simulate processing steps steps = [ "Preprocessing image...", "Applying NDT-specific filters...", "Running defect detection...", "Classifying defect types...", "Generating analysis report..." ] for i, step in enumerate(steps): st.text(f"โณ {step}") progress_bar.progress((i + 1) / len(steps)) # Prepare active defects list active_defects = [] if detect_delamination: active_defects.append('delamination') if detect_cracks: active_defects.append('crack') if detect_voids: active_defects.append('void') if detect_fibre_misalignment: active_defects.append('fibre_misalignment') if detect_resin_issues: active_defects.append('resin_rich') active_defects.append('resin_starved') # Preprocess image preprocessed = model.preprocess_image(image, ndt_method) # Detect defects defects, annotated_img = model.detect_defects( preprocessed, ndt_method, material_type, sensitivity, confidence_threshold, active_defects ) # Analyze characteristics analysis = model.analyze_defect_characteristics(defects) # Store results st.session_state.current_analysis = { 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'ndt_method': ndt_method, 'material_type': material_type, 'original_image': image, 'annotated_image': annotated_img, 'preprocessed_image': Image.fromarray(preprocessed), 'defects': defects, 'analysis': analysis, 'parameters': { 'sensitivity': sensitivity, 'confidence_threshold': confidence_threshold } } st.session_state.analysis_history.append(st.session_state.current_analysis) progress_bar.empty() st.success("โœ… Analysis Complete! Navigate to 'Detection Results' tab to view findings.") st.balloons() # Tab 2: Detection Results with tab_analysis: if st.session_state.current_analysis is None: st.info("๐Ÿ‘† Please upload and analyze an image first to see detection results.") else: analysis_data = st.session_state.current_analysis # Summary metrics st.markdown("""

๐Ÿ“Š Detection Summary

""", unsafe_allow_html=True) metric_cols = st.columns(4) with metric_cols[0]: st.markdown(f"""
{analysis_data['analysis'].get('total_defects', 0)}
Total Defects
""", unsafe_allow_html=True) with metric_cols[1]: critical = analysis_data['analysis'].get('critical_defects', 0) severity_class = "severity-critical" if critical > 0 else "severity-low" st.markdown(f"""
{critical}
Critical Defects
""", unsafe_allow_html=True) with metric_cols[2]: avg_conf = analysis_data['analysis'].get('avg_confidence', 0) * 100 st.markdown(f"""
{avg_conf:.1f}%
Avg Confidence
""", unsafe_allow_html=True) with metric_cols[3]: total_area = analysis_data['analysis'].get('total_area', 0) st.markdown(f"""
{total_area:.2f}
Total Area (mmยฒ)
""", unsafe_allow_html=True) st.markdown("---") # Image comparison st.markdown("""

๐Ÿ–ผ๏ธ Image Analysis

""", unsafe_allow_html=True) img_col1, img_col2, img_col3 = st.columns(3) with img_col1: st.markdown("

Original Image

", unsafe_allow_html=True) st.image(analysis_data['original_image'], use_container_width=True) with img_col2: st.markdown("

Preprocessed

", unsafe_allow_html=True) st.image(analysis_data['preprocessed_image'], use_container_width=True) with img_col3: st.markdown("

Detected Defects

", unsafe_allow_html=True) st.image(analysis_data['annotated_image'], use_container_width=True) st.markdown("---") # Defect list st.markdown("""

๐Ÿ” Detected Defects

""", unsafe_allow_html=True) if analysis_data['defects']: for i, defect in enumerate(analysis_data['defects'][:10], 1): severity_colors = { 'Low': '#22c55e', 'Medium': '#eab308', 'High': '#f97316', 'Critical': '#ef4444' } color = severity_colors.get(defect['severity'], '#b0b0b0') with st.expander(f"Defect #{i}: {defect['type']} - Confidence: {defect['confidence']:.2%}"): col_d1, col_d2, col_d3 = st.columns(3) with col_d1: st.markdown(f"**Type:** {defect['type']}") st.markdown(f"**Confidence:** {defect['confidence']:.2%}") with col_d2: st.markdown(f"**Severity:** {defect['severity']}", unsafe_allow_html=True) st.markdown(f"**Area:** {defect['area_mm2']} mmยฒ") with col_d3: x, y, w, h = defect['position'] st.markdown(f"**Position:** ({x}, {y})") st.markdown(f"**Size:** {w}ร—{h} px") else: st.success("โœ… No defects detected in this image!") # Tab 3: Detailed Analysis with tab_results: if st.session_state.current_analysis is None: st.info("๐Ÿ‘† Please upload and analyze an image first to see detailed analysis.") else: analysis_data = st.session_state.current_analysis # Create visualizations st.markdown("""

๐Ÿ“ˆ Defect Distribution Analysis

""", unsafe_allow_html=True) viz_col1, viz_col2 = st.columns(2) with viz_col1: # Defect types pie chart defect_types = analysis_data['analysis'].get('defect_types', {}) if defect_types: fig_types = px.pie( values=list(defect_types.values()), names=list(defect_types.keys()), title="Defect Types Distribution", color_discrete_sequence=['#3b82f6', '#8b5cf6', '#06b6d4', '#ec4899', '#f97316', '#22c55e'] ) fig_types.update_layout( paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='white' ) st.plotly_chart(fig_types, use_container_width=True) with viz_col2: # Severity distribution bar chart severity_dist = analysis_data['analysis'].get('severity_distribution', {}) if severity_dist: severity_order = ['Low', 'Medium', 'High', 'Critical'] severity_colors = {'Low': '#22c55e', 'Medium': '#eab308', 'High': '#f97316', 'Critical': '#ef4444'} fig_severity = go.Figure() for sev in severity_order: if sev in severity_dist: fig_severity.add_trace(go.Bar( x=[sev], y=[severity_dist[sev]], name=sev, marker_color=severity_colors[sev] )) fig_severity.update_layout( title="Severity Distribution", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='white', showlegend=False, xaxis_title="Severity Level", yaxis_title="Count" ) st.plotly_chart(fig_severity, use_container_width=True) st.markdown("---") # Confidence distribution st.markdown("""

๐ŸŽฏ Confidence Analysis

""", unsafe_allow_html=True) if analysis_data['defects']: confidences = [d['confidence'] for d in analysis_data['defects']] fig_conf = go.Figure() fig_conf.add_trace(go.Histogram( x=confidences, nbinsx=10, marker_color='#3b82f6', opacity=0.8 )) fig_conf.update_layout( title="Confidence Score Distribution", xaxis_title="Confidence Score", yaxis_title="Frequency", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='white' ) st.plotly_chart(fig_conf, use_container_width=True) st.markdown("---") # Generate report st.markdown("""

๐Ÿ“„ Analysis Report

""", unsafe_allow_html=True) report_col1, report_col2 = st.columns(2) with report_col1: st.markdown("""

Test Information

""", unsafe_allow_html=True) report_data = { 'Parameter': ['Date & Time', 'NDT Method', 'Material Type', 'Sensitivity', 'Confidence Threshold', 'Total Defects', 'Critical Defects'], 'Value': [ analysis_data['timestamp'], analysis_data['ndt_method'], analysis_data['material_type'], f"{analysis_data['parameters']['sensitivity']:.2f}", f"{analysis_data['parameters']['confidence_threshold']:.2f}", str(analysis_data['analysis'].get('total_defects', 0)), str(analysis_data['analysis'].get('critical_defects', 0)) ] } df_report = pd.DataFrame(report_data) st.dataframe(df_report, use_container_width=True, hide_index=True) with report_col2: st.markdown("""

Recommendations

""", unsafe_allow_html=True) critical_count = analysis_data['analysis'].get('critical_defects', 0) high_count = analysis_data['analysis'].get('high_defects', 0) if critical_count > 0: st.markdown(f"""
โš ๏ธ CRITICAL ACTION REQUIRED

{critical_count} critical defect(s) detected. Immediate inspection and potential repair/replacement recommended.

""", unsafe_allow_html=True) elif high_count > 0: st.markdown(f"""
โšก ATTENTION REQUIRED

{high_count} high severity defect(s) detected. Schedule maintenance and monitoring.

""", unsafe_allow_html=True) else: st.markdown("""
โœ… PASSED

No critical or high severity defects detected. Component meets quality standards.

""", unsafe_allow_html=True) # Export options st.markdown("---") st.markdown("""

๐Ÿ’พ Export Results

""", unsafe_allow_html=True) export_col1, export_col2, export_col3 = st.columns(3) with export_col1: if st.button("๐Ÿ“ฅ Download Annotated Image", use_container_width=True): buf = BytesIO() analysis_data['annotated_image'].save(buf, format='PNG') buf.seek(0) b64 = base64.b64encode(buf.read()).decode() href = f'' st.markdown(href, unsafe_allow_html=True) with export_col2: if st.button("๐Ÿ“Š Export CSV Report", use_container_width=True): if analysis_data['defects']: df_export = pd.DataFrame(analysis_data['defects']) df_export['position'] = df_export['position'].apply(str) csv = df_export.to_csv(index=False) b64 = base64.b64encode(csv.encode()).decode() href = f'' st.markdown(href, unsafe_allow_html=True) with export_col3: if st.button("๐Ÿ“‹ Generate JSON Report", use_container_width=True): json_report = { 'test_info': { 'timestamp': analysis_data['timestamp'], 'ndt_method': analysis_data['ndt_method'], 'material_type': analysis_data['material_type'], 'parameters': analysis_data['parameters'] }, 'summary': analysis_data['analysis'], 'defects': analysis_data['defects'] } json_str = json.dumps(json_report, indent=2, default=str) b64 = base64.b64encode(json_str.encode()).decode() href = f'' st.markdown(href, unsafe_allow_html=True) # Tab 4: History with tab_history: st.markdown("""

๐Ÿ“œ Analysis History

View all previous analyses performed in this session.

""", unsafe_allow_html=True) if not st.session_state.analysis_history: st.info("No analysis history available. Perform an analysis to see it here.") else: st.markdown(f"**Total Analyses:** {len(st.session_state.analysis_history)}") for i, hist in enumerate(reversed(st.session_state.analysis_history), 1): with st.expander(f"Analysis #{len(st.session_state.analysis_history) - i + 1}: {hist['timestamp']}"): hist_col1, hist_col2, hist_col3 = st.columns(3) with hist_col1: st.markdown(f"**NDT Method:** {hist['ndt_method']}") st.markdown(f"**Material:** {hist['material_type']}") with hist_col2: st.markdown(f"**Total Defects:** {hist['analysis'].get('total_defects', 0)}") st.markdown(f"**Critical:** {hist['analysis'].get('critical_defects', 0)}") with hist_col3: st.markdown(f"**Avg Confidence:** {hist['analysis'].get('avg_confidence', 0):.2%}") st.markdown(f"**Total Area:** {hist['analysis'].get('total_area', 0):.2f} mmยฒ") st.image(hist['annotated_image'], use_container_width=True) # Footer st.markdown("---") st.markdown("""

๐Ÿ”ฌ CompositeDefect AI - Advanced NDT Analysis System

Powered by Machine Learning | ยฉ 2024

""", unsafe_allow_html=True) """ Sample image generator for testing CompositeDefect AI Generates synthetic NDT-style images with simulated defects """ import numpy as np from PIL import Image, ImageDraw import random def generate_ultrasonic_cscan(size=(512, 512), num_defects=5): """Generate a synthetic ultrasonic C-scan image""" # Create base gradient background img = np.zeros((size[1], size[0]), dtype=np.uint8) # Add gradient for y in range(size[1]): img[y, :] = int(128 + 50 * np.sin(y / 50)) # Add noise noise = np.random.normal(0, 10, (size[1], size[0])).astype(np.int16) img = np.clip(img.astype(np.int16) + noise, 0, 255).astype(np.uint8) # Add simulated defects (darker regions) img_color = np.stack([img, img, img], axis=2) pil_img = Image.fromarray(img_color) draw = ImageDraw.Draw(pil_img) for _ in range(num_defects): x = random.randint(50, size[0] - 100) y = random.randint(50, size[1] - 100) w = random.randint(30, 80) h = random.randint(30, 80) # Draw dark ellipse for defect draw.ellipse([x, y, x+w, y+h], fill=(40, 40, 60)) return pil_img def generate_thermal_image(size=(512, 512), num_hotspots=4): """Generate a synthetic thermal/infrared image""" img = np.zeros((size[1], size[0], 3), dtype=np.uint8) # Base temperature (cool = blue) img[:, :] = [30, 30, 80] # Add hotspots (warm = red/yellow) pil_img = Image.fromarray(img) draw = ImageDraw.Draw(pil_img) for _ in range(num_hotspots): x = random.randint(50, size[0] - 100) y = random.randint(50, size[1] - 100) radius = random.randint(20, 60) # Hotspot gradient for r in range(radius, 0, -2): intensity = int(255 * (1 - r/radius)) color = (255, intensity, 0) if intensity > 128 else (255, 0, 255-intensity) draw.ellipse([x-r, y-r, x+r, y+r], fill=color) return pil_img def generate_radiograph(size=(512, 512), num_defects=3): """Generate a synthetic X-ray/radiographic image""" # Base grey img = np.full((size[1], size[0]), 180, dtype=np.uint8) # Add structure lines (fibre orientation) for i in range(0, size[0], 20): img[:, i:i+2] = np.clip(img[:, i:i+2] - 20, 0, 255) # Add defects (darker regions = less dense) pil_img = Image.fromarray(img) draw = ImageDraw.Draw(pil_img) for _ in range(num_defects): x = random.randint(50, size[0] - 150) y = random.randint(50, size[1] - 150) # Crack-like defect if random.random() > 0.5: x2 = x + random.randint(50, 150) y2 = y + random.randint(-30, 30) draw.line([(x, y), (x2, y2)], fill=80, width=3) else: # Void w = random.randint(20, 50) h = random.randint(20, 50) draw.ellipse([x, y, x+w, y+h], fill=100) return pil_img def generate_visual_inspection(size=(512, 512), num_defects=4): """Generate a synthetic visual inspection image""" # Carbon fibre weave pattern img = np.zeros((size[1], size[0], 3), dtype=np.uint8) img[:, :] = [40, 40, 40] # Dark carbon fibre base # Add weave pattern for i in range(0, size[0], 8): img[:, i:i+4] = [60, 60, 60] for i in range(0, size[1], 8): img[i:i+4, :] = [50, 50, 50] pil_img = Image.fromarray(img) draw = ImageDraw.Draw(pil_img) for _ in range(num_defects): x = random.randint(50, size[0] - 100) y = random.randint(50, size[1] - 100) defect_type = random.choice(['delamination', 'scratch', 'discoloration']) if defect_type == 'delamination': # Delamination - lighter area w = random.randint(40, 100) h = random.randint(40, 100) draw.ellipse([x, y, x+w, y+h], fill=(100, 100, 100, 128)) elif defect_type == 'scratch': # Scratch line x2 = x + random.randint(30, 100) y2 = y + random.randint(-20, 20) draw.line([(x, y), (x2, y2)], fill=(150, 150, 150), width=2) else: # Discoloration w = random.randint(30, 80) h = random.randint(30, 80) draw.rectangle([x, y, x+w, y+h], fill=(80, 60, 40)) return pil_img def main(): """Generate sample images for testing""" print("๐Ÿ”ฌ Generating sample NDT images for testing...") # Generate different types of NDT images ultrasonic = generate_ultrasonic_cscan(num_defects=6) ultrasonic.save('sample_ultrasonic.png') print("โœ… Generated: sample_ultrasonic.png") thermal = generate_thermal_image(num_hotspots=5) thermal.save('sample_thermal.png') print("โœ… Generated: sample_thermal.png") radiograph = generate_radiograph(num_defects=4) radiograph.save('sample_radiograph.png') print("โœ… Generated: sample_radiograph.png") visual = generate_visual_inspection(num_defects=5) visual.save('sample_visual.png') print("โœ… Generated: sample_visual.png") print("\n๐Ÿ“ Sample images saved in current directory") print("๐Ÿš€ You can now test the CompositeDefect AI application!") if __name__ == "__main__": main()