opencv 采集水星摄像头的rtsp视频流

opencv 采集水星摄像头的rtsp视频流

opencv获取网络摄像头的视频流

opencv获取网络摄像头的视频流

水星摄像头

PDD 上图便宜,66块钱找了个网络摄像头,正好家里装修,重新布置了一下网线,准备给楼下车棚里面安装一个摄像头。

  1. 水星摄像头;
  2. 路由器:电信配的路由器限制ip,只能接8个ip,所以用以前的送的磊科路由器当第二层交换机,分配ip。
  3. 插上12v电,插上网线,去路由器里面找到IP。 192.168.2.16.
  4. 进入摄像头的设置界面,设置一下RTSP的端口号。 这样就能通过程序访问了。
    在这里插入图片描述
    5.视频地址流有两个,分别为:
高清
rtsp://用户名:密码@192.168.2.16:554/stream1
一般
rtsp://用户名:密码@192.168.2.16:554/stream2

6.coding

我用python调用 采集视频并且保存下来。

以下是代码:使用python3.8执行,需要提前安装opencv-python和numpy库。

import cv2 as cv
import time
import numpy
import os
import threading	#多线程
import datetime

# 创建文件方法:
def create_file(filename):
#         """
#         创建日志文件夹和日志文件
#         :param filename:
#         :return:
#         """
    path = filename[0:filename.rfind("/")]
    if not os.path.isdir(path):  # 无文件夹时创建
        os.makedirs(path)
    if not os.path.isfile(filename):  # 无文件时创建
        fd = open(filename, mode="w", encoding="utf-8")
        fd.close()
    else:
       pass


def get_file_list(file_path):
    """
    :param file_path: the file path where you want to get file
    :return: list, files sorted by name
    """
    dir_list = os.listdir(file_path)
    if not dir_list:
        return
    else:
        # 注意,这里使用lambda表达式,将文件按照最后修改时间顺序升序排列
        # os.path.getmtime() 函数是获取文件最后修改时间
        # os.path.getctime() 函数是获取文件最后创建时间
        dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))
        #dir_list = sorted(dir_list, key=lambda x: int(x[:-4]))  # 按名称排序
        # print(dir_list)
        return dir_list

def SaveVideo():
        fpsize = os.path.getsize('/capturevideo/2020-06-28-17-04.avi') / 1024
        if fpsize >= 150.0: #大于150KB的视频需要压缩
            if '/capturevideo/2020-06-28-17-04.avi':
                compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline  -crf 23 -acodec aac -b:a 32k -strict -5 {}".format('/capturevideo/2020-06-28-17-04.avi','/capturevideo/2020-06-28-17-041.avi')
                isRun = os.system(compress)
            else:
                print(" ")
                #compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline  -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(self.fileInputPath, self.fileInputPath)
                #isRun = os.system(compress)
            if isRun != 0:
                return (isRun,"没有安装ffmpeg")
            return True
        else:
            return True

def Compress_Video():
    # 异步保存打开下面的代码,注释同步保存的代码
    thr = threading.Thread(target=SaveVideo)
    thr.start()
    #下面为同步代码
    # fpsize = os.path.getsize(self.fileInputPath) / 1024
    # if fpsize >= 150.0:  # 大于150KB的视频需要压缩
    #     compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline  -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(
    #         self.fileInputPath, self.fileOutPath)
    #     isRun = os.system(compress)
    #     if isRun != 0:
    #         return (isRun, "没有安装ffmpeg")
    #     return True
    # else:
    #     return True
