码迷,mamicode.com
首页 > 其他好文 > 详细

视频的画框和保存

时间:2019-05-09 13:48:10      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:nal   uri   wait   element   put   nump   col   bre   sdi   

这是来自一段动态物体检测的代码,首先将动态物体检测出来并画框,然后将画框的图片以视频的形式保存下来。

import cv2
import numpy as np

camera = cv2.VideoCapture("F:/7.mp4")

# 判断视频是否打开
if (camera.isOpened()):
    print(Open)
else:
    print(摄像头未打开)

# 测试用,查看视频size
size = (int(camera.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print(size:+repr(size))
 
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 4))
kernel = np.ones((5, 5), np.uint8)
background = None
a = 0
b = 0

fourcc = cv2.VideoWriter_fourcc(M, P, 4, 2)
out = cv2.VideoWriter(F:\output0.avi,fourcc, 20.0, (1280,720))
while True:
    # 读取视频流
    grabbed, frame_lwpCV = camera.read()

    if frame_lwpCV is None:
        break
    gray_lwpCV = cv2.cvtColor(frame_lwpCV, cv2.COLOR_BGR2GRAY)

    gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (21, 21), 0)
 
    # 将第一帧设置为整个输入的背景
    if background is None:
        background = gray_lwpCV 
        continue

    diff = cv2.absdiff(gray_lwpCV, background)
    background = gray_lwpCV

    diff = cv2.threshold(diff, 9, 255, cv2.THRESH_BINARY)[1]
    diff = cv2.dilate(diff, es, iterations=2) # 形态学膨胀

    # 显示矩形框
     # 该函数计算一幅图像中目标的轮廓
    image, contours, hierarchy = cv2.findContours(diff.copy(), 
                                                  cv2.RETR_EXTERNAL, 
                                                  cv2.CHAIN_APPROX_SIMPLE)    
    aaa = 0
    for c in contours:
        aaa += 1
        if cv2.contourArea(c) < 2000: # 对于矩形区域,只显示大于给定阈值的轮廓
            continue

        (x, y, w, h) = cv2.boundingRect(c) # 该函数计算矩形的边界框
        #print(x, y, w, h)
        cv2.rectangle(frame_lwpCV, (x, y), (x+w, y+h), (0, 255, 0), 2)

    out.write(frame_lwpCV)
    cv2.imshow(contours, frame_lwpCV)
    cv2.imshow(dis, diff)
 
    key = cv2.waitKey(1) & 0xFF
    # 按‘q‘健退出循环
    if key == ord(q):
        break

camera.release()
cv2.destroyAllWindows()

 

视频的画框和保存

标签:nal   uri   wait   element   put   nump   col   bre   sdi   

原文地址:https://www.cnblogs.com/czz0508/p/10837773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!