0

我正在尝试使用 Python 套接字和 OpenCV 通过 HTTP 提供网络摄像头图像,但它不能正常工作。服务器不提供从网络摄像头捕获的适当 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。

提供的 HTML 服务器日志

4

1 回答 1

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()
于 2017-01-28T13:26:21.960 回答