我正在尝试使用Django创建一个简单的视频流网站。我正在使用cv2启动网络摄像头,并使用ZMQ将数据从客户端传输到服务器。我找到了这个 link ,用于编写代码的网络部分。
代码本身可以正常工作,但是当我创建一个简单的HTML文件以通过浏览器启动实时流时,代码失败并显示此错误消息
zmq.error.ZMQError: Address in use
我猜会出现此错误,因为Django使用的IP和ZMQ尝试使用的IP是相同的。但是我不确定如何纠正此错误。
到目前为止,这是我的代码
def start_server():
context = zmq.Context()
footage_socket = context.socket(zmq.SUB)
print('socket created')
footage_socket.setsockopt_string(zmq.SUBSCRIBE, np.unicode(''))
footage_socket.bind('tcp://192.168.1.18:5020')
print('binding complete')
print('server ready')
return footage_socket
def recv_content(socket, face_cascade_path):
cascade = cv2.CascadeClassifier(face_cascade_path)
while True:
try:
data = socket.recv_string()
img = base64.b64decode(data)
npimg = np.fromstring(img, dtype=np.uint8)
frame = cv2.imdecode(npimg, 1)
print(frame)
face = cascade.detectMultiScale(frame, scaleFactor=1.3, minNeighbors=3)
for (x, y, w, h) in face:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imshow("Stream", frame)
except KeyboardInterrupt:
cv2.destroyAllWindows()
break
from server import *
def index(request):
face_cascade_path = '../../../TRAINED MODELS/FACE/haarcascade_frontalface_default.xml'
footage_socket = start_server()
recv_content(footage_socket, face_cascade_path)
return render(request, 'index.html')
def start_client(request):
context = zmq.Context()
footage_socket = context.socket(zmq.PUB)
footage_socket.connect('tcp://192.168.1.18:5020')
print('connected to server')
print('starting video on client machine')
camera = cv2.VideoCapture(0) # init the camera
while True:
try:
grabbed, frame = camera.read() # grab the current frame
frame = cv2.resize(frame, (640, 480)) # resize the frame
frame = cv2.flip(frame, 1)
encoded, buffer = cv2.imencode('.jpg', frame)
jpg_as_text = base64.b64encode(buffer)
footage_socket.send(jpg_as_text)
except KeyboardInterrupt:
camera.release()
cv2.destroyAllWindows()
break
<html>
<head>
</head>
<body>
<div class='container'>
<h2>CAMERA SERVER CLIENT TEST</h2>
<p>
Click the start_client button to start camera. Each frame of the stream is sent to the server.
</p>
<p>
The camera code is running on the client side.
</p>
<a href ='start_client/'><button>start client</button></a>
</div>
</body>
</html>
请帮助我。
提前谢谢
答案 0 :(得分:1)
您应该采用其他端口,而不是通常使用的公用cmd.exe
端口。
另一个想法是,必须在ZMQ中的8000
或bind
方法之前放置所有套接字选项。
因此您的代码将如下所示:
connect
[注意]:
不要忘记将客户端(def start_server():
context = zmq.Context()
footage_socket = context.socket(zmq.SUB)
footage_socket.setsockopt_string(zmq.SUBSCRIBE, np.unicode(''))
try:
footage_socket.bind('tcp://192.168.1.18:5020') # Another port used.
except:
pass
return footage_socket
)的端口更改为.connect()
。
[更新]:
5020
更新了有关刷新问题的答案。
或者,您可以使用try-except
方法清除先前的套接字,也可以将条件置于检查先前的套接字的位置。