You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

97 lines
4.3 KiB

# 実験課題10
# 3.10 背景差分法(ラベリング・ノイズ処理含む)
import cv2
import numpy as np
# Webカメラの初期化
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("カメラを開けませんでした。")
else:
print("背景差分法を開始します。")
print("'q': 終了, 'r': 背景画像を現フレームで更新")
# 最初のフレームを背景画像として取得するための準備
bg_gray = None
while True:
ret, frame = cap.read()
if not ret:
print("フレームを取得できませんでした。")
break
# 差分計算を安定させるため、現フレームをグレースケール化
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# ガウシアンブラ(平滑化)を適用して、カメラ特有の細かいノイズを低減
gray = cv2.GaussianBlur(gray, (21, 21), 0)
# 起動直後、または 'r' キーが押された場合に背景画像を保存・更新する
if bg_gray is None:
bg_gray = gray
print("背景画像を保存しました。カメラの前から離れてください。")
continue
# --- 3.101 背景差分法:背景画像と現フレームの絶対差分を計算 ---
frame_diff = cv2.absdiff(bg_gray, gray)
# 差分画像を2値化して、動いている領域(前景)を白(255)にする
# 閾値は環境に合わせて調整(ここでは例として 25)
_, thresh = cv2.threshold(frame_diff, 25, 255, cv2.THRESH_BINARY)
# --- 3.102 ノイズ処理(モルフォロジー演算:オープニング) ---
# 3.7で学んだ手法を使い、背景に散らばる小さなチラツキノイズを消去
kernel = np.ones((5, 5), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
# 領域内の穴を埋めて結合を強める(クロージング)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# --- 3.102 ラベリング処理 ---
# 2値化画像から、繋がっている白い領域(動体)を検出してラベルを貼る
# nlabels: ラベルの総数(背景含む)
# labels: 各画素にラベル番号(0, 1, 2...)が割り当てられた画像
# stats: 各領域の矩形座標や面積[x, y, w, h, area]の行列
# centroids: 各領域の中心座標
nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh)
# 各ラベルごとに色分けするためのランダムな色マップを作成(背景の0は黒にする)
# 乱数のシードを固定して、フレーム間で色が激しく変わるのを防ぐ
np.random.seed(42)
colors = np.random.randint(0, 255, (nlabels, 3), dtype=np.uint8)
colors[0] = [0, 0, 0] # ラベル0(背景)は黒に固定
# 画素ごとのラベル番号に対応する色を割り当てて、色分け画像(ラベリング画像)を作成
labeled_img = colors[labels]
# 動体領域に矩形(枠線)を描画する
for i in range(1, nlabels): # 0は背景なので1からループ
x = stats[i, cv2.CC_STAT_LEFT]
y = stats[i, cv2.CC_STAT_TOP]
w = stats[i, cv2.CC_STAT_WIDTH]
h = stats[i, cv2.CC_STAT_HEIGHT]
area = stats[i, cv2.CC_STAT_AREA]
# 面積が小さすぎる領域(微小なノイズの残り)は無視する
if area > 500:
# 動体を緑色の矩形で囲む
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# ラベル番号を画像上に描画
cv2.putText(frame, f"ID:{i}", (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
# --- 結果の表示 ---
cv2.imshow('Original Frame (Motion Detection)', frame)
cv2.imshow('Foreground Mask (Thresh)', thresh)
cv2.imshow('Labeled Components', labeled_img)
# キー入力の受付
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord('r'):
bg_gray = None # 次のループで背景が再キャプチャされる
cap.release()
cv2.destroyAllWindows()