GithubHelp home page GithubHelp logo

Comments (6)

miguelgrinberg avatar miguelgrinberg commented on June 25, 2024

There is a complete implementation of a video file writer for Python in this article: https://www.learnopencv.com/read-write-and-display-a-video-using-opencv-cpp-python/.

from flask-video-streaming.

robsmall avatar robsmall commented on June 25, 2024

Thanks for the quick response and share! I was hoping to avoid needing to use openCV as well as picamera to generate the data to write to the file so I could use the same stream that is sent over the network. I was looking to achieve this by using a custom StreamingOutput from the picamera's recording like so:

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            self.frame = self.buffer.getvalue()
            self.buffer.seek(0)
        return self.buffer.write(buf)

    def flush(self):
        print "\n\nflush!!!!\n\n"
        try:
            fourcc = cv2.cv.CV_FOURCC(*'MJPG')
            out = cv2.VideoWriter("output.avi", fourcc, 40.0, (1640, 922))

            arr = np.fromstring(self.buffer.getvalue(), dtype=np.uint8)
            out.write(arr)

            # Release everything if job is finished
            out.release()
            cv2.destroyAllWindows()
        except Exception as e:
            print e


class Camera(BaseCamera):
    camera = None
    output = None

    @staticmethod
    def start_recording():
        """ Start recording from the camera object. """
        Camera.camera.start_recording(Camera.output, format='mjpeg')

    @staticmethod
    def stop_recording():
        """ Stop the Camera object from recording. """
        Camera.camera.stop_recording()

    @staticmethod
    def frames():
        with picamera.PiCamera(
                sensor_mode=5, resolution="1640x922", framerate=40) as camera:
            Camera.camera = camera
            Camera.output = StreamingOutput()

            Camera.start_recording()
            
            while True:
                frame = Camera.output.frame
                yield frame

The issue is when I open the output avi file (output.avi), it is empty. I also tried writing the frames themselves but to no avail. Curious if you have any pointers here.

from flask-video-streaming.

miguelgrinberg avatar miguelgrinberg commented on June 25, 2024

The code that you are using is not written by me, it is actually based on code that I wrote, but was modified in a way that I don't fully understand. You now took that code and modified it even more, so I can't really tell you for sure what's wrong. What seems wrong to me though, is that the flush() function is opening the video file. My guess is that flush() is called several times during the recording, and each time it is called, you are creating a new video file, overwriting anything you may have written to it before that.

from flask-video-streaming.

robsmall avatar robsmall commented on June 25, 2024

Thanks for the insight! flush() is called at the end of the output (according to the picamera docs) from the picamera. I was using this to PoC writing the output to a file by terminating the feed and looking at the file after recording for a while. Unfortunately, in reading up some more it looks like there are quite a few issues here.

Sorry for asking about modified broken code, I wanted to flag this as a question not an issue to see if you had any insight into writing the output from a stream to a file but in hindsight this is more of a question about writing picamera output to a file on a pi, not about the code in this repo. Will close.

from flask-video-streaming.

robsmall avatar robsmall commented on June 25, 2024

Well... That was very broken. The issue was that I wasn't thinking clearly and missed the fact that I was truncating the buffer so it was only writing a single frame. The solution is to write out each frame and then release the buffer at the end:

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()

        four_cc = cv2.cv.CV_FOURCC(*'MJPG')
        now = datetime.datetime.now()
        self.out = cv2.VideoWriter(
            "output_{}.avi".format(now.strftime("%Y-%m-%d_%H:%M:%S")),
            four_cc,
            30,
            (1640, 922))

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            self.frame = self.buffer.getvalue()
            self.buffer.seek(0)

            arr = cv2.imdecode(np.fromstring(buf, dtype=np.uint8), 1)
            self.out.write(arr)

            return self.buffer.write(buf)

    def flush(self):
        # Release everything since the job is finished
        self.out.release()
        cv2.destroyAllWindows()

from flask-video-streaming.

LMJayasundara avatar LMJayasundara commented on June 25, 2024

Hello

Is there any way to do this

from flask-video-streaming.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.