opencv 使用python通过ZMQ pubsub发送视频?

alen0pnh  于 2023-01-31  发布在  Python
关注(0)|答案(2)|浏览(129)

我想使用Python和ZMQ创建一个简单的客户机/服务器设置。客户机必须将现场视频从我的笔记本电脑摄像头发送到服务器,服务器显示视频。
我遇到了一些“答案”,但除了以base64格式发送图像外,我无法让它们中的任何一个工作。我不想以base64格式发送-它速度慢,开销大。我认为发送图像字节数据更有意义。
这是我的客户:

import base64
import zmq
import time
import cv2
from imutils.video import VideoStream

ctx = zmq.Context()

send_sock = ctx.socket(zmq.PUB)
send_sock.bind("tcp://*:1235")

vs = VideoStream(src=0, resolution=(640, 480)).start()
time.sleep(2.0)  # allow camera sensor to warm up

while True:  # send images as stream until Ctrl-C

    frame = vs.read()
    encoded, buf = cv2.imencode('.jpg', frame)
    image = base64.b64encode(buf)
    send_sock.send(image)

    # detect any kepresses
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

send_sock.close()
ctx.term()

这里是我的服务器:

import zmq
import time
import base64
import numpy as np
import cv2

ctx = zmq.Context()

rcv_sock = ctx.socket(zmq.SUB)
rcv_sock.connect("tcp://127.0.0.1:1235")
rcv_sock.subscribe("")

while True:

    image_string = rcv_sock.recv_string()
    raw_image = base64.b64decode(image_string)
    image = np.frombuffer(raw_image, dtype=np.uint8)
    frame = cv2.imdecode(image, 1)
    cv2.imshow("frame", frame)

    time.sleep(0.1)

    # detect any kepresses
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

rcv_sock.close()
ctx.term()
cv2.destroyAllWindows()

上面的代码使用Base64,可以正常工作。
我怎么能做同样的,但没有Base64(我正在寻找一个更快的解决方案)。

e5nqia27

e5nqia271#

答案是简单地删除base64编码...
委托单位:

frame = vs.read()
encoded, buf = cv2.imencode('.jpg', frame)
send_sock.send(buf)

服务器:

raw_image = rcv_sock.recv()
image = np.frombuffer(raw_image, dtype=np.uint8)
frame = cv2.imdecode(image, 1)
cv2.imshow("frame", frame)
vtwuwzda

vtwuwzda2#

使用opencv代替,实时工作。

服务器:

import zmq
import cv2

ctx = zmq.Context()

send_sock = ctx.socket(zmq.PUB)
send_sock.bind("tcp://*:1235")

cap = cv2.VideoCapture(0)
while True: 
    ret, frame = cap.read()
    if ret:
        encoded, buf = cv2.imencode('.jpg', frame)
        send_sock.send(buf)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break
cap.release()
cv2.destroyAllWindows()
send_sock.close()
ctx.term()

客户:

import zmq
import time
import base64
import numpy as np
import cv2

ctx = zmq.Context()

rcv_sock = ctx.socket(zmq.SUB)
rcv_sock.connect("tcp://127.0.0.1:1235")
rcv_sock.subscribe("")

while True:
    raw_image = rcv_sock.recv()
    image = np.frombuffer(raw_image, dtype=np.uint8)
    frame = cv2.imdecode(image, 1)
    cv2.imshow("Receiver stream", frame)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

rcv_sock.close()
ctx.term()
cv2.destroyAllWindows()

相关问题