👁️ Computer Vision Fundamentals

คู่มือครบถ้วนเกี่ยวกับพื้นฐาน Computer Vision
สำหรับการประยุกต์ใช้ในงานอุตสาหกรรมและ Automation

📸
Image Processing
การประมวลผลภาพ
🔍
Feature Extraction
การดึงลักษณะเด่น
🎯
Pattern Recognition
การจดจำรูปแบบ
🏭
Industrial Applications
การใช้งานอุตสาหกรรม

Computer Vision คืออะไร?

Computer Vision เป็นสาขาหนึ่งของ Artificial Intelligence ที่เน้นการสอนคอมพิวเตอร์ให้ "เห็น" และ "เข้าใจ" เนื้อหาของภาพและวิดีโอเหมือนมนุษย์ โดยใช้อัลกอรึทึมและแบบจำลองทางคณิตศาสตร์ เพื่อวิเคราะห์ ประมวลผล และตีความข้อมูลภาพ ในงานอุตสาหกรรม Computer Vision ถูกใช้เพื่อ การตรวจสอบคุณภาพ การตรวจจับข้อบกพร่อง การนำทางหุ่นยนต์ และการอ่านค่าเครื่องมือวัด

Computer Vision Processing Pipeline

1

📷 Image Acquisition

การได้มาของภาพจากกล้อง, sensor หรือแหล่งข้อมูลอื่น ๆ

Hardware:
CCD/CMOS cameras
Resolution:
VGA to 8K
Frame Rate:
30-1000 FPS
2

🔧 Image Preprocessing

การปรับปรุงคุณภาพภาพและเตรียมข้อมูลสำหรับการวิเคราะห์

Filtering:
Noise reduction
Enhancement:
Contrast/Brightness
Correction:
Geometric distortion
3

🎯 Feature Extraction

การค้นหาและสกัดคุณลักษณะสำคัญจากภาพ

Edges:
Canny, Sobel
Corners:
Harris, SIFT
Textures:
LBP, GLCM
4

🧠 Analysis & Recognition

การวิเคราะห์และจดจำวัตถุ รูปแบบ หรือข้อมูลที่ต้องการ

Classification:
ML algorithms
Detection:
Object localization
Measurement:
Dimensional analysis
5

⚡ Decision & Action

การตัดสินใจและสั่งการกระทำตามผลการวิเคราะห์

Accept/Reject:
Quality control
Alert/Report:
System notifications
Control:
Actuator commands

เทคนิคพื้นฐาน Computer Vision

🌫️

Image Filtering

การกรองภาพเพื่อลดสัญญาณรบกวนและเพิ่มคุณภาพ

Linear Filters:
  • • Gaussian blur - ลด noise
  • • Mean filter - เรียบภาพ
  • • Motion blur - จำลองการเคลื่อนไหว
Non-linear Filters:
  • • Median filter - ลบ salt & pepper noise
  • • Morphological operations - ปรับรูปร่าง
Common Use
Preprocessing
📐

Edge Detection

การหาขอบ (Edge) ของวัตถุในภาพ

Gradient-based:
  • • Sobel operator - หาขอบแนวตั้ง/นอน
  • • Prewitt operator - คล้าย Sobel
  • • Roberts cross - ขอบเฉียง
Advanced:
  • • Canny edge detector - ขอบที่แม่นยำ
  • • Laplacian of Gaussian - หา zero-crossing
Accuracy
95-99%
🎯

Object Detection

การตรวจจับและระบุตำแหน่งวัตถุในภาพ

Traditional Methods:
  • • Template matching - จับคู่แม่แบบ
  • • Haar cascades - ใบหน้า, ตา
  • • HOG + SVM - คน, รถ
Deep Learning:
  • • YOLO - Real-time detection
  • • R-CNN family - High accuracy
  • • SSD - Speed vs accuracy balance
Speed
30-150 FPS
✂️

Image Segmentation

การแบ่งภาพออกเป็นส่วน ๆ ตามความหมาย

Pixel-level:
  • • Thresholding - แบ่งตามสี
  • • K-means clustering - จัดกลุ่มสี
  • • Watershed - แบ่งตามลุ่มน้ำ
Semantic:
  • • U-Net - Medical imaging
  • • DeepLab - Scene understanding
  • • Mask R-CNN - Instance segmentation
Precision
Pixel-level
🔗

Feature Matching

การจับคู่จุดสำคัญระหว่างภาพ

Feature Descriptors:
  • • SIFT - Scale invariant
  • • SURF - Speeded up SIFT
  • • ORB - Oriented FAST and BRIEF
Matching Algorithms:
  • • Brute force matcher - ทดสอบทุกคู่
  • • FLANN matcher - Fast approximate
  • • Ratio test - Lowe's ratio
