Textile Defect Detection System

Real-time fabric quality inspection using computer vision

Python OpenCV TensorFlow Flask React
Textile Defect Detection System

Project Overview

This project implements a comprehensive defect detection system for textile manufacturing, capable of identifying various fabric defects including holes, stains, weaving errors, and color inconsistencies at production line speeds.

Challenge

Textile manufacturers face significant quality control challenges:

  • Manual inspection is slow and inconsistent
  • Defects are often subtle and easy to miss
  • High-speed production lines require real-time processing
  • Various fabric types and patterns need different approaches

Solution Architecture

System Components

  1. Image Acquisition: High-resolution line-scan cameras
  2. Preprocessing: Noise reduction and normalization
  3. Detection Engine: Multi-model approach
  4. Dashboard: Real-time monitoring and analytics
  5. Alert System: Immediate notification of defects

Technical Implementation

1. Image Preprocessing Pipeline

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import cv2
import numpy as np

def preprocess_fabric_image(image):
    # Convert to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Apply Gaussian blur to reduce noise
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    
    # Enhance contrast using CLAHE
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    enhanced = clahe.apply(blurred)
    
    # Normalize
    normalized = cv2.normalize(enhanced, None, 0, 255, cv2.NORM_MINMAX)
    
    return normalized

2. Multi-Model Detection Approach

We use different models for different defect types:

For Structural Defects (holes, tears):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Classical CV approach for speed
def detect_structural_defects(image):
    # Edge detection
    edges = cv2.Canny(image, 50, 150)
    
    # Find contours
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, 
                                   cv2.CHAIN_APPROX_SIMPLE)
    
    defects = []
    for contour in contours:
        area = cv2.contourArea(contour)
        if area > MIN_DEFECT_AREA:
            x, y, w, h = cv2.boundingRect(contour)
            defects.append({
                'type': 'structural',
                'bbox': [x, y, w, h],
                'area': area
            })
    
    return defects

For Color/Pattern Defects:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Deep learning approach for complex patterns
model = tf.keras.models.load_model('pattern_detector.h5')

def detect_pattern_defects(image):
    # Prepare image
    img_array = preprocess_for_model(image)
    
    # Get predictions
    predictions = model.predict(img_array)
    
    # Post-process
    defects = parse_predictions(predictions, threshold=0.8)
    
    return defects

3. Real-Time Processing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from threading import Thread
from queue import Queue

class RealtimeDetector:
    def __init__(self):
        self.frame_queue = Queue(maxsize=30)
        self.result_queue = Queue()
        
    def capture_thread(self):
        cap = cv2.VideoCapture(0)
        while True:
            ret, frame = cap.read()
            if ret and not self.frame_queue.full():
                self.frame_queue.put(frame)
    
    def process_thread(self):
        while True:
            frame = self.frame_queue.get()
            
            # Detect defects
            structural = detect_structural_defects(frame)
            pattern = detect_pattern_defects(frame)
            
            # Combine results
            all_defects = structural + pattern
            
            if all_defects:
                self.result_queue.put({
                    'frame': frame,
                    'defects': all_defects,
                    'timestamp': time.time()
                })
    
    def run(self):
        Thread(target=self.capture_thread, daemon=True).start()
        Thread(target=self.process_thread, daemon=True).start()

Web Dashboard

Backend API (Flask)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

detector = RealtimeDetector()

@app.route('/api/defects/recent', methods=['GET'])
def get_recent_defects():
    defects = get_last_n_defects(10)
    return jsonify(defects)

@app.route('/api/stats', methods=['GET'])
def get_statistics():
    stats = {
        'total_inspected': get_total_count(),
        'defects_found': get_defect_count(),
        'defect_rate': calculate_defect_rate(),
        'uptime': get_system_uptime()
    }
    return jsonify(stats)

Frontend (React)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React, { useState, useEffect } from 'react';

function Dashboard() {
  const [stats, setStats] = useState({});
  const [defects, setDefects] = useState([]);
  
  useEffect(() => {
    // Fetch stats every 5 seconds
    const interval = setInterval(() => {
      fetch('/api/stats')
        .then(res => res.json())
        .then(data => setStats(data));
    }, 5000);
    
    return () => clearInterval(interval);
  }, []);
  
  return (
    <div className="dashboard">
      <StatsPanel stats={stats} />
      <DefectList defects={defects} />
      <LiveFeed />
    </div>
  );
}

Results & Performance

Detection Accuracy

Defect Type Precision Recall F1-Score
Holes 99.2% 98.5% 98.8%
Stains 96.8% 94.2% 95.5%
Weaving Errors 97.5% 96.8% 97.1%
Color Issues 95.3% 93.7% 94.5%

Processing Speed

  • Throughput: 120 meters/minute
  • Latency: < 100ms per frame
  • Resolution: 4096 x 2048 pixels

Business Impact

  • 85% reduction in manual inspection time
  • 45% decrease in defective products shipped
  • $750K annual cost savings
  • Payback period: 6 months

Challenges & Solutions

Challenge 1: Varied Fabric Patterns

Solution: Pattern-agnostic detection using texture analysis and pattern subtraction

Challenge 2: Different Lighting Conditions

Solution: Automatic exposure control and robust preprocessing

Challenge 3: High-Speed Requirements

Solution: GPU acceleration and optimized algorithms

Deployment

Hardware Requirements

  • Industrial camera: Basler linea2 GigE
  • Processing unit: NVIDIA Jetson AGX Xavier
  • Lighting: LED line lights (6500K)
  • Network: 10 Gigabit Ethernet

Software Stack

  • OS: Ubuntu 20.04 LTS
  • Deep Learning: TensorFlow 2.8
  • Computer Vision: OpenCV 4.5
  • Web Framework: Flask 2.0
  • Frontend: React 18

Future Enhancements

  • Add 3D defect detection using depth cameras
  • Implement predictive maintenance for production equipment
  • Expand to multiple fabric types
  • Mobile app for remote monitoring
  • Integration with ERP systems

Conclusion

This textile defect detection system demonstrates the power of combining classical computer vision with modern deep learning approaches to solve real-world manufacturing challenges. The hybrid approach allows for both speed and accuracy, making it suitable for high-throughput production environments.

Resources


Interested in implementing a similar system? Contact us for consultation!