title: Flask video stream using OpenCV images
body: <p>I am trying to use Flask to show a stream of OpenCV images. I am using ROS and the Zed stereo camera. </p>
  
  <p>The issue is that the flask server only shows a broken image icon. I am guessing that the issue is in the gen() method because the cv2.imwrite('t.jpg', img) method is the wrong way to go. I have very little experience with OpenCV. </p>
  
  <p>The image data that the Flask server receives is an InputArray. I need a way of converting this and showing the image in the Flask server. </p>
  
  <p>I am using Python 2.7 and rospy (ROS). </p>
  
  <p>Any advice?</p>
  
  <p>UPDATE: </p>
  
  <p>The code for the ROS node accessing ZED cam:</p>
  
  <pre><code>    #!/usr/bin/env python
  
  # ROS imports
  import rospy
  from sensor_msgs.msg import Image
  
  # Utils
  import numpy as np
  import cv2
  from cv_bridge import CvBridge, CvBridgeError
  import stream
  
  
  def callback(data):
      """
      param data: data from zed/rgb/image_rect_color topic
      """
      # convert from ROS sensor_msgs/Image to cv2
      bridge = CvBridge()
      try:
          cv_img = bridge.imgmsg_to_cv2(data, desired_encoding='passthrough')
          stream.img = cv_img
      except CvBridgeError as e:
          print(e)
      # show image stream
      # cv2.imshow('zed', cv_img)
      # cv2.waitKey(3)
  
  
  def zed_sub():
      # initialize ROS node 'zed_sub'
      rospy.init_node('zed_sub')
      # subscribe to the ROS topic 'zed/rgb/image_rect_color'
      rospy.Subscriber('zed/rgb/image_rect_color', Image, callback)
      # keep python from exiting until this node is stopped
      try:
          rospy.spin()
      except KeyboardInterrupt:
          cv2.destroyAllWindows()
  
  
  if __name__ == '__main__':
      zed_sub()
  </code></pre>
  
  <p>The code for the Flask server: </p>
  
  <pre><code>#!/usr/bin/env python
  
  from flask import Flask, render_template, Response
  import cv2
  
  
  app = Flask(__name__)
  HOST = '192.168.1.3'    # on-board computer's IP address
  PORT = 8080
  
  img = None
  
  
  @app.route('/')
  def index():
      return render_template('index.html')
  
  
  @app.route('/video_feed')
  def video_feed():
      return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
  
  
  def gen():
      """Video streaming generator function."""
      global img
      while True:
          try:
              cv2.imwrite('t.jpg', img)
              yield(b'--frame\r\n'
                  b'Content-Type: image/jpeg\r\n\r\n' + open('t.jpg', 'rb').read() + b'\r\n')
          except NameError as e:
              print(e)
  
  
  if __name__ == '__main__':
      app.run(host=HOST, port=PORT, debug=True, threaded=True)
  </code></pre>