Python Webcam图像服务器通过HTTP不显示图像

时间:2017-01-28 12:51:50

标签: python sockets opencv webcam-capture

我正在尝试使用Python套接字和OpenCV通过HTTP提供Webcam图像,但它不能正常工作。服务器无法提供从Webcam捕获的适当JPEG图像。它只显示了一些二进制数组。

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()

我从这里找到了原始源代码:Python socket server to send camera image to client我修改为使用OpenCV而不是PICamera。

Served HTML Server Log

1 个答案:

答案 0 :(得分:1)

如果您需要能够在浏览器中查看图像,请发送内容类型:

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()
相关问题