可以参考官方接口文档:官方接口手册
提高FPS处理性能,参考:https://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/
https://towardsdatascience.com/@datitran
读取视频
封装了一个类,和使用方法如下:
class WebcamVideoStream:
def __init__(self, src, width, height):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
(self.grabbed, self.frame) = self.stream.read()
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
def start(self):
# start the thread to read frames from the video stream
Thread(target=self.update, args=()).start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
return
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# return the frame most recently read
return self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
# sources表示摄像头编号0,1,2...
video_capture = WebcamVideoStream(ConfigManager.get_sources(),
ConfigManager.get_width(),
ConfigManager.get_height()).start()
while True:
origin_frame = video_capture.read()
# 显示帧
cv2.imshow("video", origin_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
保存图像
# 第一个参数为文件名
cv2.imwrite('messigray.jpg', img)
默认imwrite会压缩图像,如果想保存高质量图像,需要加参数
[int( cv2.IMWRITE_JPEG_QUALITY), 100],如:
cv2.imwrite('messigray.jpg', img, [int( cv2.IMWRITE_JPEG_QUALITY), 100])
转换图像
# BGR转为RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# BGR转为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
获取某一个位置的b,g,r值
(b, g, r) = origin_frame[0, 0]
(b, g, r) = origin_frame[50, 100]
翻转图像
以下两行把图像翻转270度,4:3图像,翻转90度270度后可能会自动裁剪图片。所以,中心点我设的是(width/2, width/2)
M = cv2.getRotationMatrix2D((width/2, width/2), 270, 1)
while True:
ret, frame1 = cap.read()
frame = cv2.warpAffine(frame1, M, (width, width))
完整代码如下(翻转图像,并提取前景),如果找不到imutils。pip install imutils:
import argparse
import cv2
import numpy as np
import imutils
# construct the argument parser and parse the arguments
ag = argparse.ArgumentParser()
ag.add_argument("-v", "--video", help="source of the video")
ag.add_argument("-a", "--min-area", type=int, default=500, help="minimum area size")
args = vars(ag.parse_args())
source = "0"
if args.get("video", None) is None:
source = "0"
else:
source = args["video"]
min_area = args["min_area"]
cap = cv2.VideoCapture(int(source))
fgbg = cv2. createBackgroundSubtractorMOG2()
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
width = 800
height = 600
cap.set(3,width)
cap.set(4,width)
M = cv2.getRotationMatrix2D((width/2, width/2), 270, 1)
while True:
ret, frame1 = cap.read()
frame = cv2.warpAffine(frame1, M, (width, width))
#frame = cv2.resize()
fgmask = fgbg.apply(frame)
(_,cnts, _) = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
maxArea = 0
for c in cnts:
if cv2.contourArea(c) < 900:
(x, y, w, h) = (0,0,0,0)
continue
else:
m=c
(x, y, w, h) = cv2.boundingRect(m)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('original', frame)
cv2.imshow('fg', fgmask)
#cv2.imshow('normal', frame1)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
参考接口:
# read image
image = cv2.imread(source_path + "\\" + img)
# rotate image
rows,cols,_ = temp.shape
# rotate 45 degrees with 0.6 Scaling factor
M1 = cv2.getRotationMatrix2D((cols/2, rows/2), 90, 1)
image_1 = cv2.warpAffine(image, M1, (cols, rows))
# rotate 90 degrees with 0.6 Scaling factor
M2 = cv2.getRotationMatrix2D((cols/2, rows/2), 180, 1)
image_2 = cv2.warpAffine(image, M2, (cols, rows))
保存视频
试了好几种编码格式,Centos7上*"MJPG"这个是可以的
# fourcc = cv2.VideoWriter_fourcc(*'XVID')
# fourcc = cv2.VideoWriter_fourcc(*'X264')
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
# fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', '2')
out_video_name = "/home/trade_info/" + self.__cur_trade_id + "/video" + str(id) + ".avi"
out = cv2.VideoWriter(out_video_name, fourcc, 6.0, (valid_width, height))
video_capture = WebcamVideoStream(src, width, height).start()
while True:
ret, origin_frame = video_capture.read()
out.write(frame)
网友评论