import sys
import json
import cv2
import numpy as np
import requests
import os
from PyQt5.QtCore import Qt, QTimer, pyqtSignal, QObject, QThread
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import (QWidget, QLabel, QPushButton, QTextEdit,
QHBoxLayout, QVBoxLayout, QSplitter, QApplication,
QMessageBox)
from caipanconnect import *
SERVER_IP = "192.168.1.88"
client = RefereeBoxClient(SERVER_IP, 6666)
if not client.connect():
exit(1)
# 信号类 - 用于线程间通信
class SignalEmitter(QObject):
new_data = pyqtSignal(dict)
# 工作线程 - 运行Flask应用
class FlaskThread(QThread):
def __init__(self, flask_run_func):
super().__init__()
self.flask_run_func = flask_run_func
self.emitter = SignalEmitter()
def run(self):
self.flask_run_func() # 调用Flask运行函数
def stop(self):
"""安全停止Flask"""
if self.isRunning():
self.quit()
self.wait(1000) # 等待1秒
if self.isRunning():
self.terminate()
self.wait()
class VideoThread(QThread):
change_pixmap_signal = pyqtSignal(QImage)
def __init__(self, url):
super().__init__()
self.url = url
self.running = True
self.session = requests.Session()
def run(self):
while(1):
try:
response = self.session.get(self.url, stream=True, timeout=10)
if response.status_code != 200:
return
content_type = response.headers['Content-Type']
boundary = content_type.split('=')[1].encode()
data_buffer = b''
for chunk in response.iter_content(chunk_size=8192):
if not self.running:
break
data_buffer += chunk
a = data_buffer.find(b'\r\n--' + boundary + b'\r\n')
b = data_buffer.find(b'\r\n--' + boundary + b'--')
if a != -1:
if b == -1:
frame_data = data_buffer[:a]
data_buffer = data_buffer[a + len(b'\r\n--' + boundary + b'\r\n'):]
else:
frame_data = data_buffer[:b]
data_buffer = b''
start = frame_data.find(b'\r\n\r\n') + 4
image_data = frame_data[start:]
qimg = QImage.fromData(image_data)
if not qimg.isNull():
self.change_pixmap_signal.emit(qimg)
except Exception as e:
print(f"Video stream error: {e}")
def stop(self):
self.running = False
self.session.close() # 关闭请求会话
#self.wait(2000) # 等待2秒
if self.isRunning():
self.terminate() # 强制终止
self.wait()
class MainWindow(QWidget):
def __init__(self, data_queue):
super().__init__()
self.data_queue = data_queue
self.setWindowTitle("Robocup")
# 增大窗口的最小尺寸
self.setMinimumSize(1200, 800)
self.textbutton = False
self.should_clear_queue = False
self.should_clear_queueimg = False
self.video_thread = None
self.desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop', 'results_r')
self.detection_result = []
self.detnum=0
self.detresultnum=[]
self.signal=False
# 创建Flask线程
from flasksignal import run_flask_app
self.flask_thread = FlaskThread(run_flask_app)
self.flask_thread.emitter.new_data.connect(self.update_display)
self.flask_thread.start()
self.should_clear_queue = True
# 初始化UI
self.init_ui()
# 启动定时器检查数据队列
self.timer = QTimer(self)
self.timer.timeout.connect(self.check_data_queue)
self.timer.start(0)
self._auto_started = False
# 连接窗口显示事件
self.showEvent = self.window_shown
def window_shown(self,event):
if not self._auto_started:
self._auto_started = True
self.auto_start()
return super().showEvent(event)
def auto_start(self):
self.start_flask_thread()
def init_ui(self):
# 创建主布局
main_layout = QHBoxLayout(self)
# 创建左侧Splitter
left_splitter = QSplitter(Qt.Vertical)
self.image_label = QLabel("图像显示区域")
self.image_label.setAlignment(Qt.AlignCenter)
# 更改图像显示区域的背景颜色
self.image_label.setStyleSheet("background-color: #e0e0e0; border: 2px solid #888;")
# 按钮区域
button_splitter = QSplitter(Qt.Horizontal)
self.show_image_btn = QPushButton("展示图像")
self.end_image_btn = QPushButton("结束图像")
# 优化按钮的样式,增大按钮大小和文字大小
self.show_image_btn.setStyleSheet("background-color: #4CAF50; color: white; font-size: 18px; padding: 10px;")
self.end_image_btn.setStyleSheet("background-color: #F44336; color: white; font-size: 18px; padding: 10px;")
self.show_image_btn.setMaximumHeight(60)
self.end_image_btn.setMaximumHeight(60)
button_splitter.addWidget(self.show_image_btn)
button_splitter.addWidget(self.end_image_btn)
left_splitter.addWidget(self.image_label)
left_splitter.addWidget(button_splitter)
# 扩大显示界面的位置比例
left_splitter.setSizes([600, 60])
# 创建右侧区域
right_widget = QWidget()
right_layout = QVBoxLayout(right_widget)
self.text_edit = QTextEdit()
self.text_edit.setReadOnly(True)
# 更改文本编辑区域的样式,背景设为黑色,文字设为白色,增大文字大小
self.text_edit.setStyleSheet("background-color: #000000; color: #ffffff; border: 2px solid #888; font-size: 16px;")
right_layout.addWidget(self.text_edit)
button_layout = QHBoxLayout()
self.end_btn = QPushButton("开始")
self.start_btn = QPushButton("结束")
self.force_quit_btn = QPushButton("退出")
# 优化按钮的样式,增大按钮大小和文字大小
self.end_btn.setStyleSheet("background-color: #2196F3; color: white; font-size: 18px; padding: 10px;")
self.start_btn.setStyleSheet("background-color: #FF9800; color: white; font-size: 18px; padding: 10px;")
self.force_quit_btn.setStyleSheet("background-color: #ff4444; color: white; font-size: 18px; padding: 10px;")
button_layout.addWidget(self.end_btn)
button_layout.addWidget(self.start_btn)
button_layout.addWidget(self.force_quit_btn)
right_layout.addLayout(button_layout)
# 将左右区域添加到主布局
main_splitter = QSplitter(Qt.Horizontal)
main_splitter.addWidget(left_splitter)
main_splitter.addWidget(right_widget)
# 扩大显示界面的位置比例
main_splitter.setSizes([800, 400])
main_layout.addWidget(main_splitter)
# 连接按钮点击事件
self.end_btn.clicked.connect(self.start_flask_thread)
self.start_btn.clicked.connect(self.set_clear_queue_flag)
self.show_image_btn.clicked.connect(self.start_flask_threadimg)
self.end_image_btn.clicked.connect(self.set_clear_queue_flagimg)
self.force_quit_btn.clicked.connect(self.force_quit)
def start_flask_threadimg(self):
self.should_clear_queueimg = True
self.signal=True
if self.video_thread is None :
self.video_thread = VideoThread("http://127.0.0.1:5002/")
self.video_thread.change_pixmap_signal.connect(self.update_image)
self.video_thread.start()
if not self.video_thread.isRunning():
self.video_thread.change_pixmap_signal.connect(self.update_image)
self.video_thread.start()
def set_clear_queue_flagimg(self):
self.should_clear_queueimg = False
if self.video_thread:
self.image_label.clear()
def start_flask_thread(self):
team_id = "eeem001"
client.send_team_id(team_id)
time.sleep(0.1) # 给服务器处理时间
self.should_clear_queue = False
self.signal=True
self.start_flask_threadimg()
if not self.flask_thread.isRunning():
self.flask_thread.start()
def set_clear_queue_flag(self):
self.should_clear_queue = True
def check_data_queue(self):
if self.should_clear_queue:
while not self.data_queue.empty():
self.data_queue.get()
else:
while not self.data_queue.empty():
data = self.data_queue.get()
self.flask_thread.emitter.new_data.emit(data)
def update_display(self, data):
self.detection_result.append(data)
if data["state"]=="last" :
self.detnum=self.detnum+1
print( self.detnum)
if self.detnum==100:
#print(self.detection_result)
for it in self.detection_result:
if self.detresultnum==None:
self.detresultnum.append({"ID":it["ID"],"num":it["num"]})
else:
flag=0
for itnum in self.detresultnum:
if itnum["ID"]==it["ID"]:
itnum["num"]=itnum["num"]+it["num"]
flag=1
if flag==0:
self.detresultnum.append({"ID":it["ID"],"num":it["num"]})
#content=self.text_edit.toPlainText()
#print(content)
#if not content.strip():
self.text_edit.clear()
for it in self.detresultnum:
import math
#print(it["num"])
it["num"]=(it["num"]/(self.detnum+1))
integer_part=int(it["num"])
dec_part=it["num"]-integer_part
if dec_part<0.15:
it["num"]=int(it["num"])
else:
it["num"]=int(it["num"]+1)
if it["num"]==0:
continue
#self.text_edit.append("目标ID:" + it["ID"] + " 数量:" + str(it["num"]))
self.text_edit.append(f"目标ID:{it['ID']} 数量:{it['num']}")
self.text_edit.moveCursor(self.text_edit.textCursor().End)
self.save_txt()
#signal = 1
#self.force_quit()
#try:
#self.client.connect()
#file_path = os.path.join(self.desktop_path, "shdjxy-team-Rx.txt")
#with open(file_path,'r',encoding='utf-8') as f:
# print(f.read())
#self.client.send_file(file_path, data_type=1)
#finally:
# import time
# time.sleep(0.3)
# self.client.close()
#写入文件,在桌面文件夹里 ---在update-data中
#写入属性self.datalast+传来的string---在update-data中
#如果为state==last 就是最后一次---在update-data中
def update_image(self, qimg):
if self.should_clear_queueimg:
pixmap = QPixmap.fromImage(qimg)
self.image_label.setPixmap(
pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
def force_quit(self):
reply = QMessageBox.question(
self, '确认退出',
"确定要退出所有程序吗?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No
)
if reply == QMessageBox.Yes:
# 停止视频线程
if hasattr(self, 'video_thread') and self.video_thread:
self.video_thread.stop()
#self.video_thread.wait()
# 停止Flask线程
if hasattr(self, 'flask_thread') and self.flask_thread.isRunning():
self.flask_thread.stop()
# 强制退出应用
QApplication.quit()
def save_txt(self):
os.makedirs(self.desktop_path, exist_ok=True)
file_name = f"shdjxy-team-Rx.txt"
file_path = os.path.join(self.desktop_path,file_name)
with open(file_path,'w',encoding='utf-8') as f:
f.write("START\n")
for result in self.detresultnum:
if result["num"]==0:
continue
line = f"Goal_ID={result['ID']};Num={result['num']}"
f.write(line+"\n")
f.write("END")
self.detection_result=[]
self.detnum=0
self.detresultnum=[]
self.set_clear_queue_flag()
file_path = r"/home/HwHiAiUser/Desktop/results_r/shdjxy-team-Rx.txt"
client.send_file(file_path, data_type=1)
time.sleep(0.1)
client.close()
if __name__ == "__main__":
app = QApplication(sys.argv)
from queue import Queue
data_queue = Queue()
window = MainWindow(data_queue)
window.show()
sys.exit(app.exec_())
写出软件界面及功能说明。
最新发布