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.
 

63 lines
2.1 KiB

# 実験課題10
# 3.10 背景差分法
import cv2
import numpy as np
# Webカメラの初期化
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("カメラを開けませんでした.")
else:
# 最初のフレームを背景画像として取得するための準備
background = 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)
if background is None:
background = gray
continue
# 背景画像と現フレームの絶対差分を計算
frame_diff = cv2.absdiff(background, gray)
# 差分画像を2値化して動いている領域を白(255)にする
_, thresh = cv2.threshold(frame_diff, 25, 255, cv2.THRESH_BINARY)
# ノイズ処理
kernel = np.ones((5, 5), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# ラベリング処理
nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh)
# 各ラベルごとに色分けするためのランダムな色マップを作成
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]
cv2.imshow('Original Frame (Motion Detection)', frame)
cv2.imshow('Foreground Mask (Thresh)', thresh)
cv2.imshow('Labeled Components', labeled_img)
# 'q' キーが押されたら終了
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()