在本系列的第二篇已经教给了大家如何在win11进行qt界面模拟,这里再次给大家带来一篇接入到yolov5的远程页面通信
1.编写服务端(树莓派)
1.1detect封装
首先将yolov5的detect函数进行封装抽取,这一步骤网上很多,随便拉点,我这里抽取的是
box, scores, classid, a = yolo.detect(frame)
其中a返回的是画框之后的图像
1.2 Server.py
import socket
import time
# from picamera2 import Picamera2
from PIL import Image
from io import BytesIO
import numpy as np
from detect_by_cv import *
import socket
import cv2
import numpy as np
from detect_by_cv import Yolov5
from PIL import Image
from io import BytesIO
def main():
yolo = Yolov5()
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 8083)) # 使用树莓派的IP地址
server_socket.listen(1)
print("服务器启动,等待连接...")
while True: # 主循环,用于接受新的连接
client_socket, addr = server_socket.accept()
print(f"接受到来自 {addr} 的连接")
cap = cv2.VideoCapture(0) # 打开摄像头
try:
count = 0
while True:
ret, frame = cap.read()
if ret:
box, scores, classid, a = yolo.detect(frame)
photo = a
im = Image.fromarray(photo)
if im.mode != 'RGB':
im = im.convert('RGB')
buffer = BytesIO()
im.save(buffer, format='JPEG')
buffer = buffer.getvalue()
max_pixel_value = np.max(photo)
min_pixel_value = np.min(photo)
max_min_str = f"{max_pixel_value},{min_pixel_value},{max_pixel_value},{min_pixel_value}"
# 发送图像数据长度和数据
client_socket.sendall(len(buffer).to_bytes(4, 'big'))
client_socket.sendall(buffer)
# 发送最大最小值数据
client_socket.sendall(len(max_min_str).to_bytes(4, 'big'))
client_socket.sendall(max_min_str.encode())
count += 1
print(f"已成功发送第 {count} 张图片")
else:
break
except Exception as e:
print(f"发生异常: {e}")
finally:
client_socket.close()
cap.release()
print("等待新的连接...")
if __name__ == '__main__':
main()
1.3代码效果
2.编写服客户端
客户端代码和(二)中的一样,具体效果如下,以火焰检测为例子:
3.结语
到此为止,本系列yolov5与win11通信的教程已经结束,大家有需要可以自己优化代码