国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

yolov5-Lite通過修改Detect.py代碼實現(xiàn)靈活的檢測圖像、視頻和打開攝像頭檢測

這篇具有很好參考價值的文章主要介紹了yolov5-Lite通過修改Detect.py代碼實現(xiàn)靈活的檢測圖像、視頻和打開攝像頭檢測。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

yolov5-Lite介紹

yolov5-Lite通過修改Detect.py代碼實現(xiàn)靈活的檢測圖像、視頻和打開攝像頭檢測,圖像識別,YOLO,音視頻
這里項目鏈接查看,或者這里下載。
經(jīng)過本人測試,與yolov5-7.0相比,訓練好的權(quán)重文件大小大約是yolov5-7.0的0.3倍(yolov5-Lite——3.4M,yolov5-7.0——13M),置信度均在0.9之上。特別的,我之所以使用此Lite改進算法,是因為需要部署在智能小車上實現(xiàn)圖像識別的功能,而小車上只有CPU,yolov5-7.0使用CPU計算的速度太慢了,一秒只能處理3張圖像,距離功能的要求還差些,而Lite算法的權(quán)重參數(shù)減少了很多,速度也相應快了一些,部署在小車上,使用CPU計算的速度快了0.8倍,不算很多,但也算是勉強能使用了,每秒5/6張圖片。

需求

算法自帶檢測圖片、視頻的detect.py腳本,但是拿來自己靈活的使用還是有許多問題,一般圖像檢測都是對實時性有要求,detect.py腳本是檢測本地的圖片視頻。我修改一部分代碼,將detect.py腳本寫成一個api,直接調(diào)用函數(shù),傳入一個img數(shù)組對象,即可輸出detections字典,包含各檢測對象的類別、位置信息、置信度。

修改代碼

原函數(shù)

def detect(save_img=False):
    source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
    save_img = not opt.nosave and not source.endswith('.txt')  # save inference images
    webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
        ('rtsp://', 'rtmp://', 'http://', 'https://'))

    # Directories
    save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # Initialize
    set_logging()
    device = select_device(opt.device)
    half = device.type != 'cpu'  # half precision only supported on CUDA

    # Load model
    model = attempt_load(weights, map_location=device)  # load FP32 model
    stride = int(model.stride.max())  # model stride
    imgsz = check_img_size(imgsz, s=stride)  # check img_size
    if half:
        model.half()  # to FP16

    # Second-stage classifier
    classify = False
    if classify:
        modelc = load_classifier(name='resnet101', n=2)  # initialize
        modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()

    # Set Dataloader
    vid_path, vid_writer = None, None
    if webcam:
        view_img = check_imshow()
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz, stride=stride)
    else:
        dataset = LoadImages(source, img_size=imgsz, stride=stride)

    # Get names and colors
    names = model.module.names if hasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]

    # Run inference
    if device.type != 'cpu':
        model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))  # run once
    t0 = time.time()
    for path, img, im0s, vid_cap in dataset:
        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)

        # Inference
        t1 = time_synchronized()
        pred = model(img, augment=opt.augment)[0]

        # Apply NMS
        pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
        t2 = time_synchronized()

        # Apply Classifier
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)

        # Process detections
        for i, det in enumerate(pred):  # detections per image
            if webcam:  # batch_size >= 1
                p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
            else:
                p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # img.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # img.txt
            s += '%gx%g ' % img.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)  # label format
                        with open(txt_path + '.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or view_img:  # Add bbox to image
                        label = f'{names[int(cls)]} {conf:.2f}'
                        plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)

            # Print time (inference + NMS)
            print(f'{s}Done. ({t2 - t1:.3f}s)')

            # Stream results
            if view_img:
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video' or 'stream'
                    if vid_path != save_path:  # new video
                        vid_path = save_path
                        if isinstance(vid_writer, cv2.VideoWriter):
                            vid_writer.release()  # release previous video writer
                        if vid_cap:  # video
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        else:  # stream
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
                            save_path += '.mp4'
                        vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
                    vid_writer.write(im0)

    if save_txt or save_img:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
        print(f"Results saved to {save_dir}{s}")

    print(f'Done. ({time.time() - t0:.3f}s)')

修改后的函數(shù)

