基于Pytorch搭建yolov5环境训练自己的数据集(中药饮片识别系统)
基于Pytorch搭建YOLOV5 6.1环境利用PYQT5实现中药饮片检测系统
完整的详细步骤,亲测实现,可能只适合yolov5 6.1版本,只适用于小白,大佬请绕行,希望大家可以得到帮助,也希望大家可以指正错误。
一.配置YOLOV5 6.1版本的虚拟环境
1.安装Anaconda
没有安装的可以 跳转这个网址链接: Anaconda安装教程(超详细)
2.使用Anaconda创建虚拟环境

输入conda create -n new_yolov5 python=3.8
new_yolov5是你虚拟环境的名称,可以替换,这里选用 python为3.8版本

conda activate new_yolov5
这里的new_yolov5替换成你的虚拟环境的名称
激活环境成成功

二.安装CUDA和CUDANN
我这里选用的是cuda10.2,如果全盘按照我的方案走,建议使用cuda10.2版本
这里提供cuda10.2版本的cuda和与之对应的cudann的百度网盘下载方式(官网下载需要注册账号,下载比较慢)
cuda下载: 百度网盘地址 ,提取码:hi86
cudnn下载: 百度网盘地址,提取码:e0qq
安装步骤:参考这一部分进行安装(选择好cuda的版本,并且cudann需要与cuda对应)----链接: Cuda和cuDNN安装教程(超级详细)
三.安装Pytorch
进入pytorch官网: 地址
选择之前的版本
我们选择pytorch1.71版本
复制conda install pytorch==1.7.1 torchvision==0.8.2 torchaudio==0.7.2 cudatoolkit=10.2 -c pytorch
根据最新的官网方式复制,这里只是进行演示。
提醒:这里普通网下载会很慢,经常出错
有条件的挂梯子,无条件的可以查找别的方式或者私信我,看到就会回复。(伸手党勿扰)
这时候需要打开之前的虚拟环境,粘贴conda install pytorch==1.7.1 torchvision==0.8.2 torchaudio==0.7.2 cudatoolkit=10.2 -c pytorch
需要等待一小段时间,请耐心等待。
输入y进行安装依赖包
出现这一部分部分依赖安装完成
安装完成后进行测试,验证pytoch是否下载成功,cuda是否可用:
import torch
torch.cuda.is_available()

出现True表示成功。
如果False,重新安装pytorch
卸载指令:pip uninstall torch
四.下载YOLOV5 6.1版本
yolov5 6.1版本官网地址: yolov5-6.1,其他版本自行下载(github网站可能比较慢,挂梯子或者使用steam++加速器进行加速)
这里以为大家提供源码下载地址:
链接: 百度网盘地址,提取码:1w99
下滑找到这里,进行下载
打开下载好的yolov5-6.1文件,在地址这里输入cmd后回车
进入cmd,输入activate new_yolov5 ,
然后下载yolov5所需要的依赖包:pip install -r requirements.txt
这里可以选择使用镜像:清华源,豆瓣源等;
下载方式为:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt

我这里使用的是‘自己的方式’,就不再用其他源了。
安装完成后会显示successfully
五.准备数据集
这里有已经写好的处理数据的文件
下载地址: 百度网盘下载地址
提取码:ber9
下载之后建议将这个文件名称改为英文路径
下载好的目录结构如下
首先我们将已经处理好的图像放在JPEGImages下
然后将相应的xml文件放在Annotations下
如下所示:(注意:图像需要与xml对应,建议使用labelimg进行数据标注)
建议将标注好的图像进行备份


然后运行split_train_val.py
再运行transform.py



成功复制到绝对路径
运行完毕之后,会在VOC2007同级目录下生成images和labels两个文件
这两个文件就是我们将来需要训练的文件
然后我们将这两个文件进行复制,然后在yolov5-6.1同级目录下新建datasets
在datasets下再新建VOC
在VOC下粘贴images和labels文件
六.修改yolov5配置文件
进入yolov5-6.1文件中
1.VOC.yaml配置


