在手机上需要下载IP摄像头软件,可以通过内置RTSP和HTTP服务器把手机设备变成包含双向音频支持的无线IP摄像头并用于安全监控,你可以使用电脑上的浏览器查看,在这里我用OpenCV读取视频流并进行录屏操作
打开下好的软件,点击“打开IP摄像头服务器”,可以获得在当前内网下,视频流的地址,在这里我选择第一个RTSP协议的视频流,访问时需要输入账号密码,默认都为admin
新建VideoCapture对象,读取视频流
cap = cv2.VideoCapture("rtsp://admin:admin@******.local:8554/live")
用while语句循环读取视频,并显示出来
while True:
success,img = cap.read()
cv2.imshow("camera",img)
新建VideoWriter对象,将图像写入视频,需要指定几个参数
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
size = (int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH)), \
int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out = cv2.VideoWriter("name.mp4", fourcc, 25, self.size)
out.write(img) #将图片写入视频
根据上面的思路,我对代码进行了一些封装和优化,通过使用空格键进行录制的开始和结束,按下ESC键可退出程序,还在视频中显示了当前的录制状态和当前时间,Normal表示为正常展示状态,Recoding表示正在录制,可以使用空格键切换状态。如果没有按下暂停键就使用ESC推出程序,也可以正常保存视频。
import cv2
import time
class Camera:
def __init__(self, addr, save_dir="./"):
"""initial value"""
self.save_dir = save_dir
self.addr = addr
self.isRecoding = False
self.capture =cv2.VideoCapture(self.addr)
self.fourcc = cv2.VideoWriter_fourcc(*'mp4v')
self.size = (int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH)), \
int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
def exit(self):
"""exit"""
self.capture.release()
if self.isRecoding:
self.out.release()
cv2.destroyWindow("camera")
print("exit")
def mark(self,img):
now = int(time.time())
timeArray = time.localtime(now)
if self.isRecoding:
state = "Recoding:"
else:
state = "Normal:"
otherStyleTime = state + time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
otherStyleTime = otherStyleTime.encode("gbk").decode(errors="ignore")
cv2.putText(img, otherStyleTime, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (55,255,155), 2)
return img
def open(self):
"""open camera"""
cv2.namedWindow("camera",1)
while (self.capture.isOpened()):
success,img = self.capture.read()
if success:
cv2.namedWindow("camera",0)
key = cv2.waitKey(5)
if key == 32: #按空格键开始录制和结束录制
self.isRecoding = not self.isRecoding
print("isRecoding",self.isRecoding)
if self.isRecoding:
vedeo_name = time.strftime("%Y%m%d%H%M%S", time.localtime(int(time.time()))) + ".mp4"
self.out = cv2.VideoWriter(self.save_dir+vedeo_name, self.fourcc, 25, self.size)
print()
else:
self.out.release()
img = self.mark(img)
result = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
if self.isRecoding:
self.out.write(result)
cv2.imshow("camera",img)
if key == 27: #ESC键退出
self.exit()
else:
print("Fail to get image")
if __name__ == '__main__':
addr = "rtsp://admin:[email protected]:8554/live"
cam1 = Camera(addr)
cv2.namedWindow("camera",1)
cam1.open()
文件已上传到Gitee上,有需要可以进行下载
https://gitee.com/ZT-Brilly/practice/tree/master/Camera