Top Ad unit 728 × 90


Quay và ghi video bằng OpenCV (Ví dụ với C++ & Python)

1.Reading a Video

Trong OpenCV, video có thể đọc bằng cách sử dụng nguồn từ camera được kết nối vào máy tính hoặc đọc video file trong máy. Bước đầu tiên là chúng ta cần tạo một object được gọi là VideoCapture. Tham số của nó có thế hoặc là  chỉ số của thiết bị hoặc tên của video file.
Trong hầu hết các trường hợp chỉ có một video kết nối vào máy tính, chúng ta sẽ set tham số cho VideoCapture là '0' và OpenCV chỉ sử dụng camera kết nối vào máy tính. Khi chúng ta có nhiều hơn một camera được kết nối, chúng ta có thể lựa chọn camera bằng cách truyền tham số ‘1’ cho CAM 2,  ‘2’ cho CAM 3 hoặc nhiều hơn theo quy luật tăng dần.
Python
1
2
3
4
# Create a VideoCapture object and read from input file
# If the input is taken from the camera, pass 0 instead of the video file name.
cap = cv2.VideoCapture('chaplin.mp4')
C++
1
2
3
4
// Create a VideoCapture object and open the input file
// If the input is taken from the camera, pass 0 instead of the video file name
VideoCapture cap("chaplin.mp4");
Sau khi thiết lập VideoCapture object chúng ta có thể lấy được các khung ảnh của video (frame by frame)

Hiển thị video

Sau khi đọc video file, chúng ta có thể hiển thị video theo từng frame ảnh. Một frame ảnh của video đơn giản là một ảnh, chúng ta hiển thị từng frame như khi hiển thị một bức ảnh trong OpenCV bằng hàm imshow().
Như là trường hợp của một ảnh, chúng ta sử dụng waitKey() sau hàm imshow() để dừng từng frame ảnh.Trong trường hợp của một ảnh chúng ta truyền tham số  ‘0’ cho waitKey() , nhưng để trình chiếu video chúng ta cần truyền tham số lớn hơn '0', bới nếu set '0' sẽ làm dừng frame ảnh trong video. Tham số này bằng với thời gian tính bằng milliseconds thời gian chúng ta muốn hiện mỗi frame ảnh.
Trong khi đọc các frame ảnh từ webcam, sử dụng waitKey(1) là thích hợp bởi vì tần số khung hình giới hạn bởi webcam kể cả chúng ta sử dụng 1 ms ở hàm waitKey.
Dưới đây là ví dụ dùng Python và C++ để đọc và hiển thị video.
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import cv2
import numpy as np
# Create a VideoCapture object and read from input file
# If the input is the camera, pass 0 instead of the video file name
cap = cv2.VideoCapture('chaplin.mp4')
# Check if camera opened successfully
if (cap.isOpened()== False):
  print("Error opening video stream or file")
# Read until video is completed
while(cap.isOpened()):
  # Capture frame-by-frame
  ret, frame = cap.read()
  if ret == True:
    # Display the resulting frame
    cv2.imshow('Frame',frame)
    # Press Q on keyboard to  exit
    if cv2.waitKey(25) & 0xFF == ord('q'):
      break
  # Break the loop
  else:
    break
# When everything done, release the video capture object
cap.release()
# Closes all the frames
cv2.destroyAllWindows()
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(){
  // Create a VideoCapture object and open the input file
  // If the input is the web camera, pass 0 instead of the video file name
  VideoCapture cap("chaplin.mp4");
    
  // Check if camera opened successfully
  if(!cap.isOpened()){
    cout << "Error opening video stream or file" << endl;
    return -1;
  }
     
  while(1){
    Mat frame;
    // Capture frame-by-frame
    cap >> frame;
  
    // If the frame is empty, break immediately
    if (frame.empty())
      break;
    // Display the resulting frame
    imshow( "Frame", frame );
    // Press  ESC on keyboard to exit
    char c=(char)waitKey(25);
    if(c==27)
      break;
  }
  
  // When everything done, release the video capture object
  cap.release();
  // Closes all the frames
  destroyAllWindows();
     
  return 0;
}