class DETECT_API:
    def __init__(self,opt):
        weights,imgsz = opt.weights,opt.img_size
        self.device = select_device(opt.device)
        # device = device_ if torch.cuda.is_available() else 'cpu'  # 設(shè)置代碼執(zhí)行的設(shè)備 cuda device, i.e. 0 or 0,1,2,3 or cpu
        # self.device = device
        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA

        # self.imgsz = (imgsz, imgsz)  # 輸入圖片的大小 默認640(pixels)
        self.conf_thres = opt.conf_thres  # object置信度閾值 默認0.25  用在nms中
        self.iou_thres = opt.iou_thres  # 做nms的iou閾值 默認0.45   用在nms中
        # self.max_det = max_det  # 每張圖片最多的目標數(shù)量  用在nms中
        self.classes = opt.classes  # 在nms中是否是只保留某些特定的類 默認是None 就是所有類只要滿足條件都可以保留 --class 0, or --class 0 2 3
        self.agnostic_nms = opt.agnostic_nms  # 進行nms是否也除去不同類別之間的框 默認False
        self.augment = opt.augment  # 預測是否也要采用數(shù)據(jù)增強 TTA 默認False
        # self.visualize = False  # 特征圖可視化 默認FALSE
        # self.half = False  # 是否使用半精度 Float16 推理 可以縮短推理時間 但是默認是False
        # self.dnn = False  # 使用OpenCV DNN進行ONNX推理


        # Load model
        self.model = attempt_load(weights, map_location=self.device)  # load FP32 model
        if self.half:
            self.model.half()  # to FP16

        if self.device.type != 'cpu':
            self.model(torch.zeros(1, 3, imgsz, imgsz).to(self.device).type_as(next(self.model.parameters())))  # run once

        self.stride = int(self.model.stride.max())  # model stride
        self.imgsz = check_img_size(imgsz, s=self.stride)  # check img_size
        # Get names and colors
        self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
        colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]

    def detect2(self,img):
        '''
        檢測圖像,輸入圖片數(shù)組
        Args:
            img: 圖片數(shù)組

        Returns:字典{'class': cls, 'conf': conf, 'position': xywh}

        '''
        # Set Dataloader
        # dataset = LoadImages(img_path, img_size=self.imgsz, stride=self.stride)

        # 用于存放結(jié)果
        detections = []
        s = ''
        if True:
            # print(path)
            im0 = img*1
            # Padded resize
            img = letterbox(im0, self.imgsz, stride=self.stride)[0]
            # Convert
            img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
            img = ascontiguousarray(img) # np.ascontiguousarray(img)

            img = torch.from_numpy(img).to(self.device)
            img = img.half() if self.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)

            # Inference
            t1 = time_synchronized()
            pred = self.model(img, augment=self.augment)[0]

            # Apply NMS
            pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes=self.classes, agnostic=self.agnostic_nms)
            t2 = time_synchronized()


            # Process detections
            for i, det in enumerate(pred):  # detections per image
                s = '%gx%g ' % img.shape[2:]  # print string
                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):
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4))).view(-1).tolist()
                        xywh = [round(x) for x in xywh]
                        xywh = [xywh[0] - xywh[2] // 2, xywh[1] - xywh[3] // 2, xywh[2],
                                xywh[3]]  # 檢測到目標位置,格式:(left,top,w,h)

                        cls = self.names[int(cls)]
                        conf = float(conf)
                        detections.append({'class': cls, 'conf': conf, 'position': xywh})
                        # 輸出結(jié)果
        for i in detections:
            print(i)
        # Print time (inference + NMS)
        print(f'{s}Done. ({t2 - t1:.3f}s)')
        return detections

將代碼封裝為一個類,先載入模型,之后就可以傳入圖像進行圖像檢測了。
未來更好測試,寫了各簡單的GUI。使用python自帶的tkinter庫實現(xiàn)。

# 界面設(shè)計
    detect_state = False
    top = tk.Tk()
    top.title('YOLOV5-Lite Detect')
    top['bg'] = 'white'
    width = 300
    height = 150
    win_width = top.winfo_screenwidth()
    win_height = top.winfo_screenheight()
    center_place = str(int(win_width/2 - width/2))+'+'+str(int(win_height/2 - height/2))
    top.geometry(str(width)+'x'+str(height)+'+'+center_place)

    label = tk.Label(top,text='path')
    label.pack(fill='both')
    btn_img = tk.Button(top,text='選擇圖片',command=select_img)
    btn_img.pack(fill='both')
    btn_video = tk.Button(top,text='選擇視頻',command=select_video)
    btn_video.pack(fill='both')

    btn_detect = tk.Button(top,text='DETECT',command=mt_detect)
    btn_detect.pack(fill='both')

    top.mainloop()