Applications
Alignment, Tracking
🔤

Optical Character Recognition

การแปลงข้อความในภาพเป็นข้อมูลดิจิทัล

Traditional OCR:
  • • Tesseract - Open source OCR
  • • Template matching - จับคู่รูปแบบ
  • • Feature extraction - วิเคราะห์ลักษณะ
Deep Learning OCR:
  • • CRNN - CNN + RNN
  • • EAST - Efficient text detection
  • • PaddleOCR - End-to-end OCR
Accuracy
99%+ (clear text)

การประยุกต์ใช้ในอุตสาหกรรม

Quality Control

การตรวจสอบคุณภาพผลิตภัณฑ์อัตโนมัติ

ตรวจจับข้อบกพร่องบนพื้นผิว
วัดขนาดและรูปทรงแม่นยำ
ตรวจสอบสีและความเรียบ
การจัดเรียงและนับจำนวน
Accuracy
99.8%
🤖

Robotics & Automation

การใช้ความมองเห็นในระบบหุ่นยนต์

Robot vision guidance
Pick and place operations
Assembly line automation
Autonomous navigation
Precision
±0.1mm
🛡️

Safety & Security

การรักษาความปลอดภัยด้วยระบบมองเห็น

Personnel detection in danger zones
PPE compliance monitoring
Intrusion detection systems
Behavior analysis & alerts
Response Time
<100ms
📊

Process Monitoring

การติดตามกระบวนการผลิตแบบ Real-time

Gauge และ meter reading
Level monitoring in tanks
Flow rate visualization
Equipment status monitoring
Update Rate
1-30 FPS
📦

Inventory Management

การจัดการสต็อกและคลังสินค้าอัตโนมัติ

Barcode และ QR code reading
Automatic counting
Package sorting
Shelf monitoring
Speed
1000+/min
🔧

Predictive Maintenance

การทำนายการบำรุงรักษาด้วยการมองเห็น

Visual wear detection
Crack และ corrosion monitoring
Oil condition analysis
Component alignment check
Early Detection
30 วัน

ความท้าทายและแนวทางแก้ไข

🌟 ปัญหา: Lighting Conditions

  • • แสงไม่สม่ำเสมอ (Uneven illumination)
  • • เงา (Shadows) และการสะท้อน
  • • การเปลี่ยนแปลงแสงตามเวลา
  • • Backlighting และ glare

💡 แนวทางแก้ไข:

  • • ใช้ LED ring light หรือ diffused lighting
  • • Histogram equalization
  • • Adaptive thresholding
  • • HDR imaging techniques

🌡️ ปัญหา: Environmental Factors

  • • อุณหภูมิและความชื้นสูง
  • • ฝุ่นและสิ่งสกปรกบนเลนส์
  • • การสั่นไหวจากเครื่องจักร
  • • สภาพแวดล้อมที่กัดกร่อน

🛡️ แนวทางแก้ไข:

  • • ใช้ industrial-grade cameras
  • • Protective housing (IP65/67)
  • • Anti-vibration mounting
  • • Auto-cleaning systems

⏱️ ปัญหา: Processing Speed

  • • Real-time processing requirements
  • • High resolution images
  • • Complex algorithms
  • • Multiple simultaneous streams

⚡ แนวทางแก้ไข:

  • • GPU acceleration (CUDA)
  • • Edge computing deployment
  • • Algorithm optimization
  • • Multi-threading processing

⚖️ ปัญหา: Accuracy vs Speed Trade-off

  • • ความแม่นยำสูง = ความเร็วช้า
  • • Real-time requirements
  • • Limited computational resources
  • • Cost constraints

🎯 แนวทางแก้ไข:

  • • Hybrid approaches
  • • Region of Interest (ROI) processing
  • • Model compression techniques
  • • Adaptive processing based on load

ตัวอย่าง Code Implementation

Basic Computer Vision Pipeline with OpenCV


import cv2
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

