-
-
Notifications
You must be signed in to change notification settings - Fork 437
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #735 from neuropsychology/feature_read_video
[Feature] read_video() function read video files into array (mp4)
- Loading branch information
Showing
2 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
# -*- coding: utf-8 -*- | ||
import numpy as np | ||
|
||
|
||
def read_video(filename="video.mp4"): | ||
"""**Reads a video file into an array** | ||
Reads a video file (e.g., .mp4) into a numpy array of shape. This function requires OpenCV to | ||
be installed via the ``opencv-python`` package. | ||
Parameters | ||
---------- | ||
filename : str | ||
The path of a video file. | ||
Returns | ||
------- | ||
array | ||
numpy array of shape (frame, RGB-channel, height, width). | ||
int | ||
Sampling rate in frames per second. | ||
Examples | ||
-------- | ||
.. ipython:: python | ||
import neurokit2 as nk | ||
# videodata, sampling_rate = nk.read_video("video.mp4") | ||
""" | ||
# Try loading cv2 | ||
try: | ||
import cv2 | ||
except ImportError: | ||
raise ImportError( | ||
"The 'cv2' module is required for this function to run. ", | ||
"Please install it first (`pip install opencv-python`).", | ||
) | ||
|
||
capture = cv2.VideoCapture(filename) | ||
sampling_rate = int(capture.get(cv2.CAP_PROP_FPS)) | ||
|
||
frames = [] | ||
while capture.isOpened(): | ||
success, frame = capture.read() # By default frame is BGR | ||
if not success: | ||
break | ||
frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) # Convert to RGB | ||
capture.release() | ||
# Swap axes to be (frame, RGB-channel, height, width) | ||
return np.array(frames).swapaxes(3, 1).swapaxes(3, 2), sampling_rate |