python-3.x - 带有opencv-python的烧瓶:在访问g @app.route之前保持相机运行并在发送GET请求时拍摄图像
问题描述
我正在尝试初始化相机并启动视频源,然后打开 @app.route 函数,并且只有在我从 GET 请求中收到 URL 时才应保存帧。
我的代码是:
from flask import Flask, jsonify
from flask import request
from flask_restful import Resource, Api, reqparse
from datetime import datetime
import time
import numpy as np
import glob
import os
import sys
import cv2
# initialize the flask application
app = Flask(__name__)
# initialize the camera and grab a reference to the raw camera capture
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
#RESTAPI for image
@app.route('/take_image')
def image():
start_time = time.time()
jobnummer = request.args.get('JOB') #if key doesn't exist, returns None
#save the frame when GET Request is sentt
if jobnummer:
cv2.imwrite('test.jpg', frame)
end_time = time.time()
time_tot = end_time-start_time
res = {"jobnummer" : jobnummer,
"time":time_tot
}
return jsonify(res) , 200
if __name__ == "__main__":
# run flask application in debug mode
app.run(debug=True,port=5000,host='0.0.0.0')
但是当我运行它时,由于 while 循环,我无法进入 @app.route 函数。有什么方法可以让视频感觉正常运行然后访问@app.route?
解决方案
这是一个解决问题的演示:
from flask import Flask, render_template, Response
import cv2
app = Flask(__name__)
'''
for ip camera use - rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp'
for local webcam use cv2.VideoCapture(0)
'''
camera = cv2.VideoCapture(0)
def gen_frames():
while True:
success, frame = camera.read() # read the camera frame
if not success:
break
else:
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/video_feed')
def video_feed():
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == "__main__":
app.run(debug=True)
index.html(使用引导但不是必需的)
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Live Streaming Demonstration</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8 offset-lg-2">
<h3 class="mt-5">Live Streaming</h3>
<img src="{{ url_for('video_feed') }}" width="100%">
</div>
</div>
</div>
</body>
</html>
推荐阅读
- tableau-api - 我已经为我的参数计算了尺寸,其中等于 - 全部。但是,我也希望它返回 null 作为 0
- bash - 如何在不重新启动 nvim 的情况下获取 neovim 配置文件?
- java - 如何中断套接字的循环
- reactjs - 使用外部 Api 的 TypeScript 拉取图像的问题
- excel - Excel XIRR 函数返回无效计算
- node.js - 节点 Module.export 和 GET 从表单显示搜索结果
- python - 使用继承的类打印没有新行
- apache-beam - Apache Beam Spark 便携式跑步者
- python - 按月分组 DataFrame 并计数值
- schema.org - schema.org: aggregateRating 不同的符号