gpt4 book ai didi

python - 通过HTTP的Python网络摄像头图像服务器未显示图像

转载 作者:行者123 更新时间:2023-12-02 17:43:00 28 4
gpt4 key购买 nike

我正在尝试使用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。

Served HTML
Server Log

最佳答案

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

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

关于python - 通过HTTP的Python网络摄像头图像服务器未显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41909986/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com