完整代碼(調(diào)用接口腳本)

import tkinter as tk
from tkinter import filedialog#用于打開文件  核心:filepath = filedialog.askopenfilename() #獲得選擇好的文件,單個文件

import argparse
import time
from pathlib import Path

import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random, ascontiguousarray


from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages, letterbox
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
    scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
from utils.plots import plot_one_box
from utils.torch_utils import select_device, load_classifier, time_synchronized

class DETECT_API:
    def __init__(self,opt):
        weights,imgsz = opt.weights,opt.img_size
        self.device = select_device(opt.device)
        # device = device_ if torch.cuda.is_available() else 'cpu'  # 設(shè)置代碼執(zhí)行的設(shè)備 cuda device, i.e. 0 or 0,1,2,3 or cpu
        # self.device = device
        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA

        # self.imgsz = (imgsz, imgsz)  # 輸入圖片的大小 默認640(pixels)
        self.conf_thres = opt.conf_thres  # object置信度閾值 默認0.25  用在nms中
        self.iou_thres = opt.iou_thres  # 做nms的iou閾值 默認0.45   用在nms中
        # self.max_det = max_det  # 每張圖片最多的目標數(shù)量  用在nms中
        self.classes = opt.classes  # 在nms中是否是只保留某些特定的類 默認是None 就是所有類只要滿足條件都可以保留 --class 0, or --class 0 2 3
        self.agnostic_nms = opt.agnostic_nms  # 進行nms是否也除去不同類別之間的框 默認False
        self.augment = opt.augment  # 預測是否也要采用數(shù)據(jù)增強 TTA 默認False
        # self.visualize = False  # 特征圖可視化 默認FALSE
        # self.half = False  # 是否使用半精度 Float16 推理 可以縮短推理時間 但是默認是False
        # self.dnn = False  # 使用OpenCV DNN進行ONNX推理


        # Load model
        self.model = attempt_load(weights, map_location=self.device)  # load FP32 model
        if self.half:
            self.model.half()  # to FP16

        if self.device.type != 'cpu':
            self.model(torch.zeros(1, 3, imgsz, imgsz).to(self.device).type_as(next(self.model.parameters())))  # run once

        self.stride = int(self.model.stride.max())  # model stride
        self.imgsz = check_img_size(imgsz, s=self.stride)  # check img_size
        # Get names and colors
        self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
        colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]

    def detect(self,img_path):
        '''
        檢測圖像,輸入圖片路徑,不能輸入視頻路徑
        Args:
            img_path: 圖片路徑

        Returns:字典{'class': cls, 'conf': conf, 'position': xywh}

        '''
        # Set Dataloader
        dataset = LoadImages(img_path, img_size=self.imgsz, stride=self.stride)

        # 用于存放結(jié)果
        detections = []
        s = ''
        for path, img, im0s, vid_cap in dataset:
            print(path)
            img = torch.from_numpy(img).to(self.device)
            img = img.half() if self.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)

            # Inference
            t1 = time_synchronized()
            pred = self.model(img, augment=self.augment)[0]

            # Apply NMS
            pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes=self.classes, agnostic=self.agnostic_nms)
            t2 = time_synchronized()


            # Process detections
            for i, det in enumerate(pred):  # detections per image
                s = '%gx%g ' % img.shape[2:]  # print string
                im0 = im0s
                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):
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4))).view(-1).tolist()
                        xywh = [round(x) for x in xywh]
                        xywh = [xywh[0] - xywh[2] // 2, xywh[1] - xywh[3] // 2, xywh[2],
                                xywh[3]]  # 檢測到目標位置,格式:(left,top,w,h)

                        cls = self.names[int(cls)]
                        conf = float(conf)
                        detections.append({'class': cls, 'conf': conf, 'position': xywh})
                        # 輸出結(jié)果
        for i in detections:
            print(i)
        # Print time (inference + NMS)
        print(f'{s}Done. ({t2 - t1:.3f}s)')
        return detections

    def detect2(self,img):
        '''
        檢測圖像,輸入圖片數(shù)組
        Args:
            img: 圖片數(shù)組

        Returns:字典{'class': cls, 'conf': conf, 'position': xywh}

        '''
        # Set Dataloader
        # dataset = LoadImages(img_path, img_size=self.imgsz, stride=self.stride)

        # 用于存放結(jié)果
        detections = []
        s = ''
        if True:
            # print(path)
            im0 = img*1
            # Padded resize
            img = letterbox(im0, self.imgsz, stride=self.stride)[0]
            # Convert
            img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
            img = ascontiguousarray(img) # np.ascontiguousarray(img)

            img = torch.from_numpy(img).to(self.device)
            img = img.half() if self.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)

            # Inference
            t1 = time_synchronized()
            pred = self.model(img, augment=self.augment)[0]

            # Apply NMS
            pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes=self.classes, agnostic=self.agnostic_nms)
            t2 = time_synchronized()


            # Process detections
            for i, det in enumerate(pred):  # detections per image
                s = '%gx%g ' % img.shape[2:]  # print string
                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):
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4))).view(-1).tolist()
                        xywh = [round(x) for x in xywh]
                        xywh = [xywh[0] - xywh[2] // 2, xywh[1] - xywh[3] // 2, xywh[2],
                                xywh[3]]  # 檢測到目標位置,格式:(left,top,w,h)

                        cls = self.names[int(cls)]
                        conf = float(conf)
                        detections.append({'class': cls, 'conf': conf, 'position': xywh})
                        # 輸出結(jié)果
        for i in detections:
            print(i)
        # Print time (inference + NMS)
        print(f'{s}Done. ({t2 - t1:.3f}s)')
        return detections