camera = cv.VideoCapture("rtsp://guyang:a@1234567@192.168.2.16:554/stream2")
# camera=cv.VideoCapture(0) #获取摄像头
fps=camera.get(cv.CAP_PROP_FPS) #获取帧率
numFramesRemaining=1*fps; #z
width=int(camera.get(cv.CAP_PROP_FRAME_WIDTH)) #一定要转int 否则是浮点数
height=int(camera.get(cv.CAP_PROP_FRAME_HEIGHT))
print(width)
print(height)
size=(width,height) #大小
# 格式化成2016-03-20 11:45:39形式
success,frame=camera.read()#只写10帧
# print (time.strftime("%Y-%m-%d-%H-%M", time.localtime())) 
# newfilename=time.strftime("%Y-%m-%d-%H-%M", time.localtime())+'.avi'
# newrootpath = '/capturevideo/'
# newfilefullname=newrootpath+ newfilename
#Compress_Video()
while True:
    print (time.strftime("%Y-%m-%d-%H-%M", time.localtime())) 
    newfilename=time.strftime("%Y-%m-%d-%H-%M", time.localtime())+'.flv'
    newrootpath = '/capturevideo/'
    newfilefullname=newrootpath+ newfilename
    if os.path.exists(newfilefullname):
        # VWirte=cv.VideoWriter(newfilefullname,cv.VideoWriter_fourcc('I','4','2','0'),fps,size) #初始化文件写入 文件名 编码解码器 帧率 文件大小
        VWirte=cv.VideoWriter(newfilefullname,cv.VideoWriter_fourcc("F", "L", "V", "1"),fps,size) #初始化文件写入 文件名 编码解码器 帧率 文件大小
        while True:
            VWirte.write(frame)    
            success,frame=camera.read()
            numFramesRemaining-=1
            if (time.strftime("%Y-%m-%d-%H-%M", time.localtime()) not in  newfilename):
                break
        VWirte.release()
    else:
        if success == False:
            while not success:
                camera = cv.VideoCapture("rtsp://guyang:a@1234567@192.168.2.16:554/stream2")
                success,frame=camera.read()
        # print("   ")
        # print (time.strftime("%Y-%m-%d-%H-%M", time.localtime())) 
        # newfilename=time.strftime("%Y-%m-%d-%H-%M", time.localtime())+'.avi'
        # newrootpath = '/capturevideo/'
        # newfilefullname=newrootpath+ newfilename
        create_file(newfilefullname)
        filelist = get_file_list(newrootpath)
        for filename in filelist:
            lastupdatetime = os.path.getmtime(os.path.join(newrootpath, filename))
            d1 = datetime.datetime.now()
            d3 = d1 + datetime.timedelta(hours=-36)
            threeDaysAgoTimeStamp = int(time.mktime(d3.timetuple()))

            # timeArray = time.localtime(lastupdatetime)
            if lastupdatetime < threeDaysAgoTimeStamp:
                if os.path.exists(os.path.join(newrootpath, filename)):  # 如果文件存在
                    # 删除文件,可使用以下两种方法。
                    os.remove(os.path.join(newrootpath, filename))  
                    #os.unlink(path)
                else:
                    print('no such file:%s'%os.path.join(newrootpath, filename))  # 则返回文件不存在
            else:
                break
            #if lastupdatetime<time.time():

        # for root, dirs, files in os.walk(newrootpath):  
        #     print(root) #当前目录路径  
        #     print(dirs) #当前路径下所有子目录  
        #     print(files) #当前路径下所有非目录子文件  

time.sleep(1) #y延迟一秒关闭摄像头 否则会出现 terminating async callback 异步处理错误
camera.release() #释放摄像头
print('ok')

'''
 编码器常用的几种:
 cv2.VideoWriter_fourcc("I", "4", "2", "0") 
     压缩的yuv颜色编码器,4:2:0色彩度子采样 兼容性好,产生很大的视频 avi
 cv2.VideoWriter_fourcc("P", I", "M", "1")
     采用mpeg-1编码,文件为avi
 cv2.VideoWriter_fourcc("X", "V", "T", "D")
     采用mpeg-4编码,得到视频大小平均 拓展名avi
 cv2.VideoWriter_fourcc("T", "H", "E", "O")
     Ogg Vorbis, 拓展名为ogv
 cv2.VideoWriter_fourcc("F", "L", "V", "1")
     FLASH视频,拓展名为.flv
 '''

结果会保存在C盘的 C:\capturevideo 这个文件夹下面。
我为了通用才这样写,可以自行修改。
结果如下:

在这里插入图片描述
我是要把它做成24小时不间断采集视频的功能的话还需要改进一下内容:
1.压缩视频文件,10M一分钟文件内容太大。
2.自动删除前三天的视频内容。

算是留个坑,以后可能会填上。
以上是全部内容,本文结束。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值