一、功能

1、实现多个摄像头同时获取图像,并保存到个各自目录

2、摄像头类别包括海康RSTP协议网络摄像头和普通USB摄像头

3、可自动和手动保存图片

二、注意事项

1.python可以使用multiprocessing多进程读取多个摄像头,但是multiprocessing自带的队列在交换数据时内存不会释放(没搞明白),所以使用了python threading多线程配合python自带的队列queue交换数据。

三、代码与演示

"""
@ capture multiple cameras images to different folder
"""import cv2
import numpy as np
import time
import os
import threading
from time import ctime,sleep
import queueabspath = os.path.abspath(os.path.dirname(__file__))class threadCameraRSTP (threading.Thread):"""Hikvision camera@user   User name.@passwd User password.@ip     Camera ip name.@queue  Output queue."""def __init__(self, user, passwd, ip, queue):threading.Thread.__init__(self)self.user = userself.passwd = passwdself.ip = ipself.q = queuedef run(self):access = "rtsp://%s:%s@%s//Streaming/Channels/1"  % (self.user, self.passwd, self.ip)cap = cv2.VideoCapture(access)if cap.isOpened():print('camera ' + self.ip + " connected.")while True:ret, img = cap.read()if ret:self.q.put(img)self.q.get() if self.q.qsize() > 2 else time.sleep(0.01)class threadCameraUSB (threading.Thread):"""usb camera@access   Usb descriptor.@queue    Output queue."""def __init__(self, access, queue):threading.Thread.__init__(self)self.access = accessself.q = queuedef run(self):cap = cv2.VideoCapture(self.access)if cap.isOpened():print('camera usb ' + str(self.access) + " connected.")while True:ret, img = cap.read()if ret:self.q.put(img)self.q.get() if self.q.qsize() > 2 else time.sleep(0.01)def image_save(queueImage, queueCmd, dstDir, startNum, identification, display=True):"""save image@queueImage   Image input queue.@queueCmd     Command input queue.@dstDir       Folder storing images.@startNum     Images number.@identification     Image show name.@display       Whether display image."""count = startNumif display:cv2.namedWindow(identification, 0)img = Nonewhile(True):if queueCmd.qsize() > 0:cmd = queueCmd.get()if cmd == 's':while True:if queueImage.qsize() > 0:img = queueImage.get()cv2.imwrite(dstDir + '/' + ('%s' % count) + ".png", img)print('n' + identification + ' save img ' + str(count) + ' OK')count += 1breakif queueImage.qsize() > 1:img = queueImage.get()if display:cv2.imshow(identification, img)cv2.waitKey(1)def captureMutipleCamera(camera_access=[], start_Num=0, display=True):"""save image@camera_access  All paremeters to capture and save the image, list, the format lile,[["HIKVISION", "admin", "aaron20127", "192.168.0.111", 'D:/data/image'],["USB", 0, 'D:/data/image']]@start_Num     Image show name.@display       Whether display image."""# there must import queue, I don't know whyimport queuequeueCmds = []thread_ids = []## 1.start camera threads and save threadsfor camera in camera_access:identification = NonecameraThread = NonedstDir = NonequeueImage = queue.Queue(maxsize=4)queueCmd = queue.Queue(maxsize=4)if camera[0] == "HIKVISION":identification = camera[3]dstDir = camera[4]cameraThread = threadCameraRSTP(camera[1], camera[2], camera[3], queueImage)elif camera[0] == "USB":identification = "USB " + str(camera[1])dstDir = camera[2]cameraThread = threadCameraUSB(camera[1], queueImage)# camera threadthread_ids.append(cameraThread)# save image threadthread_ids.append(threading.Thread(target=image_save,args=(queueImage, queueCmd, dstDir, start_Num, identification, display)))# cmd input queuequeueCmds.append(queueCmd)for thread in thread_ids:thread.daemon = Truethread.start()## 2. Enter enter to save imagetime.sleep(4)print("Please confirm the image saving mode:")print(" -- p (Press enter to save the image manually.)")print(" -- a (Automatically save pictures at intervals.)")mode = input()while(not (mode == 'p' or mode == 'a')):print("Input error, please input p or a.")mode = input()intervel = 5if mode == 'a':print('')print("Autosave mode !")print("Please input the intervals to autosave image times/seconds.")intervel = input()while(not intervel.isdigit()):print("")print("Please input a positive integer.")intervel = input()print("")print("Start auto saving ... n")intervals_time = 1.0 / int(intervel)start = time.time()while(True):if (time.time() - start) > intervals_time:for queue in queueCmds:if queue.qsize() == 0:queue.put('s')start = time.time()else:print('')print("Enter mode !")print("Please press 'Enter' to start saving ... n")while(True):if(input() == ''):for queue in queueCmds:if queue.qsize() == 0:queue.put('s')if __name__ == '__main__':"""example to capture camera"""camera_access = [["HIKVISION", "admin", "12345678", "192.168.0.111", abspath + '/image/left'],["HIKVISION", "admin", "12345678", "192.168.0.112", abspath + '/image/right'],["USB", 0,  abspath + '/image/usb']]captureMutipleCamera(camera_access, start_Num = 0, display=True)

