Instantly share code, notes, and snippets.

Embed
What would you like to do?
Grab a single frame from an MJPEG stream
#!/usr/bin/env python
import socket
import sys
if len(sys.argv) != 3:
print "Usage: %s host:port destfile.jpg" % sys.argv[0]
sys.exit(1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host, port = sys.argv[1].split(':')
s.connect((host, int(port)))
fh = s.makefile()
# Read in HTTP headers:
line = fh.readline()
while line.strip() != '':
parts = line.split(':')
if len(parts) > 1 and parts[0].lower() == 'content-type':
# Extract boundary string from content-type
content_type = parts[1].strip()
boundary = content_type.split(';')[1].split('=')[1]
line = fh.readline()
if not boundary:
raise Exception("Can't find content-type")
# Seek ahead to the first chunk
while line.strip() != boundary:
line = fh.readline()
# Read in chunk headers
while line.strip() != '':
parts = line.split(':')
if len(parts) > 1 and parts[0].lower() == 'content-length':
# Grab chunk length
length = int(parts[1].strip())
line = fh.readline()
image = fh.read(length)
with open(sys.argv[2], 'w') as out_fh:
out_fh.write(image)
s.close()
@jogu

This comment has been minimized.

jogu commented Apr 26, 2018

FWIW, this didn't work for me until I changed line 29 to:
while line.strip() != "--"+boundary:

It's proving very useful though - thank you for sharing!

@scar86

This comment has been minimized.

scar86 commented May 7, 2018

Thanks a lot !!

@adwidianjaya

This comment has been minimized.

adwidianjaya commented Aug 12, 2018

Thank you so much, very useful!

@unkaMoMo

This comment has been minimized.

unkaMoMo commented Nov 13, 2018

This worked fine for years until I upgraded to Ubuntu 18.04 LTS where it suddenly no longer worked. Making the change suggested by jogu got it back to working again. Thanks, jogu.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment