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

เล่นวิดีโอถอยหลังด้วย Python OpenCV

OpenCV (Open Source Computer Vision) ใช้ทำ operations ต่างๆ บนภาพและวิดีโอ

พื้นที่ประยุกต์

  • Facial recognition system
  • Motion tracking
  • Artificial neural network
  • Deep neural network
  • Video streaming ฯลฯ

การติดตั้ง


# Windows
pip install opencv-python

# Linux
sudo apt-get install python3-opencv

แนวคิด: เล่นวิดีโอถอยหลัง

  1. นำเข้า OpenCV (cv2)
  2. เปิดไฟล์วิดีโอ
  3. อ่านเฟรมทุกเฟรม เก็บไว้ในลิสต์
  4. กลับลำดับลิสต์ (reverse)
  5. แสดงเฟรมทีละเฟรมจากลิสต์ที่กลับแล้ว

โค้ดตัวอย่าง (แก้ไขจากต้นฉบับให้ทำงานได้)


import cv2

# เปิดวิดีโอ
cap = cv2.VideoCapture('input_video.mp4')  # หรือ 0 สำหรับ webcam

if not cap.isOpened():
    print("Error: Cannot open video")
    exit()

frame_list = []

# อ่านเฟรมทั้งหมดเก็บในลิสต์
while True:
    ret, frame = cap.read()
    if not ret:
        break
    frame_list.append(frame)

cap.release()

# เล่นไปข้างหน้า (Normal)
print("Playing forward...")
for frame in frame_list:
    cv2.imshow('Frame', frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

# เล่นถอยหลัง (Reverse)
print("Playing reverse...")
for frame in reversed(frame_list):
    cv2.imshow('Frame', frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

โค้ดแบบประหยัดหน่วยความจำ (Generator)

ถ้าวิดีโอใหญ่เกิน RAM ใช้ generator + seek (ถ้ารองรับ)


import cv2

cap = cv2.VideoCapture('input_video.mp4')
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

# ข้ามไปเฟรมสุดท้ายแล้วอ่านย้อนหลัง (ต้องการ codec ที่รองรับ seeking)
for frame_idx in range(total_frames - 1, -1, -1):
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
    ret, frame = cap.read()
    if not ret:
        break
    cv2.imshow('Reverse', frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

หมายเหตุ: โค้ดต้นฉบับมีหลายปัญหา: ตัวแปร cap ไม่ได้ define, ใช้ cv2.imwrite เขียนไฟล์ทีละเฟรม (ช้า), logic ผิด โค้ดด้านบนแก้ไขให้ทำงานจริงได้แล้ว

ผลลัพธ์

เล่นวิดีโอถอยหลังด้วย Python OpenCV