def select_img():
    global detect_state
    pass
    filepath = filedialog.askopenfilename(title='選擇圖片',filetypes=[('圖片', '*.jpg *.png'), ('All files', '*')])
    label['text'] = filepath
    detect_state = 1
def select_video():
    global detect_state
    pass
    filepath = filedialog.askopenfilename(title='選擇視頻', filetypes=[('視頻', '*.mp4'), ('All files', '*')])
    label['text'] = filepath
    detect_state = 2

def mt_detect():
    global detect_state
    pass
    path = label['text']
    print(path)
    if not detect_state:
        print('請選擇圖片或視頻')
    else:
        # opt.source = path
        if detect_state == 1:
            show_img(path)
        elif detect_state == 2:
            show_video(path)

    detect_state = 0

def show_img(img_path):
    # # 傳入圖片路徑
    # detections = Detect.detect(img_path)

    # print(detections)
    img = cv2.imread(img_path)

    t1 = time.time()
    detections = Detect.detect2(img)
    t2 = time.time()
    for i in detections:
        # print(i)
        x, y, w, h = i['position']
        img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)
        img = cv2.putText(img, "{} {}".format(i['class'], round(i['conf'], 4)), (x, y - 5),
                          cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1,
                          cv2.LINE_AA)
    img = cv2.putText(img, "{}s".format( round((t2 - t1), 3)),
                      (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 1, cv2.LINE_AA)

    cv2.imshow('yolov5-Lite img', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def show_video(video_path):
    cap = cv2.VideoCapture(video_path)
    while cap.isOpened():
        ret, img = cap.read()
        if ret:
            pass
            t1 = time.time()
            detections = Detect.detect2(img)
            t2 = time.time()
            for i in detections:
                # print(i)
                x, y, w, h = i['position']
                img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)
                img = cv2.putText(img, "{} {}".format(i['class'], round(i['conf'], 4)), (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA)
            img = cv2.putText(img, "{}FPS - {}s".format(round(1/(t2-t1),2), round((t2-t1),3)), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 1,cv2.LINE_AA)

            cv2.imshow('yolov5-Lite img', img)
            # cv2.waitKey(1000)
            if cv2.waitKey(10) == ord('q'):
                break
        else:
            break
    cap.release()
    cv2.destroyAllWindows()



if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp9/weights/best.pt',
                        help='model.pt path(s)')
    #parser.add_argument('--source', type=str,default='',help='source')  # file/folder, 0 for webcam
    parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
    parser.add_argument('--conf-thres', type=float, default=0.45, help='object confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
    parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='display results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default='runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    opt = parser.parse_args()
    print(opt)
    check_requirements(exclude=('pycocotools', 'thop'))

    # 初始化模型
    Detect = DETECT_API(opt)
    print('初始化完成/n')

    # 界面設(shè)計
    detect_state = False
    top = tk.Tk()
    top.title('YOLOV5-Lite Detect')
    top['bg'] = 'white'
    width = 300
    height = 150
    win_width = top.winfo_screenwidth()
    win_height = top.winfo_screenheight()
    center_place = str(int(win_width/2 - width/2))+'+'+str(int(win_height/2 - height/2))
    top.geometry(str(width)+'x'+str(height)+'+'+center_place)

    label = tk.Label(top,text='path')
    label.pack(fill='both')
    btn_img = tk.Button(top,text='選擇圖片',command=select_img)
    btn_img.pack(fill='both')
    btn_video = tk.Button(top,text='選擇視頻',command=select_video)
    btn_video.pack(fill='both')

    btn_detect = tk.Button(top,text='DETECT',command=mt_detect)
    btn_detect.pack(fill='both')

    top.mainloop()

如何運行

首先,你需要配置yolov5-Lite算法的運行環(huán)境,使能夠正確的訓練模型。配置過程與yolov5-7.0一致,如果報錯,檢測對應的庫的版本是否符合條件,一般不需要最新的庫,庫的版本不要太高。訓練好模型權(quán)重之后,parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp9/weights/best.pt', help='model.pt path(s)')修改成自己的權(quán)重路徑即可。

一些截圖

yolov5-Lite通過修改Detect.py代碼實現(xiàn)靈活的檢測圖像、視頻和打開攝像頭檢測,圖像識別,YOLO,音視頻
紅色警告是torch版本問題,可以忽略,暫時沒發(fā)現(xiàn)有什么影響。
yolov5-Lite通過修改Detect.py代碼實現(xiàn)靈活的檢測圖像、視頻和打開攝像頭檢測,圖像識別,YOLO,音視頻

最后

先到這吧,有問題可評論。文章來源地址http://www.zghlxwxcb.cn/news/detail-764807.html

到了這里,關(guān)于yolov5-Lite通過修改Detect.py代碼實現(xiàn)靈活的檢測圖像、視頻和打開攝像頭檢測的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 樹莓派4B使用NCNN部署Yolov5-lite

    樹莓派4B使用NCNN部署Yolov5-lite

    目錄 文章目錄 前言 一、樹莓派配置NCNN 1.安裝依賴 2.下載NCNN并編譯 二、Yolov5-lite模型訓練 1.源碼地址 2.安裝所需要的包? 3.訓練自己的數(shù)據(jù)集(YOLO格式) 4.模型訓練? 5.模型轉(zhuǎn)換 6.onnx模型簡化 三、樹莓派部署lite模型 1.將onnx模型轉(zhuǎn)換為ncnn 2.添加Yolov5-lite.cpp 3.修改eopt.param ?4.修

    2024年02月05日
    瀏覽(27)
  • 基于樹莓派Qt+opencv+yolov5-Lite+C++部署深度學習推理

    基于樹莓派Qt+opencv+yolov5-Lite+C++部署深度學習推理

    ? ? ? ? 本文是基于 qt和opencv的dnn 深度學習推理模塊,在樹莓派上部署YOLO系列推理,適用于yolov5-6.1以及yolov5-Lite,相比直接用python的onnxruntime,用基于opencv的dnn模塊,利用訓練生成的onnx模型,即可快速部署,不需要在樹莓派上額外安裝深度學習的一系列環(huán)境,因為我們知道

    2024年04月16日
    瀏覽(135)
  • YOLOV5-LITE實時目標檢測(onnxruntime部署+opencv獲取攝像頭+NCNN部署)python版本和C++版本

    使用yolov5-lite自帶的export.py導出onnx格式,圖像大小設(shè)置320,batch 1 之后可以使用 onnxsim對模型進一步簡化 onnxsim參考鏈接:onnxsim-讓導出的onnx模型更精簡_alex1801的博客-CSDN博客 這個版本的推理FPS能有11+FPS 這兩處換成自己的模型和訓練的類別即可: ??? parser.add_argument(\\\'--modelpa

    2024年02月04日
    瀏覽(30)
  • Python —— 解析Yolov5 - detect.py

    Python —— 解析Yolov5 - detect.py

    Yolov5自帶detect.py加入cv2簡單操作 ?????說明:im0為mat的原圖 ? ? detect.py參數(shù)解析 ?????1、運行detect.py的兩種方式: ??????????(1)、 使用命令 : ???????????????python detect.py --source ./testfiles/img1.jpg --weights runs/train/base/weights/best.pt --c

    2024年02月12日
    瀏覽(25)
  • yolov5的推理輸出detect.py部分

    ????推理階段是整個檢測模型完成后,要對模型進行測試的部分。很重要的一部分,只有了解了這個部分,才能在比賽或者項目提交中很好的輸出自己模型的檢測結(jié)果。同時,推理輸出對模型部署在不同的環(huán)境下也是十分重要的。 源碼:https://github.com/ultralytics/yolov5 版本

    2024年02月04日
    瀏覽(26)
  • YOLOv5-6.x源碼分析(一)---- detect.py

    這算是我的第一個正式博客文章吧,在準備動手寫內(nèi)容的時候,都有點無從下手的感覺。anyway,以后應該會寫的越來越嫻熟的。 YOLO系列我已經(jīng)用了接近一年了吧,從去年暑假開始學習,打算入坑深度學習,其中跑過demo,自己用Flask搭配YOLOv5寫過網(wǎng)頁端實時檢測,還看過源碼

    2024年02月16日
    瀏覽(16)
  • YOLOv5的Tricks | 【Trick13】YOLOv5的detect.py腳本的解析與簡化

    如有錯誤,懇請指出。 在之前介紹了一堆yolov5的訓練技巧,train.py腳本也介紹得差不多了。之后還有detect和val兩個腳本文件,還想把它們總結(jié)完。 在之前測試yolov5訓練好的模型時,用detect.py腳本簡直不要太方便,覺得這個腳本集成了很多功能,今天就分析源碼一探究竟。 關(guān)

    2023年04月08日
    瀏覽(19)
  • 【Yolov5】保姆級別源碼講解之-推理部分detect.py文件

    【Yolov5】保姆級別源碼講解之-推理部分detect.py文件

    克隆一下yolov5的代碼 配置好項目所需的依賴包 opt 為執(zhí)行可以傳遞的參數(shù) 具體的參數(shù)如圖所示,比較重要的參數(shù) weights權(quán)重文件、–source 數(shù)據(jù)集合 – data 數(shù)據(jù)集的配置 weights 權(quán)重文件 – source 為需要推理的原圖 data參數(shù) 數(shù)據(jù)配置 imgsz 參數(shù)是訓練配置圖片的大小 device 設(shè)備信

    2024年02月08日
    瀏覽(47)
  • YOLOv5源碼逐行超詳細注釋與解讀(2)——推理部分detect.py

    YOLOv5源碼逐行超詳細注釋與解讀(2)——推理部分detect.py

    前面簡單介紹了YOLOv5的項目目錄結(jié)構(gòu)(直通車:YOLOv5源碼逐行超詳細注釋與解讀(1)——項目目錄結(jié)構(gòu)解析),對項目整體有了大致了解。 今天要學習的是 detect.py 。通常這個文件是用來預測一張圖片或者一個視頻的,也可以預測一個圖片文件夾或者是一些網(wǎng)絡(luò)流。下載后直

    2023年04月18日
    瀏覽(31)
  • 魔改并封裝 YoloV5 Version7 的 detect.py 成 API接口以供 python 程序使用

    魔改并封裝 YoloV5 Version7 的 detect.py 成 API接口以供 python 程序使用

    YoloV5 作為 YoloV4 之后的改進型,在算法上做出了優(yōu)化,檢測的性能得到了一定的提升。其特點之一就是權(quán)重文件非常的小,可以在一些配置更低的移動設(shè)備上運行,且提高速度的同時準確度更高。具體的性能見下圖[^1]。本次使用的是最新推出的 YoloV5 Version7 版本。 GitHub 地址

    2024年01月17日
    瀏覽(19)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包