0
我正在嘗試對樹莓派進行視覺處理,並監視圖形界面上的效果。使用cv2.imshow確實會降低幀速率,所以我嘗試將操作流式傳輸到MPEG本地服務器,然後從另一臺桌面上的chrome監視它。下面是我開發的代碼:Python MJPEG服務器
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from threading import Thread
import imutils
import sys
class CamHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path.endswith('/stream.mjpg'):
self.send_response(20)
self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=--jpgboundary')
self.end_headers()
while True:
try:
if(frame != None):
pass
r, buf = cv2.imencode(".jpg", frame)
self.wfile.write("--jpgboundary\r\n".encode())
self.end_headers()
self.wfile.write(bytearray(buf))
except KeyboardInterrupt:
break
return
if self.path.endswith('.html') or self.path == "/":
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<html><head></head><body>')
self.wfile.write('<img src="http://localhost:9090/stream.mjpg" height="240px" width="320px"/>')
self.wfile.write('</body></html>')
return
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
class WebcamVideoStream:
def __init__(self, src=0):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
# self.stream.set(3, 1920)
# self.stream.set(4, 1080)
# self.stream.set(15,-100)
(self.grabbed, self.frame) = self.stream.read()
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
def start(self):
# start the thread to read frames from the video stream
Thread(target=self.update, args=()).start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
self.stream.release()
return
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# return the frame most recently read
return self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
def realmain():
global frame
ip = 'localhost'
try:
cap = WebcamVideoStream().start()
server = ThreadedHTTPServer((ip, 9090), CamHandler)
print("starting server")
target = Thread(target=server.serve_forever,args=())
i = 0
while True:
img = cap.read()
img1 = imutils.resize(img, width=600)
img2 = cv2.GaussianBlur(img1, (5, 5), 0)
#frame = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
frame = cv2.Canny(img, 35, 125)
if(i == 0):
target.start()
i +=1
except KeyboardInterrupt:
sys.exit()
if __name__ == '__main__':
realmain()
現在,我可以從我的桌面上運行的服務器和查看MPEG的從我的桌面上的鍍鉻細,但我無法從我的覆盆子PI運行服務器,並通過在我的桌面上輸入以下URL:http://「RASPBERRY PI IP」:9090/stream.mjpg來訪問它。當我這樣做時,Chrome只是說網頁不可用。即使在PI上運行服務器,我也無法查看Epiphany瀏覽器上的網址,它只是下載圖像。想知道如果有人有這個問題的答案。
另外,有沒有更快的方式來解壓縮和重新壓縮之前發送到服務器的JPG?
你可以試試* ip =「」*(空字符串)而不是*'localhost'*嗎? – sal
謝謝,我其實嘗試了我的手機wifi熱點上的服務器,並且能夠通過我的桌面進行連接。必須有防火牆阻止連接 –