我正在使用https://github.com/log0/video_streaming_with_flask_example中的代码来传输来自相机的视频并将其公开。我可以用这段代码完成它,但我需要在外部应用程序中用OpenCV分析视频,所以我需要在那个python脚本中加载它。
我使用此代码
camera.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('video.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()
和main.py
from flask import Flask, render_template, Response
from camera import VideoCamera
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
def gen(camera):
while True:
frame = camera.get_frame()
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(host='127.0.0.1', debug=True)
当我运行这两个脚本时,我得到页面127.0.0.1:5000,我可以看到视频。我需要做的是像这样流式传输视频,但是要在一些使用OpenCV进行某些分析的外部python脚本中导入它
cap = cv2.VideoCapture('127.0.0.1:5000')
但它不起作用,我收到错误
warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:808)
warning: 127.0.0.1:5000 (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:809)
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow, file C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp, line 331
Traceback (most recent call last):
我知道localhost在外面是看不到的,但是我会在解决这个问题后立即将它放在公共IP上,以便在不导入VideoCamera类的情况下使其工作。如果它现在可以在我的电脑上运行就足够了。