[TOC]

opencv

opencv既可以从视频文件读取,也可以从视频设备上获取

install

pip install opencv-python

how to use

import cv2
# video_capture = cv2.VideoCapture("/home/alex/1.mp4")
# video_capture = cv.CaptureFromFile('rtsp://192.168.1.2:8080/out.h264')
video_capture = cv2.VideoCapture(0)
while True:
    _, frame = video_capture.read()
    cv2.imshow("image", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

可以从本地文件,视频设备,或者远程视频流中获取视频信号。

# 查看本地视频设备号
$ ls /dev/video*
/dev/video0

常见实用示例

# 图片读写
def image_detector(self, imname, wait=0):
    # 读取图片
    image = cv2.imread(imname)
    
    # 得到新的图片image
    result = self.detect(image)
    self.draw_result(image, result)
    
    # 显示图片
    # cv2.imshow('Image', image)
    # cv2.waitKey(wait)
    
    # 保存图片
    cv2.imwrite(imname.replace(".jpg", "_result.jpg"), image)

# 写入视频
def camera_detector(self, cap, wait=10):
	# 获取 原视频的fps,fourcc编码,height,wieght等信息
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    # fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    weidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    print("fourcc: ", fourcc)
    
    # 创建新的写入writer
    videowriter = cv2.VideoWriter('test/test.avi', fourcc, fps, (weidth, height))
    
    # 读取一帧图片
    ret, frame = cap.read()
    
    while frame is not None:
        # 得到新的图片image
        result = self.detect(frame)
        self.draw_result(frame, result)
        # cv2.imshow('Camera', frame)
        # if cv2.waitKey(wait) & 0xFF == ord('q'):
        #     break
		
        # 写入一帧图片
        videowriter.write(frame)
        
        # 读取下一帧图片
        ret, frame = cap.read()
    
    # 释放writer
    videowriter.release()

# 调用 camera_detector
cap = cv2.VideoCapture(video_read)
detector.camera_detector(cap, wait=1)

opencv mac error

正常情况下,在mac上面使用opencv是没有问题的,但是在Python子进程中使用opencv会发现子进程的代码会无厘头的没有结果。参考 这里 ,不要问我怎么知道的 /(ㄒoㄒ)/~~

解决办法就是避开咯,例如:

# 转灰度图
gray_img = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
gray_img = np.dot(img_rgb[..., :3], [0.299, 0.587, 0.114])

# bgr 转 rgb
img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
img_rgb = image[:, :, ::-1]

# cv2.mean --> np.mean
# cv2.copyMakeBorder --> np.pad