Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมตรวจจับการเคลื่อนไหวจากเว็บแคมด้วย Python

เราจะเขียนโปรแกรม Python ที่วิเคราะห์ภาพจากเว็บแคม เพื่อตรวจจับการเคลื่อนไหว และบันทึกช่วงเวลาที่มีการเคลื่อนไหวลงในไฟล์ CSV

ไลบรารีที่จำเป็น

ใช้ OpenCV และ pandas ติดตั้งได้ด้วย:

$ pip install opencv-python pandas

โค้ดตัวอย่าง

import cv2
import pandas as pd
import time
from datetime import datetime

# ตัวแปรเริ่มต้น
stillImage = None
motionImage = [None, None]
time_list = []

# DataFrame สำหรับเก็บเวลาเริ่มต้นและสิ้นสุด
df = pd.DataFrame(columns=["start", "end"])

# เปิดวิดีโอจากเว็บแคม (0 = กล้องหลัก)
video = cv2.VideoCapture(0)

while True:
    # อ่านเฟรมจากวิดีโอ
    check, frame = video.read()
    motion = 0
    
    # แปลงเป็นภาพขาวดำและเบลอเพื่อลด雜訊
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (21, 21), 0)
    
    # จับภาพพื้นหลังครั้งแรก
    if stillImage is None:
        stillImage = gray
        continue
    
    # หาความแตกต่างระหว่างพื้นหลังและเฟรมปัจจุบัน
    diff_frame = cv2.absdiff(stillImage, gray)
    
    # แปลงเป็นขาวดำ: ความต่างมากกว่า 25 จะเป็นสีขาว
    thresh_frame = cv2.threshold(diff_frame, 25, 255, cv2.THRESH_BINARY)[1]
    thresh_frame = cv2.dilate(thresh_frame, None, iterations=2)
    
    # หาคอนทัวร์ของวัตถุที่เคลื่อนที่
    contours, hierarchy = cv2.findContours(thresh_frame.copy(), 
                                           cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    for contour in contours:
        if cv2.contourArea(contour) < 10000:  # กรองวัตถุเล็ก
            continue
        motion = 1
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
    
    # บันทึกสถานะการเคลื่อนไหว
    motionImage.append(motion)
    motionImage = motionImage[-2:]
    
    # บันทึกเวลาเริ่มต้นการเคลื่อนไหว
    if motionImage[-1] == 1 and motionImage[-2] == 0:
        time_list.append(datetime.now())
    
    # บันทึกเวลาสิ้นสุดการเคลื่อนไหว
    if motionImage[-1] == 0 and motionImage[-2] == 1:
        time_list.append(datetime.now())
    
    # แสดงภาพในโหมดต่างๆ
    cv2.imshow("Gray_Frame", gray)
    cv2.imshow("Threshold Frame", thresh_frame)
    cv2.imshow("Colored_Frame", frame)
    
    key = cv2.waitKey(1)
    # กด 'q' เพื่อหยุด
    if key == ord('q'):
        if motion == 1:
            time_list.append(datetime.now())
        break

# บันทึกเวลาลง CSV
for i in range(0, len(time_list), 2):
    df = df.append({"Start": time_list[i], "End": time_list[i + 1]}, ignore_index=True)

df.to_csv("FrameInMotion_time.csv")
video.release()
cv2.destroyAllWindows()

ผลลัพธ์

โปรแกรมจะเปิดหน้าต่าง 3 หน้าต่างแสดง:

  • ภาพระดับสีเทา (Grayscale)
  • ภาพขาวดำ閾值 (Threshold - แสดงการเคลื่อนไหวเป็นสีขาว)
  • ภาพสีพร้อมกรอบสี่เหลี่ยมรอบวัตถุที่เคลื่อนที่

ไฟล์ CSV ที่ได้จะมีรูปแบบ:

start, end
2019-02-21 18:10:59.718005, 2019-02-21 18:08:35.791487

ประยุกต์ใช้

สามารถนำไปพัฒนาเป็นระบบกล้องวงจรปิด ตรวจจับผู้บุกรุก นับจำนวนคน หรือวิเคราะห์พฤติกรรมได้