class IndustrialVisionSystem:
    def __init__(self):
        self.camera = cv2.VideoCapture(0)
        self.setup_camera()
        
    def setup_camera(self):
        """Configure camera parameters"""
        self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
        self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
        self.camera.set(cv2.CAP_PROP_FPS, 30)
        self.camera.set(cv2.CAP_PROP_EXPOSURE, -6)  # Manual exposure
        
    def preprocess_image(self, image):
        """Image preprocessing pipeline"""
        # Convert to grayscale
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        
        # Noise reduction
        denoised = cv2.bilateralFilter(gray, 9, 75, 75)
        
        # Histogram equalization
        equalized = cv2.equalizeHist(denoised)
        
        # Gaussian blur
        blurred = cv2.GaussianBlur(equalized, (5, 5), 0)
        
        return blurred
        
    def detect_edges(self, image):
        """Edge detection using Canny algorithm"""
        # Auto-threshold calculation
        sigma = 0.33
        median = np.median(image)
        lower = int(max(0, (1.0 - sigma) * median))
        upper = int(min(255, (1.0 + sigma) * median))
        
        edges = cv2.Canny(image, lower, upper)
        return edges
        
    def find_contours(self, edges):
        """Find and filter contours"""
        contours, _ = cv2.findContours(
            edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
        )
        
        # Filter contours by area
        min_area = 1000
        max_area = 50000
        filtered_contours = []
        
        for contour in contours:
            area = cv2.contourArea(contour)
            if min_area < area < max_area:
                filtered_contours.append(contour)
                
        return filtered_contours
        
    def extract_features(self, contour):
        """Extract geometric features from contour"""
        features = {}
        
        # Area and perimeter
        features['area'] = cv2.contourArea(contour)
        features['perimeter'] = cv2.arcLength(contour, True)
        
        # Bounding rectangle
        x, y, w, h = cv2.boundingRect(contour)
        features['aspect_ratio'] = float(w) / h
        features['rect_area'] = w * h
        features['extent'] = features['area'] / features['rect_area']
        
        # Minimum enclosing circle
        (cx, cy), radius = cv2.minEnclosingCircle(contour)
        features['circularity'] = features['area'] / (np.pi * radius**2)
        
        # Moments for centroid
        M = cv2.moments(contour)
        if M['m00'] != 0:
            features['centroid_x'] = int(M['m10'] / M['m00'])
            features['centroid_y'] = int(M['m01'] / M['m00'])
        
        return features
        
    def classify_object(self, features):
        """Simple rule-based classification"""
        aspect_ratio = features['aspect_ratio']
        circularity = features['circularity']
        extent = features['extent']
        
        if circularity > 0.8:
            return "Circle/Gauge"
        elif 0.8 < aspect_ratio < 1.2 and extent > 0.8:
            return "Square/Display"
        elif aspect_ratio > 2.0:
            return "Rectangle/Panel"
        else:
            return "Unknown"
            
    def process_frame(self, frame):
        """Complete processing pipeline"""
        results = []
        
        # Preprocessing
        processed = self.preprocess_image(frame)
        
        # Edge detection
        edges = self.detect_edges(processed)
        
        # Find contours
        contours = self.find_contours(edges)
        
        # Process each contour
        for contour in contours:
            features = self.extract_features(contour)
            classification = self.classify_object(features)
            
            result = {
                'contour': contour,
                'features': features,
                'classification': classification
            }
            results.append(result)
            
        return results, edges
        
    def draw_results(self, frame, results):
        """Draw detection results on frame"""
        output = frame.copy()
        
        for i, result in enumerate(results):
            contour = result['contour']
            classification = result['classification']
            features = result['features']
            
            # Draw contour
            cv2.drawContours(output, [contour], -1, (0, 255, 0), 2)
            
            # Draw bounding rectangle
            x, y, w, h = cv2.boundingRect(contour)
            cv2.rectangle(output, (x, y), (x+w, y+h), (255, 0, 0), 2)
            
            # Add text label
            label = f"{classification} #{i+1}"
            cv2.putText(output, label, (x, y-10), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
            
            # Add feature info
            info = f"Area: {features['area']:.0f}"
            cv2.putText(output, info, (x, y+h+20), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
                       
        return output
        
    def run_continuous(self):
        """Main processing loop"""
        print("Starting Industrial Vision System...")
        print("Press 'q' to quit, 's' to save frame")
        
        while True:
            ret, frame = self.camera.read()
            if not ret:
                print("Failed to grab frame")
                break
                
            # Process frame
            results, edges = self.process_frame(frame)
            
            # Draw results
            output = self.draw_results(frame, results)
            
            # Display results
            cv2.imshow('Original', frame)
            cv2.imshow('Edges', edges)
            cv2.imshow('Detection Results', output)
            
            # Print results to console
            if results:
                print(f"Detected {len(results)} objects:")
                for i, result in enumerate(results):
                    print(f"  Object {i+1}: {result['classification']}")
            
            # Handle key presses
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                break
            elif key == ord('s'):
                timestamp = cv2.getTickCount()
                cv2.imwrite(f'capture_{timestamp}.jpg', output)
                print(f"Saved frame as capture_{timestamp}.jpg")
                
        # Cleanup
        self.camera.release()
        cv2.destroyAllWindows()

# Usage example
if __name__ == "__main__":
    vision_system = IndustrialVisionSystem()
    vision_system.run_continuous()

พร้อมเริ่มต้น Computer Vision Project แล้วหรือยัง?

ปรึกษาผู้เชี่ยวชาญเพื่อออกแบบระบบ Computer Vision ที่เหมาะสมกับความต้องการของคุณ