我有一个文件来放置所有图像识别算法,现在它只是一个用于测试的空框架。 它被称为算法.py
import cv2
camera = cv2.VideoCapture(0)
class algorithms:
def raw_image(caller):
while True:
success, frame = camera.read()
if not success:
print("Error reading from camera")
frame = cv2.flip(frame, 1) #mirror image vertically
caller.output(frame)
如果我尝试使用 Flask 设置 Web 服务器,它不会像我在这里尝试的那样工作。服务器正在运行,如控制台输出所示,但我无法使用浏览器连接到它。
from algorithms import algorithms
from flask import Flask, Response
import cv2
class server:
def output(self, frame):
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')
def web(self):
app = Flask(__name__)
@app.route('/')
def video_feed():
return Response(algorithms.raw_image(self), mimetype='multipart/x-mixed-replace; boundary=frame')
app.run(host='0.0.0.0', port=5000)
server().web()
我错过了什么?
当我使用
cv2.imshow
运行此文件时,它工作正常,就像这里
from algorithms import algorithms
import cv2
class window:
def output(self, frame):
cv2.imshow("Frame", frame)
#exit
if cv2.waitKey(1) & 0xFF == ord('q'):
exit()
def start(self):
algorithms.raw_image(self)
window().start()
将算法中的
caller.output(frame)
更改为 yield caller.output(frame)
并将 yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
更改为 return (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
使流可见。