Python 通过 HTTP 的网络摄像头图像服务器不显示图像
Python Webcam image server via HTTP not showing image
我正在尝试使用 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。
如果您需要在浏览器中查看图片,请发送 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()
我正在尝试使用 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。
如果您需要在浏览器中查看图片,请发送 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()