Search code examples
pythonsocketsopencvwebcam-capture

Python Webcam image server via HTTP not showing image


I am trying to serve Webcam image via HTTP using Python socket and OpenCV but it doesn't work right. The server does not serve appropriate JPEG image captured from Webcam. It only shows some binary arrays.

import io
import socket
import atexit
from cv2 import *
from PIL import Image

def camServer():
    while True:
        print("wait...")
        conn, addr = server_socket.accept()
        if conn:
            print(conn)
            print(addr)
            connection = conn.makefile('wb')
            break

    print("Connecting")
    try:
        cam = VideoCapture(0)
        s, imgArray = cam.read()
        if s:
            atexit.register(onExit)
            img = io.BytesIO()
            imgPIL = Image.fromarray(imgArray)
            imgPIL.save(img, format="jpeg")
            img.seek(0)
            connection.write(img.read())
            img.seek(0)
            img.truncate()
    finally:
        print("close connection")
        connection.close()

def onExit():
    connection.close()
    server_socket.close()
    print("exit")

server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
server_socket.setblocking(1)

while True:
    camServer()

I found the original source code from here : Python socket server to send camera image to client and I modified to use OpenCV instead of PICamera.

Served HTML Server Log


Solution

  • If you need the ability to see the image in your browser, send the content-type:

    atexit.register(onExit)
    img = io.BytesIO()
    imgPIL = Image.fromarray(imgArray)
    imgPIL.save(img, format="jpeg")
    img.seek(0)
    
    connection.write('HTTP/1.0 200 OK\n')
    connection.write('Content-Type: image/png\n')
    connection.write('\n')
    connection.write(img.read())
    
    img.seek(0)
    img.truncate()