gpt4 book ai didi

python - 使用python和opencv模拟网络摄像机

转载 作者:太空宇宙 更新时间:2023-11-03 21:31:48 29 4
gpt4 key购买 nike

我有一个用例,我正在使用 pythonopencv模拟 IP 摄像机

我正在使用 opencv 播放视频并将帧的字节发送到一个应用程序,该应用程序在端口 8080 上流式传输它。

问题是视频一结束,我就没有任何东西可以发送到在端口 8080 流式传输这个假模拟相机的应用程序,所以 application 将其视为超时并停止工作。

我的问题是,我怎样才能发送一些假字节让几天的黑屏噪音只是为了保持我正在监听的应用程序到我 8080 的面部模拟摄像头?

编辑1:添加代码

app.py

from camera import VideoCamera
from flask import Flask, render_template, Response
import time

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

def gen(camera):
while True:
try:
frame = camera.get_frame()
except Exception:
print("Video is finished or empty")
#return None
frame = camera.get_heartbeat()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
return Response(gen(VideoCamera()),
mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
app.run(debug=True)

相机.py

import cv2

class VideoCamera(object):
def __init__(self):
# Using OpenCV to capture from device 0. If you have trouble capturing
# from a webcam, comment the line below out and use a video file
# instead.
#self.video = cv2.VideoCapture(0)
# If you decide to use video.mp4, you must have this file in the folder
# as the main.py.
# self.video = cv2.VideoCapture('suits_hd.mp4')
self.video = cv2.VideoCapture('nature.mp4')

def __del__(self):
self.video.release()

def get_frame(self):
success, image = self.video.read()
# We are using Motion JPEG, but OpenCV defaults to capture raw images,
# so we must encode it into JPEG in order to correctly display the
# video stream.
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()

def get_heartbeat(self):
# jpeg = cv2.imread('noise-black.jpg')
image = cv2.imread('noise-green.jpg')
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()

最佳答案

因此,当您初始化 VideoCamera 时,获取文件中视频帧的宽度和高度并记住它们。然后,如果 self.video.read() 失败,只需使用 numpy 创建一个与视频帧大小相同的随机数组和 imencode() 并发送。

制作一个随机的绿色框架:

import numpy as np

# Make the Green channel out of intensities in range 200-255
G=np.random.randint(200,256,(320,240,1), dtype=np.uint8)
# Make Red and Blue channel out of intensities in range 0-49
X=np.random.randint(0,50,(320,240,1), dtype=np.uint8)
# Merge into a 3-channel image, use BGR order with OpenCV - although it won't matter because G is in the middle in both!
image=np.concatenate((X,G,X),axis=2)

关于python - 使用python和opencv模拟网络摄像机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51454896/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com