我正在尝试初始化摄像头并启动视频馈送,然后打开@app.route功能,只有当我收到GET请求的网址时,才会保存帧。
我的代码是:
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?
发布于 2020-12-15 05:50:58
下面是一个解决这个问题的demo:
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>
https://stackoverflow.com/questions/65295015
复制相似问题