最近在做一个手指追踪,涉及到opencv。一开始选了个基于nodejs的opencv项目,不过环境配置项目的examples死活无法运行,可能和我macOS自己升级了catalina测试版有关。不过倒是了解了不少关于npm的用法(不过感觉npm还是没有pip方便)。
那就还是回归熟悉的Python吧。
关于Python版本的opencv,有个很棒的tutorial。地址
Opencv4在Python3.6上的安装
这部分网上很多博客教程用Homebrew装,之后又是一堆复杂的操作,创建软链接什么的。其实如果只想要Python支持opencv十分简单。
安装基础功能模块:
1pip install opencv-python
安装contrib modules:
1pip install opencv-contrib-python
具体可以参考
之后尝试import cv2,如果成功就代表安装成功。
cv2的Video相关
VideoCapture()
1.cap = cv2.VideoCapture(0)
VideoCapture()中参数是0,表示打开笔记本的内置摄像头,参数是视频文件路径则打开视频,如cap = cv2.VideoCapture("../test.avi")
2.ret, frame = capture.read()
1
2
3
4
5
6
7
8
9
10
11# 打开摄像头并灰度化显示
import cv2
capture = cv2.VideoCapture(0)
while(True):
# 获取一帧
ret, frame = capture.read()
# 将这帧转换为灰度图
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
if cv2.waitKey(1) == ord('q'):
break`
3.cap.get(propId) 获取视频属性
4.cap.set(propId,value)设置视频属性。
至于这边的propId是视频属性的id,分为18个不同的属性,详情参考上面的官方文档
VideoWriter()
ffmpeg视频编码里面适用于macOS的有对应mp4的'm', 'p', '4', 'v'和对应avi的'M','J','P','G'
同时设置的时候frame_width和frame_height用get方法获取,自己定义具体数值,可能录下的文件无法正常播放。
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
43import 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()