网络摄像头转usb接口_同时读取多个摄像头数据(包括海康网络摄像头和USB摄像头)...相关推荐

  1. 海康网络摄像头忘记密码_不要忘记网络性能

    海康网络摄像头忘记密码 Amazon released a famous statement in the late 2000s stating that every hundred millisec ...

  2. JavaCV音视频开发宝典:使用JavaCV读取海康平台或海康网络摄像头sdk回调录像回放视频PS码流并解析预览图像

    <JavaCV音视频开发宝典>专栏目录导航 <JavaCV音视频开发宝典>专栏介绍和目录 ​ 前言 上一章中<JavaCV音视频开发宝典:使用JavaCV读取海康平台或海 ...

  3. ubuntu 使用opencv 获取海康网络摄像头视频流

    1. 前言 之前在windows平台下使用opencv获取海康网络摄像头的视频流,但是不管怎么设置都无法登录摄像头,导致无法获取摄像头的视频流,但是换到ubuntu又正常了,主要是设置rtsp的格式, ...

  4. [Rtsp]海康网络摄像头基于RTSP协议的windows平台监控

    [Rtsp]海康网络摄像头基于RTSP协议的windows平台监控 基于RTSP协议的windows平台监控. 1.  基于RTSP协议的windows平台监控. 1.1 选取海康网络摄像头(支持RT ...

  5. 海康网络摄像头android,海康网络摄像头的Android端Demo

    [实例简介]海康网络摄像头的Android端Demo; 可实现通过wifi实时读取并显示摄像头捕捉的画面; [实例截图] [核心代码] /** * DemoActivity Class * @auth ...

  6. 海康网络摄像头实时视频预览(流媒体转码推流 red5,nginx-rtmp,ffmpeg)

    海康网络摄像头实时视频预览(流媒体转码推流 red5,nginx-rtmp,ffmpeg) 实现思路 获取摄像头rtsp流→流媒体拉流转码推流成rtmp流(网页具备flash可播放)→根据rtmp流地 ...

  7. 多路海康网络摄像头数据实时回调(采用软解码方式)

    由于项目中需要访问多路海康摄像头的原始图像进行相关处理,搜索了大量的博客,对于多路海康摄像头回调都没有写的很清楚明白,看到此博客的你,静下心来研读下面的内容,你将会很容易调取多路海康网络摄像头. (1 ...

  8. 安防RTSP协议摄像头实现WEB端无插件直播流媒体服务EasyNVR实现海康大华宇视摄像头网页播放的方法

    背景分析:微信直播的兴起 进入移动互联网时代以来,企业微信公众号已成为除官网以外非常重要的宣传渠道,当3.2亿直播用户与9亿微信用户的势能累加,在微信上开启直播已成为越来越多企业的必然选择. Easy ...

  9. 传统大华海康宇视安防摄像头RTSP流如何转webrtc直播低延时无插件浏览器视频播放

    传统大华海康宇视安防摄像头RTSP流如何转webrtc直播低延时无插件浏览器视频播放 1.问题场景 2.WEBRTC延时对比 3.LiveNVR支持WEBRTC输出 4.RTSP/HLS/FLV/RT ...

最新文章

  1. WinCE5.0中应用程序如何直接写屏
  2. getchar()函数的返回值赋给char型,用if(ch=getchar() != EOF)测试,输入ctrl+z同样可以结束循环的分析...
  3. 关于线程池ExecutorService的shutdown()与shutdownNow()方法的区别
  4. python一:hello world
  5. Ubuntu 进入、退出命令行的快捷键
  6. 解决Linux报错:/bin/bash^M: 坏的解释器: 没有那个文件或目录
  7. java链表变成字符串,leetcode算法题解(Java版)-6-链表,字符串
  8. (一二四)给类对象赋值、以及类对象的返回值
  9. 使用 docker 命令不用加 sudo
  10. python json传参数可以传对象吗_廖雪峰的python系列教程(52)——IO编程之序列化...
  11. OkHttp之BridgeInterceptor简单分析
  12. 2020华为软挑总结
  13. matlab白噪音wav,为声音文件添加白噪音
  14. vrp系统和linux区别,华为VRP-文件系统基础
  15. nvidia驱动程序下载类型怎么选?
  16. 水溶性/脂溶性/Cy3/Cy3.5/Cy5 NHS ester 染料在活体成像中的应用
  17. 小红书笔记无法展示是什么原因?让我们来看看吧
  18. 32位系统无法运行64位系统安装文件
  19. 仿淘宝ViewPager左滑加载详情界面
  20. IDEA插件系列(19):EduTools插件——学习编程语言

热门文章

  1. 有关判读flex 模板载入是否结束的一些问题。
  2. 昨天申请了这个blog,也就是半个多小时之前,eh,这是我的第几个blog了?
  3. 导出无法正常启动的VMware虚拟机中的文件
  4. C++之queue和dequeu用法
  5. 解决:/system/bin/sh: /system/bin/test-ndk: not executable: magic 7F45报错
  6. Android HIDL第一个HelloWorld demo
  7. Vue之webpack之Babel
  8. centos报acpi 错误解决方法实测有用
  9. lintOnSave设置
  10. Http请求返回最外层的模型