我试图制作一个将在其他客户端网络浏览器中显示该服务器的网络摄像头视频的python服务器
我编写了这段代码,但是当我尝试在浏览器中打开链接时,脚本总是崩溃
这是我的代码
import sys
sys.path.append("cv2")
import cv2
from PIL import Image
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from io import BytesIO
import time
capture=None
class CamHandler(BaseHTTPRequestHandler):
def do_GET(self):
global capture
if self.path.endswith('test.html'):
self.send_response(200)
self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')
self.end_headers()
camId = "0"
font = cv2.FONT_HERSHEY_SIMPLEX
fontsize = .8
while True:
try:
rc,img = capture.read()
if not rc:
continue
imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
jpg = Image.fromarray(imgRGB)
tmpFile = BytesIO()
jpg.save(tmpFile,'JPEG')
self.wfile.write(b"--jpgboundary")
self.send_header('Content-type','image/jpeg')
self.send_header('Content-length',str(tmpFile.getbuffer().nbytes))
self.end_headers()
jpg.save(self.wfile,'JPEG')
time.sleep(1/60)
except KeyboardInterrupt:
break
return
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
def main():
global capture
capture = cv2.VideoCapture(0)
capture.set(3,1920)
capture.set(4,1080)
global img
try:
server = ThreadedHTTPServer(('192.95.69.202', 8091), CamHandler)
print ("server started on port 8091")
server.serve_forever()
except KeyboardInterrupt:
capture.release()
server.socket.close()
if __name__ == '__main__':
main()
当我打开192.95.69.202:8091/test.html服务器脚本崩溃时