2.配置yolov5s.yaml

七.训练
首先先下载预训练权重
在同级目录下新建weights,将下载好的预训练权重放到这里
地址还是在GitHub上,下载需要的.pt文件(我这里使用的是yolov5s.pt)
我这里依旧提供了下载地址
百度网盘下载地址: yolov5s.pt
提取码:u4kw
修改train.py
方法1:修改后运行train.py即可
方法2:用云服务器跑(速度快,不占用自己的电脑)本人亲测有效
这里推荐使用锯齿云, 锯齿云地址官网
填写邀请码会赠送118元礼包,和随机时长
1.手机扫码:
2.邀请码填写:vwJnzr3c8iQZdJp
进入之后我们可以将我们需要处理的数据放到我的网盘中,这里也可以下载客户端版到本地,同理将需要处理的数据放到这里。
下面是演示视频:
教程
最后训练好的权重会在如下的路径中,自行下载即可
八.自己的中药饮片检测识别项目
1.系统展示:


2.数据集:(团队相机拍摄,数据采集不易)
内含6种数据:
天麻:
苍术:
枳实:
砂仁:
太子参:
莲子:
主函数代码:
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMenu, QAction
# from main_win.win import Ui_mainWindow
from PyQt5.uic.properties import QtGui, QtCore
from main_win.ui_win import Ui_mainWindow
from PyQt5.QtCore import Qt, QPoint, QTimer, QThread, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap, QPainter, QIcon
import sys
import os
import json
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import os
import time
import cv2
from models.experimental import attempt_load
from utils.datasets import LoadImages, LoadWebcam
from utils.CustomMessageBox import MessageBox
from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \
apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
# from utils.plots import colors, plot_one_box, plot_one_box_PIL
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device
from utils.capnums import Camera
from dialog.rtsp_win import Window
class DetThread(QThread):
send_img = pyqtSignal(np.ndarray)
send_raw = pyqtSignal(np.ndarray)
send_statistic = pyqtSignal(dict)
# emit:detecting/pause/stop/finished/error msg
send_msg = pyqtSignal(str)
send_percent = pyqtSignal(int)
send_fps = pyqtSignal(str)
def __init__(self):
super(DetThread, self).__init__()
self.weights = './weights/药片识别.pt'
self.current_weight = './weights/药片识别.pt'
self.source = '0'
self.conf_thres = 0.25
self.iou_thres = 0.45
self.jump_out = False # jump out of the loop
self.is_continue = True # continue/pause
self.percent_length = 1000 # progress bar
self.rate_check = True # Whether to enable delay
self.rate = 100
self.save_fold = './result'
@torch.no_grad()
def run(self,
imgsz=640, # inference size (pixels)
max_det=1000, # maximum detections per image
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
view_img=True, # show results
save_txt=False, # save results to *.txt
save_conf=False, # save confidences in --save-txt labels
save_crop=False, # save cropped prediction boxes
nosave=False, # do not save images/videos
classes=None, # filter by class: --class 0, or --class 0 2 3
agnostic_nms=False, # class-agnostic NMS
augment=False, # augmented inference
visualize=False, # visualize features
update=False, # update all models
project='runs/detect', # save results to project/name
name='exp', # save results to project/name
exist_ok=False, # existing project/name ok, do not increment
line_thickness=3, # bounding box thickness (pixels)
hide_labels=False, # hide labels
hide_conf=False, # hide confidences
half=False, # use FP16 half-precision inference
):
# Initialize
try:
device = select_device(device)
half &= device.type != 'cpu' # half precision only supported on CUDA
# Load model
model = attempt_load(self.weights, map_location=device) # load FP32 model
num_params = 0
for param in model.parameters():
num_params += param.numel()
stride = int(model.stride.max()) # model stride
imgsz = check_img_size(imgsz, s=stride) # check image size
names = model.module.names if hasattr(model, 'module') else model.names # get class names
if half:
model.half() # to FP16
# Dataloader
if self.source.isnumeric() or self.source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')):
view_img = check_imshow()
cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadWebcam(self.source, img_size=imgsz, stride=stride)
# bs = len(dataset) # batch_size
else:
dataset = LoadImages(self.source, img_size=imgsz, stride=stride)
# Run inference
if device.type != 'cpu':
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
count = 0
jump_count = 0
start_time = time.time()
dataset = iter(dataset)
while True:
if self.jump_out:
self.vid_cap.release()
self.send_percent.emit(0)
self.send_msg.emit('Stop')
if hasattr(self, 'out'):
self.out.release()
break
# change model
if self.current_weight != self.weights:
# Load model
model = attempt_load(self.weights, map_location=device) # load FP32 model
num_params = 0
for param in model.parameters():
num_params += param.numel()
stride = int(model.stride.max()) # model stride
imgsz = check_img_size(imgsz, s=stride) # check image size
names = model.module.names if hasattr(model, 'module') else model.names # get class names
if half:
model.half() # to FP16
# Run inference
if device.type != 'cpu':
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
self.current_weight = self.weights
if self.is_continue:
path, img, im0s, self.vid_cap = next(dataset)
# jump_count += 1
# if jump_count % 5 != 0:
# continue
count += 1
if count % 30 == 0 and count >= 30:
fps = int(30/(time.time()-start_time))
self.send_fps.emit('fps:'+str(fps))
start_time = time.time()
if self.vid_cap:
percent = int(count/self.vid_cap.get(cv2.CAP_PROP_FRAME_COUNT)*self.percent_length)
self.send_percent.emit(percent)
else:
percent = self.percent_length
statistic_dic = {name: 0 for name in names}
img = torch.from_numpy(img).to(device)
img = img.half() if half else img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
pred = model(img, augment=augment)[0]
# Apply NMS
pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes, agnostic_nms, max_det=max_det)
# Process detections
for i, det in enumerate(pred): # detections per image
im0 = im0s.copy()
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
# Write results
for *xyxy, conf, cls in reversed(det):
c = int(cls) # integer class
statistic_dic[names[c]] += 1
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
annotator.box_label(xyxy, label, color=colors(c, True))
if self.rate_check:
time.sleep(1/self.rate)
im0 = annotator.result()
self.send_img.emit(im0)
self.send_raw.emit(im0s if isinstance(im0s, np.ndarray) else im0s[0])
self.send_statistic.emit(statistic_dic)
if self.save_fold:
os.makedirs(self.save_fold, exist_ok=True)
if self.vid_cap is None:
save_path = os.path.join(self.save_fold,
time.strftime('%Y_%m_%d_%H_%M_%S',
time.localtime()) + '.jpg')
cv2.imwrite(save_path, im0)
else:
if count == 1:
ori_fps = int(self.vid_cap.get(cv2.CAP_PROP_FPS))
if ori_fps == 0:
ori_fps = 25
# width = int(self.vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# height = int(self.vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width, height = im0.shape[1], im0.shape[0]
save_path = os.path.join(self.save_fold, time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime()) + '.mp4')
self.out = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), ori_fps,
(width, height))
self.out.write(im0)
if percent == self.percent_length:
print(count)
self.send_percent.emit(0)
self.send_msg.emit('finished')
if hasattr(self, 'out'):
self.out.release()
break
except Exception as e:
self.send_msg.emit('%s' % e)
class MainWindow(QMainWindow, Ui_mainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.m_flag = False
# style 1: window can be stretched
# self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint)
# style 2: window can not be stretched
self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint
| Qt.WindowSystemMenuHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint)
# self.setWindowOpacity(0.85) # Transparency of window
self.minButton.clicked.connect(self.showMinimized)
self.maxButton.clicked.connect(self.max_or_restore)
# show Maximized window
self.maxButton.animateClick(10)
self.closeButton.clicked.connect(self.close)
self.qtimer = QTimer(self)
self.qtimer.setSingleShot(True)
self.qtimer.timeout.connect(lambda: self.statistic_label.clear())
# search models automatically
self.comboBox.clear()
self.pt_list = os.listdir('./pt')
self.pt_list = [file for file in self.pt_list if file.endswith('.pt')]
self.pt_list.sort(key=lambda x: os.path.getsize('./pt/'+x))
self.comboBox.clear()
self.comboBox.addItems(self.pt_list)
self.qtimer_search = QTimer(self)
self.qtimer_search.timeout.connect(lambda: self.search_pt())
self.qtimer_search.start(2000)
# yolov5 thread
self.det_thread = DetThread()
self.model_type = self.comboBox.currentText()
self.det_thread.weights = "./pt/%s" % self.model_type
self.det_thread.source = '0'
self.det_thread.percent_length = self.progressBar.maximum()
self.det_thread.send_raw.connect(lambda x: self.show_image(x, self.raw_video))
self.det_thread.send_img.connect(lambda x: self.show_image(x, self.out_video))
self.det_thread.send_statistic.connect(self.show_statistic)
self.det_thread.send_msg.connect(lambda x: self.show_msg(x))
self.det_thread.send_percent.connect(lambda x: self.progressBar.setValue(x))
self.det_thread.send_fps.connect(lambda x: self.fps_label.setText(x))
# self.det_thread = DetThread()
# self.model_type = self.comboBox.currentText()
# self.det_thread.weights = "./pt/%s" % self.model_type
# self.det_thread.source = '0'
# self.det_thread.percent_length = self.progressBar.maximum()
# self.det_thread.send_raw.connect(lambda x: self.show_image(x, self.raw_video))
# self.det_thread.send_statistic.connect(self.show_statistic)
# self.det_thread.send_msg.connect(lambda x: self.show_msg(x))
# self.det_thread.send_percent.connect(lambda x: self.progressBar.setValue(x))
# self.det_thread.send_fps.connect(lambda x: self.fps_label.setText(x))
#
# if self.model_type == "质量检测.pt":
# self.det_thread.send_img.connect(lambda x: self.show_fixed_image(x, self.out_video))
# else:
# self.det_thread.send_img.connect(lambda x: self.show_image(x, self.out_video))
self.fileButton.clicked.connect(self.open_file)
self.cameraButton.clicked.connect(self.chose_cam)
self.rtspButton.clicked.connect(self.chose_rtsp)
self.runButton.clicked.connect(self.run_or_continue)
self.stopButton.clicked.connect(self.stop)
self.comboBox.currentTextChanged.connect(self.change_model)
self.confSpinBox.valueChanged.connect(lambda x: self.change_val(x, 'confSpinBox'))
self.confSlider.valueChanged.connect(lambda x: self.change_val(x, 'confSlider'))
self.iouSpinBox.valueChanged.connect(lambda x: self.change_val(x, 'iouSpinBox'))
self.iouSlider.valueChanged.connect(lambda x: self.change_val(x, 'iouSlider'))
self.rateSpinBox.valueChanged.connect(lambda x: self.change_val(x, 'rateSpinBox'))
self.rateSlider.valueChanged.connect(lambda x: self.change_val(x, 'rateSlider'))
self.checkBox.clicked.connect(self.checkrate)
self.saveCheckBox.clicked.connect(self.is_save)
self.load_setting()
# def show_fixed_image(self, img_src, label):
# pixmap = QPixmap("./show/famei_show.png")
# label.setPixmap(pixmap.scaled(label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
def search_pt(self):
pt_list = os.listdir('./pt')
pt_list = [file for file in pt_list if file.endswith('.pt')]
pt_list.sort(key=lambda x: os.path.getsize('./pt/' + x))
if pt_list != self.pt_list:
self.pt_list = pt_list
self.comboBox.clear()
self.comboBox.addItems(self.pt_list)
def is_save(self):
if self.saveCheckBox.isChecked():
self.det_thread.save_fold = './result'
else:
self.det_thread.save_fold = None
def checkrate(self):
if self.checkBox.isChecked():
self.det_thread.rate_check = True
else:
self.det_thread.rate_check = False
def chose_rtsp(self):
self.rtsp_window = Window()
config_file = 'config/ip.json'
if not os.path.exists(config_file):
ip = "rtsp://admin:admin888@192.168.1.67:555"
new_config = {"ip": ip}
new_json = json.dumps(new_config, ensure_ascii=False, indent=2)
with open(config_file, 'w', encoding='utf-8') as f:
f.write(new_json)
else:
config = json.load(open(config_file, 'r', encoding='utf-8'))
ip = config['ip']
self.rtsp_window.rtspEdit.setText(ip)
self.rtsp_window.show()
self.rtsp_window.rtspButton.clicked.connect(lambda: self.load_rtsp(self.rtsp_window.rtspEdit.text()))
def load_rtsp(self, ip):
try:
self.stop()
MessageBox(
self.closeButton, title='Tips', text='Loading rtsp stream', time=1000, auto=True).exec_()
self.det_thread.source = ip
new_config = {"ip": ip}
new_json = json.dumps(new_config, ensure_ascii=False, indent=2)
with open('config/ip.json', 'w', encoding='utf-8') as f:
f.write(new_json)
self.statistic_msg('Loading rtsp:{}'.format(ip))
self.rtsp_window.close()
except Exception as e:
self.statistic_msg('%s' % e)
def chose_cam(self):
try:
self.stop()
MessageBox(
self.closeButton, title='Tips', text='Loading camera', time=2000, auto=True).exec_()
# get the number of local cameras
_, cams = Camera().get_cam_num()
popMenu = QMenu()
popMenu.setFixedWidth(self.cameraButton.width())
popMenu.setStyleSheet('''
QMenu {
font-size: 16px;
font-family: "Microsoft YaHei UI";
font-weight: light;
color:white;
padding-left: 5px;
padding-right: 5px;
padding-top: 4px;
padding-bottom: 4px;
border-style: solid;
border-width: 0px;
border-color: rgba(255, 255, 255, 255);
border-radius: 3px;
background-color: rgba(200, 200, 200,50);}
''')
for cam in cams:
exec("action_%s = QAction('%s')" % (cam, cam))
exec("popMenu.addAction(action_%s)" % cam)
x = self.groupBox_5.mapToGlobal(self.cameraButton.pos()).x()
y = self.groupBox_5.mapToGlobal(self.cameraButton.pos()).y()
y = y + self.cameraButton.frameGeometry().height()
pos = QPoint(x, y)
action = popMenu.exec_(pos)
if action:
self.det_thread.source = action.text()
self.statistic_msg('Loading camera:{}'.format(action.text()))
except Exception as e:
self.statistic_msg('%s' % e)
def load_setting(self):
config_file = 'config/setting.json'
if not os.path.exists(config_file):
iou = 0.26
conf = 0.33
rate = 10
check = 0
savecheck = 0
new_config = {"iou": iou,
"conf": conf,
"rate": rate,
"check": check,
"savecheck": savecheck
}
new_json = json.dumps(new_config, ensure_ascii=False, indent=2)
with open(config_file, 'w', encoding='utf-8') as f:
f.write(new_json)
else:
config = json.load(open(config_file, 'r', encoding='utf-8'))
if len(config) != 5:
iou = 0.26
conf = 0.33
rate = 10
check = 0
savecheck = 0
else:
iou = config['iou']
conf = config['conf']
rate = config['rate']
check = config['check']
savecheck = config['savecheck']
self.confSpinBox.setValue(conf)
self.iouSpinBox.setValue(iou)
self.rateSpinBox.setValue(rate)
self.checkBox.setCheckState(check)
self.det_thread.rate_check = check
self.saveCheckBox.setCheckState(savecheck)
self.is_save()
def change_val(self, x, flag):
if flag == 'confSpinBox':
self.confSlider.setValue(int(x*100))
elif flag == 'confSlider':
self.confSpinBox.setValue(x/100)
self.det_thread.conf_thres = x/100
elif flag == 'iouSpinBox':
self.iouSlider.setValue(int(x*100))
elif flag == 'iouSlider':
self.iouSpinBox.setValue(x/100)
self.det_thread.iou_thres = x/100
elif flag == 'rateSpinBox':
self.rateSlider.setValue(x)
elif flag == 'rateSlider':
self.rateSpinBox.setValue(x)
self.det_thread.rate = x * 10
else:
pass
def statistic_msg(self, msg):
self.statistic_label.setText(msg)
# self.qtimer.start(3000)
def show_msg(self, msg):
self.runButton.setChecked(Qt.Unchecked)
self.statistic_msg(msg)
if msg == "Finished":
self.saveCheckBox.setEnabled(True)
def change_model(self, x):
self.model_type = self.comboBox.currentText()
self.det_thread.weights = "./pt/%s" % self.model_type
self.statistic_msg('Change model to %s' % x)
def open_file(self):
config_file = 'config/fold.json'
# config = json.load(open(config_file, 'r', encoding='utf-8'))
config = json.load(open(config_file, 'r', encoding='utf-8'))
open_fold = config['open_fold']
if not os.path.exists(open_fold):
open_fold = os.getcwd()
name, _ = QFileDialog.getOpenFileName(self, 'Video/image', open_fold, "Pic File(*.mp4 *.mkv *.avi *.flv "
"*.jpg *.png)")
if name:
self.det_thread.source = name
self.statistic_msg('Loaded file:{}'.format(os.path.basename(name)))
config['open_fold'] = os.path.dirname(name)
config_json = json.dumps(config, ensure_ascii=False, indent=2)
with open(config_file, 'w', encoding='utf-8') as f:
f.write(config_json)
self.stop()
def max_or_restore(self):
if self.maxButton.isChecked():
self.showMaximized()
else:
self.showNormal()
def run_or_continue(self):
self.det_thread.jump_out = False
if self.runButton.isChecked():
self.saveCheckBox.setEnabled(False)
self.det_thread.is_continue = True
if not self.det_thread.isRunning():
self.det_thread.start()
source = os.path.basename(self.det_thread.source)
source = 'camera' if source.isnumeric() else source
self.statistic_msg('Detecting >> model:{},file:{}'.
format(os.path.basename(self.det_thread.weights),
source))
else:
self.det_thread.is_continue = False
self.statistic_msg('Pause')
def stop(self):
self.det_thread.jump_out = True
self.saveCheckBox.setEnabled(True)
def mousePressEvent(self, event):
self.m_Position = event.pos()
if event.button() == Qt.LeftButton:
if 0 < self.m_Position.x() < self.groupBox.pos().x() + self.groupBox.width() and \
0 < self.m_Position.y() < self.groupBox.pos().y() + self.groupBox.height():
self.m_flag = True
def mouseMoveEvent(self, QMouseEvent):
if Qt.LeftButton and self.m_flag:
self.move(QMouseEvent.globalPos() - self.m_Position)
def mouseReleaseEvent(self, QMouseEvent):
self.m_flag = False
@staticmethod
def show_image(img_src, label):
try:
ih, iw, _ = img_src.shape
w = label.geometry().width()
h = label.geometry().height()
# keep original aspect ratio
if iw/w > ih/h:
scal = w / iw
nw = w
nh = int(scal * ih)
img_src_ = cv2.resize(img_src, (nw, nh))
else:
scal = h / ih
nw = int(scal * iw)
nh = h
img_src_ = cv2.resize(img_src, (nw, nh))
frame = cv2.cvtColor(img_src_, cv2.COLOR_BGR2RGB)
img = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[2] * frame.shape[1],
QImage.Format_RGB888)
label.setPixmap(QPixmap.fromImage(img))
except Exception as e:
print(repr(e))
# def show_statistic(self, statistic_dic):
# try:
# self.resultWidget.clear()
# statistic_dic = sorted(statistic_dic.items(), key=lambda x: x[1], reverse=True)
# statistic_dic = [i for i in statistic_dic if i[1] > 0]
# results = [' '+str(i[0]) + ':' + str(i[1]) for i in statistic_dic]
# self.resultWidget.addItems(results)
#
# except Exception as e:
# print(repr(e))
def show_statistic(self, statistic_dic):
try:
self.resultWidget.clear()
statistic_dic = sorted(statistic_dic.items(), key=lambda x: x[1], reverse=True)
statistic_dic = [i for i in statistic_dic if i[1] > 0]
# 创建拼音到汉语的映射字典
pinyin_to_hanzi = {
'zhishi': '枳实:\n 用于积滞内停,痞满胀痛,\n泻痢后重,大便不通,痰滞气阻,\n胸痹,结胸,脏器下垂。',
'taizishen': '太子参:\n 主治脾胃虚弱、食欲不振、\n倦怠无力、气阴两伤、\n干咳痰少的肺虚咳嗽,心悸自汗气短,\n以及温病后期气虚津伤内热口渴,\n或神经衰弱,心悸失眠,头昏健忘,\n小儿夏季热,并能够提高人体免疫功能,\n改善人体的心功能',
'cangzhu': '苍术:\n 起到较好的燥湿健脾之效,\n将其与清热药物配合使用\n则能够达到较好的除湿热之效,\n可用于治疗湿阻中焦\n而导致的脘腹胀满、腹泻等病症',
'lianzi': '莲子:\n清热泻火,还有显著的强心作用,\n能扩张外周血管,降低血压.\n可以治疗口舌生疮,并有助于睡眠',
'sharen': '砂仁:\n行气调中、和胃醒脾、理气安胎、\n温脾开胃、行气化滞等等这些功效,\n主要用于人体出现脾胃虚弱、\n脾胃气滞、湿阻中焦,\n表现在腹胀、腹痛、脾胃不和、食欲欠佳',
'tianma': '天麻:\n平肝息风,祛风止痛,\n有镇静、镇痛、抗惊厥作用;\n能增加脑血流量,降低脑血管阻力,\n轻度收缩脑血管,增加冠状血管流量;\n能降低血压,减慢心率,\n对心肌缺血有保护作用'
}
results = [' ' + pinyin_to_hanzi.get(i[0], i[0]) + '\n检测数:' + str(i[1]) for i in statistic_dic]
self.resultWidget.addItems(results)
except Exception as e:
print(repr(e))
def closeEvent(self, event):
self.det_thread.jump_out = True
config_file = 'config/setting.json'
config = dict()
config['iou'] = self.confSpinBox.value()
config['conf'] = self.iouSpinBox.value()
config['rate'] = self.rateSpinBox.value()
config['check'] = self.checkBox.checkState()
config['savecheck'] = self.saveCheckBox.checkState()
config_json = json.dumps(config, ensure_ascii=False, indent=2)
with open(config_file, 'w', encoding='utf-8') as f:
f.write(config_json)
MessageBox(
self.closeButton, title='Tips', text='Closing the program', time=2000, auto=True).exec_()
sys.exit(0)
if __name__ == "__main__":
app = QApplication(sys.argv)
myWin = MainWindow()
myWin.show()
# myWin.showMaximized()
sys.exit(app.exec_())
欢迎小伙伴们的采纳,需要数据集、整个项目的的私聊,采集不易,伸手党勿扰。
如果对你有帮助的话,点个赞收藏支持一下作者,十分感谢。
更多推荐


所有评论(0)