'CV2: How to stream cv2.imshow to flask server?
I have the following code that (1) takes a video (2) analyse for motion and add some text (3) show the output via cv2.imshow (4) finally, publish the output animation on a html page (to be shared with team mates over a intranet/network drive).
How do I pass the cv2.imshow output to the camera in Flask? Also, would anyone know if the Flask webpage can be placed on a shared drive... thus allowing others to view it over intranet (eg over an address such as P:/test/index.html instead of http://127.0.0.1:5000/)?
I've tried looking for solutions by myself, but haven't been able to find answers. Thanks for your kind advice!
cap = cv2.VideoCapture('c:/data/flare2.mp4')
fgbg1 = cv2.createBackgroundSubtractorMOG2()
fgbg2 = cv2.createBackgroundSubtractorMOG2()
while(1):
ret, frame = cap.read()
frame1 = frame[0:400, 0:400]
frame2 = frame[0:400, 400:800]
#FRAME1
fgmask1 = fgbg1.apply(frame1)
number_of_white_pix1 = np.sum(fgmask1 == 255)
fgmask1 = cv2.cvtColor(fgmask1, cv2.COLOR_BGR2RGB )
maskcolour1 = cv2.addWeighted(frame1,0,fgmask1,1,0)
text1 = str(round(number_of_white_pix1/1000,0)) + ' kg / hr flare'
#FRAME2
fgmask2 = fgbg2.apply(frame2)
number_of_white_pix2 = np.sum(fgmask2 == 255)
fgmask2 = cv2.cvtColor(fgmask2, cv2.COLOR_BGR2RGB )
maskcolour2 = cv2.addWeighted(frame2,0,fgmask2,1,0)
text2 = str(round(number_of_white_pix2/1000,0)) + ' kg / hr flare'
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(maskcolour1,
text1,
(50, 50),
font, 1,
(0, 255, 0),
4,
cv2.LINE_8)
cv2.putText(maskcolour2,
text2,
(50, 50),
font, 1,
(0, 255, 0),
4,
cv2.LINE_8)
add = cv2.hconcat([maskcolour1, maskcolour2])
cv2.imshow('combinedall', add)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
##################STREAMING
cap.release()
cv2.destroyAllWindows()
from flask import Flask, render_template, Response
import cv2
app = Flask(__name__)
camera = add ###<<<<is this correct?
def gen_frames(): # generate frame by frame from camera
while True:
# Capture frame-by-frame
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') # concat frame one by one and show result
@app.route('/video_feed')
def video_feed():
#Video streaming route. Put this in the src attribute of an img tag
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/')
def index():
"""Video streaming home page."""
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True,use_reloader=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|