Skip to content
Advertisement

Capture first image from h.264 video streaming using websocket – Python

I’m trying to capture a single image from H.264 video streaming in my Raspberry Pi. The streaming is using raspivid with websocket. But, cannot show a correct image in imshow(). I also tried to set the .reshape(), but got ValueError: cannot reshape array of size 3607 into shape (480,640,3)

In client side, I successfully connect to the video streaming and get incoming bytes. The server is using raspivid-broadcaster for video streaming. I guess the first byte can be decoded to image? So, I do the following code.

JavaScript

print(frame) shows

JavaScript

print(response) shows

JavaScript

Any suggestions?

———————————- EDIT ———————————-

Thanks for this suggestion. Here is my updated code.

JavaScript

print(frame) shows

JavaScript

Below is the saved image I get. It has the wrong size of 740(height)x640(width). The correct one is 480(height) x 640(width). And, not sure why the image is grayscale instead of color one.

enter image description here

———————————- EDIT 2 ———————————-

Below is the main method to send data in raspivid.

raspivid – index.js

JavaScript

stream-split – index.js (A line of code shows the max. size is 1Mb)

JavaScript

———-Completed Answer (Thanks Ann and Christoph for the direction)———-

Please see in answer section.

Advertisement

Answer

One question, how is the frame/stream transmitted trough websocket? The Byte sequence looks like a nal unit, it can be PPS or SPS etc. how do you know its an IFrame for example, i dont know If cv2.imshow Support RAW H264. Look into pyav there u can open h264 raw bytes then you can try to exract one frame out of it :) let me know if you need help on pyav, Look at this post there is an example how you can doit.

Update

Based on your comment, you need a way to parse and decode a raw h264 stream, below is a function that give u and idea about that, you need to pass your recived bytes from websocket to this function, be aware that needs to be enough data to extract one frame.

JavaScript

PyAV docs

JavaScript

You could also try to read directly with pyav the Stream with av.open(“tcp://127.0.0.1:”)

Update 2 Could u please test this, the issues that you have on your edit are weird, you dont need a websocket layer I thing you can read directly from raspivid

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement