从局域网监控到广域网实时监控的实现

news/2025/1/9 12:28:28/


目录

  • 1. 局域网视频监控
  • 2. 与云服务器远程通信
  • 3. 云服务器中转实现远程监控


1. 局域网视频监控

  • socket 实现
  • 测试可在同一台电脑运行
  • 条件:处在同一局域网,并知道被监控端的 ip
  • 观看监控视频时同步保存视频到本地


服务端 :等待接受视频信号

import socket
import cv2
import struct
import numpy
import threading
import timeclass Camera_Connect_Object(object):def __init__(self, TargetIP=('', 6666)): #端口可以自己选self.TargetIP = TargetIPself.resolution = (640, 480)self.img_fps = 25now_time = str(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())))fourcc = cv2.VideoWriter_fourcc(*'XVID')avi_name = now_timeself.out = cv2.VideoWriter(avi_name+ '.avi' ,fourcc, 25.0, (640,480))self.Server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.Server.bind(self.TargetIP)self.Server.listen(5)def RT_Image(self):self.client, self.addr = self.Server.accept()self.name = self.addr[0] + " Camera"print(self.name)while True:# time.sleep(0.3)  # sleep for 0.3 secondstempdata = self.client.recv(8)if len(tempdata) == 0:print("+1")continueinfo = struct.unpack('lhh', tempdata)buf_size = int(info[0])if buf_size:try:self.buf = b""self.temp_buf = self.bufwhile buf_size:self.temp_buf = self.client.recv(buf_size)buf_size -= len(self.temp_buf)self.buf += self.temp_bufdata = numpy.frombuffer(self.buf, dtype='uint8')self.image = cv2.imdecode(data, 1)print(self.image.shape)self.out.write(self.image)cv2.imshow(self.name, self.image)except Exception as e:print(e.args)passfinally:if cv2.waitKey(10) == 27:self.client.close()self.out.release()cv2.destroyAllWindows()breakdef Get_data(self):showThread = threading.Thread(target=self.RT_Image)showThread.start()showThread.join()if __name__ == '__main__':camera = Camera_Connect_Object()camera.Get_data()


客户端 :向服务端发送视频信号

import socket
import struct
import time
import cv2
import numpyclass Config(object):def __init__(self):self.TargetIP = ('192.168.xx.xxx', 6666) #填自己电脑的ipself.resolution = (640, 480)  # 分辨率self.img_fps = 25  # each second send picturesself.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.server.connect(self.TargetIP)self.img = ''self.img_data = ''def RT_Image(self):camera = cv2.VideoCapture(0)img_param = [int(cv2.IMWRITE_JPEG_QUALITY), self.img_fps]while True:time.sleep(0.1)  # sleep for 0.1 seconds_, self.img = camera.read()self.img = cv2.resize(self.img, self.resolution)_, img_encode = cv2.imencode('.jpg', self.img, img_param)img_code = numpy.array(img_encode)self.img_data = img_code.tostring()  # bytes datatry:packet = struct.pack(b'lhh', len(self.img_data), self.resolution[0],self.resolution[1])self.server.send(packet)self.server.send(self.img_data)except Exception as e:print(e.args)camera.release()returnif __name__ == '__main__':config = Config()config.RT_Image()


2. 与云服务器远程通信

  • socket 实现
  • 服务端在云服务器运行,等待客户端连接
  • 通信过程,客户端发送信息至云端,云端将接收到的信息返回到客户端,并加上系统本地时间


服务端 :接受客户端的消息并回复

import socket
import time# 创建一个tcp/ip协议的套接字
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)host = "172.17.xx.xx" #填写云服务器的私网 ip
port = 8888 #记得要先开放端口
buffer_size = 1024
address = (host, port)
# 开始绑定地址
tcpSocket.bind(address)
tcpSocket.listen(5)while True:print("服务器等待被连接中。。。。。")clientSock, client_addr = tcpSocket.accept()print("已经连接到客户端,连接地址:{0}".format(client_addr))try:while True:data = clientSock.recv(buffer_size)print("接收到客户端的数据为:{0}".format(str(data, encoding="utf8")))if data.upper() == "EXIT":breaknow_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())clientSock.send(bytes("时间:{0},接受的内容为:{1}".format(now_time, str(data, encoding="utf8")), encoding="utf8"))except Exception as e:print(e)finally:clientSock.close()tcpSocket.close()


客户端 :向服务器发送数据,也可接收服务器返回的数据

import socket
import time# 创建一个tcp/ip协议的套接字
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)host = "39.97.xx.xx" #填写自己的公网 ip
port = 8888 #与服务端的端口一致
buffer_size = 1024
address = (host, port)
# 开始连接服务器地址
clientSocket.connect(address)if clientSocket is None:print("无法连接当前的服务器!\n")
else:print("已经连接服务器---> oK\n")while True:data = input("(q 退出)发送数据到服务器:")if data== "q":clientSocket.send(bytes("EXIT", encoding="utf8"))# 关闭当前的客户端clientSocket.close()breakclientSocket.send(bytes(data, encoding="utf8"))# 接收服务器发送的数据data = clientSocket.recv(buffer_size)# 打印接收的数据print("服务器返回:{0}\n".format(str(data, encoding="utf8")))


3. 云服务器中转实现远程监控

  • 先在云服务器运行服务端,等待被连接
  • 云服务器可以接收被监控方客户端的视频信号,并保存为 avi 格式存放在云服务器上
  • 云服务器同样可以接收用户客户端的请求,将实时的视频信号转发给用户
  • 用户在远程观看视频的同时,视频也将被保存到本地
  • 顺序是这样的:服务端等待、相机连接到服务器并发送一帧画面、服务器接收一帧画面并保存为 avi 格式、用户连接到服务器查看正在传输的数据并保存视频到本地


客户端 1 :向服务器发送数据,经压缩的图像

import socket
import struct
import time
import cv2
import numpyclass Config(object):def __init__(self):self.TargetIP = ('39.97.xx.xx', 8888) #使用云服务器公网 ipself.resolution = (640, 480)  # 分辨率self.img_fps = 70  # each second send picturesself.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.server.connect(self.TargetIP)print('采集者已连接服务器!')def RT_Image(self):camera = cv2.VideoCapture(0)img_param = [int(cv2.IMWRITE_JPEG_QUALITY), self.img_fps]ret, frame = camera.read()while ret:time.sleep(0.1)  # sleep for 0.1 secondsret, frame = camera.read()frame = cv2.resize(frame, self.resolution)_, img_encode = cv2.imencode('.jpg', frame, img_param)img_code = numpy.array(img_encode)self.img_data = img_code.tostring()  # bytes datatry:buf_size = len(self.img_data)if buf_size>0 and buf_size<500000:packet = struct.pack(b'i',buf_size)self.server.send(packet)self.server.send(self.img_data)except Exception as e:print(e.args)camera.release()returnif __name__ == '__main__':config = Config()config.RT_Image()


客户端 2 :从服务器读取实时数据并解析,保存视频到本地

import socket
import struct
import time
import cv2
import numpy
import threading
import sysclass FromServer(object):def __init__(self):self.TargetIP = ('39.97.xx.xx', 9999) #公网 ip 端口不要与客户端 1 的重复了self.clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.clientSocket.connect(self.TargetIP)self.resolution = (640, 480)self.img_fps = 70def RT_Image(self):video_name = bytes.decode(struct.unpack('14s', (self.clientSocket.recv(14)))[0])fourcc = cv2.VideoWriter_fourcc(*'XVID')out = cv2.VideoWriter(video_name+ '.avi' ,fourcc, 35.0, (640,480))try:while True:tempdata = self.clientSocket.recv(4)if cv2.waitKey(10) == 27:self.clientSocket.close()out.release()sys.exit()breakif len(tempdata) == 4:info = struct.unpack('i', tempdata)buf_size = int(info[0])if buf_size>0 and buf_size<500000:try:buf = b""temp_buf = bufwhile buf_size:temp_buf = self.clientSocket.recv(buf_size)buf_size -= len(temp_buf)buf += temp_bufdata = numpy.frombuffer(buf, dtype='uint8')self.image = cv2.imdecode(data, 1)out.write(self.image)cv2.imshow(video_name, self.image)except Exception as e:print(e)passelse:buf_size = 0except Exception as e:self.clientSocket.close()out.release()def Get_data(self):showThread = threading.Thread(target=self.RT_Image)showThread.start()showThread.join()if __name__ == '__main__':data = FromServer()data.Get_data()


服务端 :中转视频信号并保存数据在云端

import socket
import cv2
import struct
import numpy
import threading
import timeclass Transstation(object):def __init__(self, cam_ip, user_ip):self.cam_ip = cam_ipself.cam_Server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.cam_Server.bind(self.cam_ip)self.cam_Server.listen(5)print('服务器接收工作准备初始化完成!')self.user_ip = user_ipself.tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)self.tcpSocket.bind(self.user_ip)self.tcpSocket.listen(5)print('服务器发送工作准备初始化完成!')self.now_time = ''self.resolution = (640, 480)self.img_fps = 70def receiveVideoThread(self):     print("等待相机中。。。。。")clientSock, client_addr = self.cam_Server.accept()print("已经连接到相机,连接地址:{0}".format(client_addr))self.now_time = str(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())))fourcc = cv2.VideoWriter_fourcc(*'XVID')out = cv2.VideoWriter(self.now_time+ '.avi' ,fourcc, 35.0, (640,480))print('正在保存视频 %s.avi'%self.now_time)flag = 1while True:tempdata = clientSock.recv(4)if cv2.waitKey(10) == 27:clientSock.close()out.release()breakif len(tempdata) == 4:info = struct.unpack('i', tempdata)buf_size = int(info[0])if buf_size>0 and buf_size<500000:try:buf = b""temp_buf = bufwhile buf_size:temp_buf = clientSock.recv(buf_size)buf_size -= len(temp_buf)buf += temp_bufdata = numpy.frombuffer(buf, dtype='uint8')img = cv2.imdecode(data, 1)self.image = imgout.write(img)except Exception as e:print(e.args)passdef sendVideoThread(self):print("等待用户中。。。。。")clientSock, client_addr = self.tcpSocket.accept()print("已经连接到用户,地址:{0}".format(client_addr))img_param = [int(cv2.IMWRITE_JPEG_QUALITY), self.img_fps]s_name = struct.pack(b'14s',str.encode(self.now_time))clientSock.send(s_name)while True:if cv2.waitKey(10) == 27:clientSock.close()break_, img_encode = cv2.imencode('.jpg', self.image, img_param)img_code = numpy.array(img_encode)img_data = img_code.tostring()try:packet = struct.pack(b'i',len(img_data))clientSock.send(packet)clientSock.send(img_data)except Exception as e:passdef start_work(self):camThread = threading.Thread(target=self.receiveVideoThread)usrThread = threading.Thread(target=self.sendVideoThread)camThread.start()usrThread.start()camThread.join()usrThread.join()if __name__ == '__main__':cam_ip = ('172.17.xx', 8888) #私网 ipusr_ip = ('172.17.xx', 9999)#私网 ipserver = Transstation(cam_ip,usr_ip)server.start_work()





http://www.ppmy.cn/news/455883.html

相关文章

如何防止服务器记录上网信息,服务器怎么监控上网记录

服务器怎么监控上网记录 内容精选 换一换 您可以将现有域名从其他服务商迁移到华为云平台提供的云解析服务上(以下简称华为云DNS)。创建域名。将现有域名从其他服务商迁移到华为云DNS前&#xff0c;需先在华为云DNS上创建待托管域名的公网域名&#xff0c;用于存储托管的域名信…

192、如何查询局域网内在线的监控设备IP

如何查询局域网内在线的监控设备IP?分享几种适用的方法,希望有所帮助。 方法一:通过电脑cmd命令查询局域网内设备IP 在电脑开始菜单[运行],输入cmd回车,在弹出的命令提示窗口输入ipconfig/all回车,能够查看本机的IP、网关、mac地址信息。 然后在命令提示窗口输入arp -a,…

办公室局域网监控员工上网记录合适吗?

办公室里黑压压的都是“埋头苦干”的员工们&#xff0c;在一阵阵键盘声的掩护下&#xff0c;办公室变成了一些员工的娱乐场。上班时间有人上网炒股票、听音乐、 买、打游戏、网购&#xff0c;更甚&#xff0c;还有浏览其它不良网站、视频的。 上班时&#xff0c;公司的群里讨论…

【人工智能】— 神经网络、前向传播、反向传播、梯度下降、局部最小值、多层前馈网络、缓解过拟合的策略

【人工智能】— 神经网络、前向传播、反向传播 前向传播反向传播梯度下降局部最小值多层前馈网络表示能力多层前馈网络局限缓解过拟合的策略 前向传播和反向传播都是神经网络训练中常用的重要算法。 前向传播是指将输入数据从输入层开始经过一系列的权重矩阵和激活函数的计算后…

极客时间-左耳听风【学习笔记】

极客时间-左耳听风 开篇词 | 洞悉技术的本质&#xff0c;享受科技的乐趣01 | 程序员如何用技术变现&#xff08;上&#xff09;02 | 程序员如何用技术变现&#xff08;下&#xff09;03 | Equifax信息泄露始末04 | 从Equifax信息泄露看数据安全05 | 何为技术领导力&#xff1f;…

0003-TIPS-2020-hxp-kernel-rop : bypass-KPTI-with-trampoline

KPTI KPTI描述内容摘录自ctf wiki KPTI 机制最初的主要目的是为了缓解 KASLR 的绕过以及 CPU 侧信道攻击。 在 KPTI 机制中&#xff0c;内核态空间的内存和用户态空间的内存的隔离进一步得到了增强。 内核态中的页表包括用户空间内存的页表和内核空间内存的页表。 用户态的页…

简历---久远银海

笔试主要是java基础、js、数据库的题目&#xff0c;前面是选择题&#xff0c;单选多选都有&#xff0c;有一个写代码的题&#xff0c;最后一个大题是数据库&#xff0c;有几个小题&#xff0c;根据要求写SQL语句。然后根据笔试试卷问一些问题&#xff0c;再看简历问一下问题。 …

大蒜种子的全球与中国市场2022-2028年:技术、参与者、趋势、市场规模及占有率研究报告

本文研究全球与中国市场大蒜种子的发展现状及未来发展趋势&#xff0c;分别从生产和消费的角度分析大蒜种子的主要生产地区、主要消费地区以及主要的生产商。重点分析全球与中国市场的主要厂商产品特点、产品规格、不同规格产品的价格、产量、产值及全球和中国市场主要生产商的…