工場での不良品検知システム:機械学習を活用した品質管理の完全ガイド
はじめに
製造業において品質管理は最も重要な要素の一つです。従来の目視検査では限界がある不良品の検知を、機械学習技術を活用することで大幅に改善することができます。本記事では、工場での不良品検知システムの構築方法について詳しく解説します。
不良品検知における機械学習の必要性
従来の検査方法の課題
- 人的ミス: 作業者の疲労や集中力低下による見落とし
- 検査速度の限界: 大量生産における検査時間の制約
- 主観的判断: 検査員による品質基準の差異
- コスト: 熟練検査員の確保と人件費
機械学習による解決効果
- 24時間稼働: 連続的な品質監視が可能
- 高精度: 人間の目では発見困難な微細な不良も検知
- 標準化: 一定の品質基準での客観的判断
- コスト削減: 長期的な人件費削減効果
不良品検知の主要手法
1. 画像分類(Image Classification)
製品の画像を「良品」「不良品」に分類する最も基本的な手法です。
import tensorflow as tf
from tensorflow.keras import layers, models
# シンプルなCNNモデル
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
layers.MaxPooling2D(2, 2),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D(2, 2),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(1, activation='sigmoid') # 2値分類
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
2. 物体検出(Object Detection)
不良箇所の位置まで特定する手法です。
import cv2
import numpy as np
# YOLOを使用した不良品検出の例
def detect_defects(image_path, model, confidence_threshold=0.5):
image = cv2.imread(image_path)
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True)
model.setInput(blob)
outputs = model.forward()
defects = []
for output in outputs:
for detection in output:
scores = detection[5:]
confidence = scores[0]
if confidence > confidence_threshold:
# 不良品の座標を取得
center_x = int(detection[0] * image.shape[1])
center_y = int(detection[1] * image.shape[0])
defects.append((center_x, center_y, confidence))
return defects
3. 異常検知(Anomaly Detection)
正常品のパターンを学習し、異常を検出する手法です。
from sklearn.ensemble import IsolationForest
import numpy as np
# Isolation Forestを使用した異常検知
class DefectDetector:
def __init__(self, contamination=0.1):
self.model = IsolationForest(contamination=contamination, random_state=42)
def train(self, normal_features):
"""正常品の特徴量で学習"""
self.model.fit(normal_features)
def predict(self, features):
"""異常スコアを返す(-1が異常、1が正常)"""
return self.model.predict(features)
def get_anomaly_score(self, features):
"""異常度スコアを取得"""
return self.model.decision_function(features)
業界別の不良品検知事例
電子部品製造
# プリント基板の配線欠陥検知
def detect_pcb_defects(image):
# 前処理
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# エッジ検出
edges = cv2.Canny(blurred, 50, 150)
# 輪郭検出
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
defects = []
for contour in contours:
area = cv2.contourArea(contour)
if 100 < area < 1000: # 異常なサイズの領域
defects.append(contour)
return defects
自動車部品
# 表面傷検知システム
def detect_surface_scratches(image, model):
# 画像を小さな領域に分割
patches = extract_patches(image, patch_size=(64, 64))
predictions = []
for patch in patches:
# 各パッチを正規化
normalized_patch = patch / 255.0
# モデルで予測
pred = model.predict(np.expand_dims(normalized_patch, axis=0))
predictions.append(pred[0][0])
# 閾値以上のパッチを不良として検出
threshold = 0.7
defective_regions = [i for i, pred in enumerate(predictions) if pred > threshold]
return defective_regions
システム実装のステップ
Step 1: データ収集と前処理
import os
from PIL import Image
import pandas as pd
def prepare_dataset(data_dir):
"""データセットの準備"""
images = []
labels = []
for category in ['good', 'defective']:
category_path = os.path.join(data_dir, category)
for filename in os.listdir(category_path):
if filename.endswith(('.jpg', '.png')):
img_path = os.path.join(category_path, filename)
image = Image.open(img_path).resize((224, 224))
images.append(np.array(image))
labels.append(1 if category == 'defective' else 0)
return np.array(images), np.array(labels)
Step 2: モデル訓練
# データ分割
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
images, labels, test_size=0.2, random_state=42
)
# モデル訓練
history = model.fit(
X_train, y_train,
epochs=50,
batch_size=32,
validation_split=0.2,
verbose=1
)
# 評価
test_loss, test_accuracy = model.evaluate(X_test, y_test)
print(f'テスト精度: {test_accuracy:.4f}')
Step 3: リアルタイム検知システム
import threading
import queue
class RealTimeDefectDetector:
def __init__(self, model_path):
self.model = tf.keras.models.load_model(model_path)
self.frame_queue = queue.Queue()
self.result_queue = queue.Queue()
def process_frame(self, frame):
"""フレームを処理して不良品を検知"""
preprocessed = preprocess_image(frame)
prediction = self.model.predict(np.expand_dims(preprocessed, axis=0))
is_defective = prediction[0][0] > 0.5
confidence = float(prediction[0][0])
return {
'defective': is_defective,
'confidence': confidence,
'timestamp': time.time()
}
def start_detection(self):
"""リアルタイム検知を開始"""
while True:
if not self.frame_queue.empty():
frame = self.frame_queue.get()
result = self.process_frame(frame)
self.result_queue.put(result)
パフォーマンス評価指標
主要指標
from sklearn.metrics import classification_report, confusion_matrix
def evaluate_model(y_true, y_pred):
"""モデル評価"""
# 混同行列
cm = confusion_matrix(y_true, y_pred)
print("混同行列:")
print(cm)
# 分類レポート
report = classification_report(y_true, y_pred)
print("\n分類レポート:")
print(report)
# カスタム指標
tn, fp, fn, tp = cm.ravel()
precision = tp / (tp + fp) # 適合率
recall = tp / (tp + fn) # 再現率
specificity = tn / (tn + fp) # 特異度
print(f"適合率: {precision:.4f}")
print(f"再現率: {recall:.4f}")
print(f"特異度: {specificity:.4f}")
導入時の注意点
データ品質の確保
- バランスの取れたデータセット: 良品と不良品の比率を適切に保つ
- 多様なパターン: 様々な不良パターンを網羅したデータ収集
- 品質ラベリング: 専門家による正確なアノテーション
運用環境での考慮事項
# エラーハンドリングの例
def robust_detection(image_path, model):
try:
# 画像読み込み
image = cv2.imread(image_path)
if image is None:
raise ValueError("画像が読み込めません")
# 前処理
processed_image = preprocess_image(image)
# 予測
prediction = model.predict(processed_image)
return {
'status': 'success',
'prediction': prediction,
'confidence': float(prediction[0])
}
except Exception as e:
return {
'status': 'error',
'message': str(e),
'prediction': None
}
今後の技術動向
最新技術の活用
- Transfer Learning: 事前学習済みモデルの活用
- AutoML: 自動機械学習による効率化
- Edge AI: エッジデバイスでのリアルタイム処理
- 説明可能AI: 判断根拠の可視化
統合システムの構築
# IoTとの連携例
import json
import paho.mqtt.client as mqtt
class IoTIntegratedDetector:
def __init__(self, mqtt_broker, topic):
self.client = mqtt.Client()
self.client.connect(mqtt_broker, 1883, 60)
self.topic = topic
def send_alert(self, defect_info):
"""不良品検知時のアラート送信"""
alert_data = {
'timestamp': time.time(),
'defect_type': defect_info['type'],
'confidence': defect_info['confidence'],
'location': defect_info['position']
}
self.client.publish(
self.topic,
json.dumps(alert_data)
)
まとめ
工場での不良品検知に機械学習を導入することで、品質向上とコスト削減の両立が可能になります。成功の鍵は、適切な手法の選択、質の高いデータセットの構築、そして継続的な改善にあります。
技術の進歩により、より高精度で効率的な不良品検知システムの構築が可能になっています。自社の製造プロセスに適した機械学習ソリューションの導入を検討してみてはいかがでしょうか。
■テックジム「AIエンジニア養成コース」
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<オンライン無料>ゼロから始めるPython爆速講座