Ghi video

Sau khi kết thúc video capturing và processing từng frame bước tiếp theo chúng ta sẽ làm là ghi video vào máy tính.
Đối với ảnh, nó khá là đơn giản bằng lệnh cv2.imwrite(). Nhưng đối với videos, chúng ta cần thêm một số bước phức tạp hơn. Chúng ta cần tạo một VideoWriter object. Đầu tiên chúng ta cần set đường dẫn và tên file cần lưu (ví dụ: output.avi).Sau đó chúng ta cần set FourCC code và số lượng frames/second (FPS). Cuối cùng, kích cỡ frame cũng được định nghĩa.
Python
1
2
3
4
# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
# Define the fps to be equal to 10. Also frame size is passed.
out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
C++
1
2
3
4
// Define the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file.
// Define the fps to be equal to 10. Also frame size is passed.
  VideoWriter video("outcpp.avi",CV_FOURCC('M','J','P','G'),10, Size(frame_width,frame_height));
FourCC là code 4-byte sử dụng trong mã hóa video . danh sách các code bạn có thể tìm ở dây fourcc.org. Có rất nhiều mã FOURCC nhưng trong bài này chúng ta sử dụng mã MJPG.
Chú ý: Chỉ một số mã FourCC có thể làm việc trên hệ thống máy tính của chúng ta, MJPG là lựa chọn an toàn nhất.
Toàn bộ code ví dụ đọc/hiển thị/ghi,lưu video các bạn có thể xem dưới dây:
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import cv2
import numpy as np
# Create a VideoCapture object
cap = cv2.VideoCapture(0)
# Check if camera opened successfully
if (cap.isOpened() == False):
  print("Unable to read camera feed")
# Default resolutions of the frame are obtained.The default resolutions are system dependent.
# We convert the resolutions from float to integer.
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
while(True):
  ret, frame = cap.read()
  if ret == True:
     
    # Write the frame into the file 'output.avi'
    out.write(frame)
    # Display the resulting frame   
    cv2.imshow('frame',frame)
    # Press Q on keyboard to stop recording
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
  # Break the loop
  else:
    break 
# When everything done, release the video capture and video write objects
cap.release()
out.release()
# Closes all the frames
cv2.destroyAllWindows()
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(){
  // Create a VideoCapture object and use camera to capture the video
  VideoCapture cap(0);
  // Check if camera opened successfully
  if(!cap.isOpened())
  {
    cout << "Error opening video stream" << endl;
    return -1;
  }
  // Default resolution of the frame is obtained.The default resolution is system dependent.
  int frame_width = cap.get(CV_CAP_PROP_FRAME_WIDTH);
  int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
   
  // Define the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file.
  VideoWriter video("outcpp.avi",CV_FOURCC('M','J','P','G'),10, Size(frame_width,frame_height));
  while(1)
  {
    Mat frame;
     
    // Capture frame-by-frame
    cap >> frame;
  
    // If the frame is empty, break immediately
    if (frame.empty())
      break;
     
    // Write the frame into the file 'outcpp.avi'
    video.write(frame);
    
    // Display the resulting frame   
    imshow( "Frame", frame );
  
    // Press  ESC on keyboard to  exit
    char c = (char)waitKey(1);
    if( c == 27 )
      break;
  }
  // When everything done, release the video capture and write object
  cap.release();
  video.release();
  // Closes all the windows
  destroyAllWindows();
  return 0;
}
Quay và ghi video bằng OpenCV (Ví dụ với C++ & Python) Reviewed by Jacky on tháng 12 19, 2017 Rating: 5

Không có nhận xét nào:

All Rights Reserved by Cộng Đồng OpenCV © 2017
Edit bởi: Jacky Le | Youtube Channel: JACKY LE

Biểu mẫu liên hệ

Tên

Email *

Thông báo *

Được tạo bởi Blogger.