首页 > 编程语言 >PYTHON 视频时间检测

PYTHON 视频时间检测

时间:2023-04-08 09:04:39浏览次数:33  
标签:视频 get PYTHON 检测 frame cv2 camera print lwpCV

import cv2

cameraCapture = cv2.VideoCapture('./1/11.mp4')

success, frame = cameraCapture.read()
while success:
    if cv2.waitKey(1) == 27:
        break
    cv2.imshow('Test camera', frame)
    success, frame = cameraCapture.read()
    milliseconds = cameraCapture.get(cv2.CAP_PROP_POS_MSEC)

    seconds = milliseconds//1000
    milliseconds = milliseconds%1000
    minutes = 0
    hours = 0
    if seconds >= 60:
        minutes = seconds//60
        seconds = seconds % 60

    if minutes >= 60:
        hours = minutes//60
        minutes = minutes % 60

    print(int(hours), int(minutes), int(seconds), int(milliseconds))

cv2.destroyAllWindows()
cameraCapture.release()

 

#!/usr/bin/env python
# coding: utf-8
# @author: sSWans
# @file: main.py
# @time: 2018/1/11 15:54
 
import os,sys
import random
from _datetime import datetime
 
import cv2
 
path = 'D:\\C理论\\ti'
 
 
# 遍历目录下的视频文件
def get_files(fpath):
    files_list = []
    for i in os.listdir(fpath):
        files_list.append(os.path.join(fpath, i))
    return files_list
 
 
# 视频处理
def process(file, fname):
    # camera = cv2.VideoCapture(0)  # 参数0表示第一个摄像头
    camera = cv2.VideoCapture(file)
    # 参数设置,监测矩形区域
    rectangleX = 750  # 矩形最左点x坐标
    rectangleXCols = 340  # 矩形x轴上的长度
    rectangleY = 320  # 矩形最上点y坐标
    rectangleYCols = 30  # 矩形y轴上的长度
    KeyFrame = 50  # 取关键帧的间隔数,根据视频的帧率设置,我的视频是16FPS
    counter = 1  # 取帧计数器
    pre_frame = None  # 总是取视频流前一帧做为背景相对下一帧进行比较
 
    # 判断视频是否打开
    if not camera.isOpened():
        print('视频文件打开失败!')
    
    width = int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT))
    print('视频尺寸(高,宽):', height, width)
    fps = camera.get(cv2.CAP_PROP_FPS)
    print("fps:",fps)
    fpsA = camera.get(cv2.CAP_PROP_POS_MSEC)
    print("fpsA:",fpsA)
    if rectangleXCols == 0:
        rectangleXCols = width - rectangleX
    if rectangleYCols == 0:
        rectangleYCols = height - rectangleY
    start_time = datetime.now()
    print('{} 开始处理文件: {}'.format(start_time.strftime('%H:%M:%S'), fname))
    while True:
        grabbed, frame_lwpCV = camera.read()  # 读取视频流
        if grabbed:
            fpsA = camera.get(cv2.CAP_PROP_POS_MSEC)
            #print("fpsA:",fpsA)
            if counter % KeyFrame == 0:
                # if not grabbed:
                #     print('{} 完成处理文件: {} 。。。  '.format(datetime.now().strftime('%H:%M:%S'),fname))
                #     break
                gray_lwpCV = cv2.cvtColor(frame_lwpCV, cv2.COLOR_BGR2GRAY)  # 转灰度图
                gray_lwpCV = gray_lwpCV[rectangleY:rectangleY + rectangleYCols, rectangleX:rectangleX + rectangleXCols]
                lwpCV_box = cv2.rectangle(frame_lwpCV, (rectangleX, rectangleY),
                                          (rectangleX + rectangleXCols, rectangleY + rectangleYCols), (0, 255, 0),
                                          2)  # 用绿色矩形框显示监测区域
                # cv2.imshow('lwpCVWindow', frame_lwpCV)  # 显示视频播放窗口,开启消耗时间大概是3倍
                gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (21, 21), 0)
                if pre_frame is None:
                    pre_frame = gray_lwpCV
                else:
                    img_delta = cv2.absdiff(pre_frame, gray_lwpCV)
                    thresh = cv2.threshold(img_delta, 25, 255, cv2.THRESH_BINARY)[1]
                    thresh = cv2.dilate(thresh, None, iterations=2)
                    #image, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
                    contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
##                    print(contours)
##                    print(hierarchy)
##                    sys.exit(0)
                    for x in contours:
                        if cv2.contourArea(x) < 1000:  # 设置敏感度
                            continue
                        else:
##                            cv2.imwrite(
##                                'image/' + fname + '_' + datetime.now().strftime('%H%M%S') + '_' + str(
##                                    random.randrange(0, 9999)) + '.jpg',
##                                frame_lwpCV)
                            cv2.imwrite(
                                'image/' + fname + '_' + str(fpsA) + '.jpg',
                                frame_lwpCV)
                            # print("监测到移动物体。。。  ", datetime.now().strftime('%H:%M:%S'))
                            break
                    pre_frame = gray_lwpCV
            counter += 1
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                break
        else:
            end_time = datetime.now()
            print('{} 完成处理文件: {}  耗时:{}'.format(end_time.strftime('%H:%M:%S'), fname, end_time - start_time))
            break
    camera.release()
    # cv2.destroyAllWindows() #  与上面的imshow对应
 
 
for file in get_files(path):
    fname = file.split('\\')[-1].replace('.mp4', '')
    process(file, fname)

 

import cv2
#视频帧率(Frame rate)是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second,简:FPS)或“赫兹”(Hz)。此词多用于影视制作和电子游戏。
cap = cv2.VideoCapture('d:\\python37\\1\\11.mp4')
fps = cap.get(cv2.CAP_PROP_FPS)
print(fps)
timestamps = [cap.get(cv2.CAP_PROP_POS_MSEC)]
calc_timestamps = [0.0]
 
while(cap.isOpened()):
    frame_exists, curr_frame = cap.read()
    if frame_exists:
        timestamps.append(cap.get(cv2.CAP_PROP_POS_MSEC))
        calc_timestamps.append(calc_timestamps[-1] + 1000/fps)
    else:
        break
 
cap.release()
 
for i, (ts, cts) in enumerate(zip(timestamps, calc_timestamps)):
    print('Frame %d difference:'%i, abs(ts - cts))

 

标签:视频,get,PYTHON,检测,frame,cv2,camera,print,lwpCV
From: https://www.cnblogs.com/xkdn/p/17297868.html

相关文章

  • python之装饰器
    ###################                    #######################......
  • python远程控制windows机器
    1,进入cmd,输入winrmquickconfig-q,如果出现下图报错,把电脑公网设置为专网   设置专网步骤:win+i,网络和internet,状态,属性  2,检查winrm服务监听状态;进入cmd,输入winrmewinrm/config/listener;记录端口号Port值,后面会用到     3,查看winrm配置信息(可选)通......
  • Python实现Json文件转为点表示法(Dot-Notation)
    将Json转换为点表示法有很多用途,本文基于Python实现一个简单demo来转换。【原文见我的博客,如有更新请博客园的不一定及时同步改:https://blog.jfz.me/2023/python-json-to-dot-notation.html】{"vehicle":{"car":{"bmw":true,"audi"......
  • 【进阶11】【自学笔记】Python _解包的操作
    一、Python解包定义Python解包是指将一个可迭代对象(如列表、元组、字典等)中的元素分别赋值给多个变量的过程。解包可以通过在变量前添加星号`*`来实现,也可以通过在变量前添加双星号`**`来实现字典解包。解包可以简化代码,使代码更加清晰易懂。二、解包实例1、最简单的解包......
  • python相关命令
    1,查看此电脑是否安装python,进入cmd,输入python  2,查看python安装的版本,进入cmd,输入python--version  3,查看python安装的路径,进入cmd,输入py-0p ......
  • python装饰器
    参考:https://www.bilibili.com/video/BV1DW4y147Hm/感觉很久没有学到python的一些新玩法了,参考B站教程在Python中,装饰器(Decorator)是一种用于修改函数或者类的行为的语法结构。装饰器允许我们在不修改函数定义的情况下,动态地修改函数的行为,从而实现更加灵活和可重用的代码。......
  • Python常见的数据结构
    Python常见的数据结构包括: 列表(List):一种有序的、可变的序列数据结构,可以存储不同类型的元素。支持添加、删除、修改和查询元素等操作。 元组(Tuple):与列表类似,但元组是不可变的,一旦创建就无法修改。元组通常用于表示一个具有一定结构的记录。 集合(Set):一种无序的、不重复的......
  • flask-day5——python项目高并发异步部署、uwsgi启动python的web项目不要使用全局变量
    目录一、python项目高并发异步部署二、uwsgi启动Python的Web项目中不要使用全局变量三、信号3.1flask信号3.2django信号四、微服务的概念五、flask-script六、sqlalchemy快速使用七、sqlalchemy快速使用4.1原生操作的快速使用八、创建操作数据表九、作业1、什么是猴子补丁,有什......
  • python opencv line
    pythonopencvline importcv2#Loadanimageimg=cv2.imread("image1.jpg")#Drawaredlinefrom(0,0)to(100,100)withathicknessof5pixelscv2.line(img,(0,0),(100,100),(0,0,255),5)#Displaytheimagecv2.imshow("Im......
  • python-xpath,爬取猪八戒网(半成品)
    数据未进行清洗xpath  / 层级关系text() 拿文本//    https://blog.csdn.net/KELLENSHAW/article/details/127877476爬取https://task.zbj.com/hall/list-all-0-p1?kw=HTML先定位小盒子的div然后通过检查,xpath://*[@id="hall-list-wrap"]/div[4]/div[1]/div[1]/div[1]/d......