pycharm已经安装了cv2库,直接import cv2即可。
测试代码:
import cv2
import numpy as np
img = cv2.imread('D:\lena.jpg')
cv2.imshow('lena",img)
cv2.waitKey(10000)
cv2.VideoCapture(0) 读取笔记本内置摄像头视频
cv2.VideoCapture('/path/to/your/video.mp4') 读取本地文件
cap = cv2.VideoCapture("rtsp://admin:admin@192.168.2.64:554//Streaming/Channels/1") 读实时视频流,代码如下:
import cv2
cap = cv2.VideoCapture("rtsp://admin:admin@192.168.2.64:554//Streaming/Channels/1")
print cap.isOpened()
while cap.isOpened():
ret,frame = cap.read()
cv2.imshow("frame",frame)
cv2.waitKey(1)
播放视频:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(cap.isOpened()):
# 从摄像头读取一帧,ret是表明成功与否
ret, frame = cap.read()
if ret:
#处理得到的帧,这里将其翻转
frame = cv2.flip(frame,0)
cv2.imshow('frame',frame)
else:
break
# 监听键盘,按下q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
##释放
cap.release()
cv2.destroyAllWindows()
注意:frame是array数组,其格式为480,640,3(举例),和matlab格式不同。
使用函数cap.get(propId) 来获得视频的参数信息
有时候需要在视频的某一个区域进行标注,因此需用矩形标注并返回2个点的坐标,程序示例:
import cv2
import numpy as np
import time
img = cv2.imread('D://lena.jpg')
# 当鼠标按下时变为True
drawing = False
# 如果mode 为true 绘制矩形。按下'm' 变成绘制曲线。
mode = True
ix, iy = -1, -1
# 创建回调函数
def draw_circle(event, x, y, flags, param):
global ix, iy, drawing, mode
# 当按下左键是返回起始位置坐标
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
# 当鼠标左键按下并移动是绘制图形。event 可以查看移动,flag 查看是否按下
elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
if drawing == True:
if mode == True:
cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 1)
else:
# 绘制圆圈,小圆点连在一起就成了线
cv2.circle(img, (x, y), 30, (0, 0, 255), 1)
# 当鼠标松开停止绘画。
elif event == cv2.EVENT_LBUTTONUP:
drawing == False
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_circle)
while (1):
cv2.imshow('image', img)
k = cv2.waitKey(1)
if k == ord('m'):
mode = not mode
elif k == ord('q'):
cv2.destroyAllWindows()
break