import cv2
import numpy as np
import matplotlib.pyplot as plt
def real_world_applications():
"""Demonstrate real-world applications of edge detection"""
# Simulate different real-world scenarios
# 1. Lane Detection (Autonomous Vehicles)
def simulate_lane_detection():
# Create a road-like image
road = np.ones((200, 300), dtype=np.uint8) * 100 # Road surface
# Add lane markings
cv2.line(road, (50, 0), (50, 200), 255, 3) # Left lane
cv2.line(road, (150, 0), (150, 200), 255, 3) # Center lane
cv2.line(road, (250, 0), (250, 200), 255, 3) # Right lane
# Add some noise and blur
road = cv2.GaussianBlur(road, (3, 3), 1.0)
noise = np.random.normal(0, 5, road.shape)
road = np.clip(road + noise, 0, 255).astype(np.uint8)
# Apply edge detection
edges = cv2.Canny(road, 50, 150)
# Use Hough transform to detect lines
lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=50,
minLineLength=50, maxLineGap=10)
# Draw detected lines
lane_image = cv2.cvtColor(road, cv2.COLOR_GRAY2BGR)
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(lane_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
return road, edges, lane_image
# 2. Medical Image Analysis
def simulate_medical_imaging():
# Simulate a medical scan with organ boundaries
medical = np.zeros((150, 150), dtype=np.uint8)
# Simulate organ shapes
cv2.ellipse(medical, (75, 75), (60, 40), 0, 0, 360, 150, -1) # Main organ
cv2.ellipse(medical, (75, 75), (40, 25), 0, 0, 360, 200, -1) # Inner structure
cv2.circle(medical, (60, 60), 8, 100, -1) # Small structure
cv2.circle(medical, (90, 90), 6, 180, -1) # Another structure
# Add realistic medical imaging noise
noise = np.random.normal(0, 8, medical.shape)
medical = np.clip(medical + noise, 0, 255).astype(np.uint8)
# Apply different edge detection methods for medical analysis
canny_edges = cv2.Canny(medical, 30, 80)
sobel_edges = cv2.Sobel(medical, cv2.CV_8U, 1, 1, ksize=3)
return medical, canny_edges, sobel_edges
# 3. Industrial Inspection
def simulate_industrial_inspection():
# Simulate a manufactured part with potential defects
part = np.ones((120, 120), dtype=np.uint8) * 200 # Base material
# Perfect circular part
cv2.circle(part, (60, 60), 50, 150, -1)
# Add defects
cv2.circle(part, (45, 45), 5, 100, -1) # Void/defect
cv2.rectangle(part, (70, 70), (75, 85), 100, -1) # Scratch
# Add manufacturing noise
noise = np.random.normal(0, 3, part.shape)
part = np.clip(part + noise, 0, 255).astype(np.uint8)
# Edge detection for defect identification
edges = cv2.Canny(part, 40, 120)
# Find contours for defect analysis
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw contours
part_color = cv2.cvtColor(part, cv2.COLOR_GRAY2BGR)
cv2.drawContours(part_color, contours, -1, (0, 255, 0), 1)
return part, edges, part_color
# Run all simulations
road_orig, road_edges, lane_detected = simulate_lane_detection()
medical_orig, medical_canny, medical_sobel = simulate_medical_imaging()
part_orig, part_edges, part_analyzed = simulate_industrial_inspection()
# Create comprehensive visualization
plt.figure(figsize=(18, 12))
# Lane Detection
plt.subplot(3, 4, 1)
plt.imshow(road_orig, cmap='gray')
plt.title('Simulated Road Scene')
plt.axis('off')
plt.subplot(3, 4, 2)
plt.imshow(road_edges, cmap='gray')
plt.title('Edge Detection')
plt.axis('off')
plt.subplot(3, 4, 3)
plt.imshow(cv2.cvtColor(lane_detected, cv2.COLOR_BGR2RGB))
plt.title('Lane Detection Result')
plt.axis('off')
plt.subplot(3, 4, 4)
# Cross-section analysis
row = 100
plt.plot(road_orig[row, :], label='Original', alpha=0.7)
plt.plot(road_edges[row, :], label='Edges', linewidth=2)
plt.title('Lane Intensity Profile')
plt.legend()
plt.grid(True)
# Medical Imaging
plt.subplot(3, 4, 5)
plt.imshow(medical_orig, cmap='bone') # Medical imaging colormap
plt.title('Simulated Medical Scan')
plt.axis('off')
plt.subplot(3, 4, 6)
plt.imshow(medical_canny, cmap='gray')
plt.title('Canny Edge Detection')
plt.axis('off')
plt.subplot(3, 4, 7)
plt.imshow(medical_sobel, cmap='gray')
plt.title('Sobel Edge Detection')
plt.axis('off')
plt.subplot(3, 4, 8)
# Compare edge detection methods
canny_count = np.sum(medical_canny > 0)
sobel_count = np.sum(medical_sobel > 128)
plt.bar(['Canny', 'Sobel'], [canny_count, sobel_count])
plt.title('Edge Pixel Comparison')
plt.ylabel('Edge Pixels')
# Industrial Inspection
plt.subplot(3, 4, 9)
plt.imshow(part_orig, cmap='gray')
plt.title('Manufactured Part')
plt.axis('off')
plt.subplot(3, 4, 10)
plt.imshow(part_edges, cmap='gray')
plt.title('Defect Detection Edges')
plt.axis('off')
plt.subplot(3, 4, 11)
plt.imshow(cv2.cvtColor(part_analyzed, cv2.COLOR_BGR2RGB))
plt.title('Defect Analysis')
plt.axis('off')
plt.subplot(3, 4, 12)
# Quality metrics
total_edge_pixels = np.sum(part_edges > 0)
total_pixels = part_edges.size
edge_density = total_edge_pixels / total_pixels * 100
metrics = ['Edge Density %', 'Defect Score']
values = [edge_density, min(edge_density * 2, 100)] # Simplified defect score
colors = ['green' if v < 50 else 'red' for v in values]
plt.bar(metrics, values, color=colors)
plt.title('Quality Metrics')
plt.ylabel('Score')
plt.tight_layout()
plt.show()
print("Real-world applications demonstrated:")
print(f"1. Lane Detection: Found {len(lane_detected)} lane markings")
print(f"2. Medical Imaging: Detected {np.sum(medical_canny > 0)} edge pixels")
print(f"3. Industrial Inspection: Edge density = {edge_density:.2f}%")
# Run real-world applications demo
real_world_applications()