有谁知道如何将 tkinter 网络摄像头连接到 Yolov5?

2023-12-07

现在我正在使用 Yolov5 进行我的小项目,我想将相机界面更改为 tkinter (网络摄像头打开)进行设计

带有本地相机代码的 tkinter 是:

from tkinter import Tk, Label, Image
import cv2

win = Tk()
win.geometry("700x350")
label = Label(win)
label.grid(row=0, column=0)
cap = cv2.VideoCapture(0)

def show_frames():
    cv2image = cv2.cv2Color(cap.read()[1], cv2.COLOR_BGR2RGB)
    img = Image.fromarray(cv2image)

    imgtk = ImageTk.PhotoImage(image=img)
    label.imgtk = imgtk
    label.configure(image=imgtk)
    label.after(20, show_frames)

(抱歉评论)

  • 我添加了整个文件(运行 yolov5 的 detector.py)
# YOLOv5 ???? by Ultralytics, GPL-3.0 license
"""
Run inference on images, videos, directories, streams, etc.
Usage - sources:
    $ python path/to/detect.py --weights yolov5s.pt --source 0              # webcam
                                                             img.jpg        # image
                                                             vid.mp4        # video
                                                             path/          # directory
                                                             path/*.jpg     # glob
                                                             'https://youtu.be/Zgi9g1ksQHc'  # YouTube
                                                             'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream
Usage - formats:
    $ python path/to/detect.py --weights yolov5s.pt                 # PyTorch
                                         yolov5s.torchscript        # TorchScript
                                         yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn
                                         yolov5s.xml                # OpenVINO
                                         yolov5s.engine             # TensorRT
                                         yolov5s.mlmodel            # CoreML (macOS-only)
                                         yolov5s_saved_model        # TensorFlow SavedModel
                                         yolov5s.pb                 # TensorFlow GraphDef
                                         yolov5s.tflite             # TensorFlow Lite
                                         yolov5s_edgetpu.tflite     # TensorFlow Edge TPU
"""

import argparse
import os
import sys
from pathlib import Path
import subprocess
import eel
import time
from datetime import datetime as dt
from tkinter import *
from PIL import Image, ImageTk
import cv2
from datetime import datetime

import torch
import torch.backends.cudnn as cudnn

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
                           increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync
import sys

bread_name = '0'
bread_num = 0
bread_re = ''


@torch.no_grad()
def run(
        weights=ROOT / 'yolov5s.pt',  # model.pt path(s)
        source=ROOT / 'data/images',  # file/dir/URL/glob, 0 for webcam
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        imgsz=(640, 640),  # inference size (height, width)
        conf_thres=0.25,  # confidence threshold
        iou_thres=0.45,  # NMS IOU threshold
        max_det=1000,  # maximum detections per image
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img=False,  # 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=ROOT / '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
        dnn=False,  # use OpenCV DNN for ONNX inference
):
    ##파일 형식에 따른 선언
    #webcam은 tk에서 선언한 cap인데 실행할때의 source가 맞지 않아서 그런걸수도 있다...
    # show_frames(),win.mainloop()
    source = str(source)
    # source = show_frames(), win.mainloop()
    save_img = not nosave and not source.endswith('.txt')  # save inference images
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
    webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
    # webcam = cap
    if is_url and is_file:
        source = check_file(source)  # download

    # 디렉토리 선언
    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # 디바이스 선택 및 모델 로드 해오기
    # Load model
    device = select_device(device)
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
    stride, names, pt = model.stride, model.names, model.pt
    imgsz = check_img_size(imgsz, s=stride)  # check image size

    # 데이터 로드 해오기 웹캠이거나 다른거 일시
    # Dataloader
    if webcam:
        view_img = check_imshow()
        # view_img = True
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
        bs = len(dataset)  # batch_size
    else:
        # save_img = True
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
        bs = 1  # batch_size
    vid_path, vid_writer = [None] * bs, [None] * bs

    # Run inference
    # 데이터 런 시작 부분
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup
    seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
    for path, im, im0s, vid_cap, s in dataset:
        t1 = time_sync()
        im = torch.from_numpy(im).to(device)
        im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
        im /= 255  # 0 - 255 to 0.0 - 1.0
        if len(im.shape) == 3:
            im = im[None]  # expand for batch dim
        t2 = time_sync()
        dt[0] += t2 - t1

        # Inference
        visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
        pred = model(im, augment=augment, visualize=visualize)
        t3 = time_sync()
        dt[1] += t3 - t2

        # NMS
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
        dt[2] += time_sync() - t3

        # Second-stage classifier (optional)
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
        # Process predictions

        for i, det in enumerate(pred):  # per image
            seen += 1
            if webcam:  # batch_size >= 1
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
                s += f'{i}: '
            else:
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # im.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
            s += '%gx%g ' % im.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            imc = im0.copy() if save_crop else im0  # for save_crop
            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(im.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)},"  # 출력 결과 값

                    # 들어갈 변수들 선언해주기
                    global bread_re
                    re1 = str(n).split('(')
                    re2 = re1[1]
                    result = re2[:-1]
                    bread_name = names[int(c)]
                    bread_num = result
                    bread_re += bread_name + ' ' + bread_num + ','

                # 전부 선언 후 마지막 , 자르고 pos 부분 실행
                bread_re = bread_re.rstrip(',')
                now = str(datetime.today().replace(microsecond=0))
                # now = datetime.replace(microsecond=' ')

                f = open('soldlist.txt', 'a')
                f.write(now)
                f.write(bread_re)
                f.write('\n')

                f.close()
                pos()

                # 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 save_conf else (cls, *xywh)  # label format
                        with open(f'{txt_path}.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or save_crop or view_img:  # Add bbox to image
                        c = int(cls)  # integer class
                        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 save_crop:
                        save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

            # Stream results
            im0 = annotator.result()
            if view_img:
                if p not in windows:
                    windows.append(p)
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
                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[i] != save_path:  # new video
                        vid_path[i] = save_path
                        if isinstance(vid_writer[i], cv2.VideoWriter):
                            vid_writer[i].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 = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
                    vid_writer[i].write(im0)

        # Print time (inference-only)
        LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')

    # Print results
    t = tuple(x / seen * 1E3 for x in dt)  # speeds per image
    LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
    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 ''
        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
    if update:
        strip_optimizer(weights)  # update model (to fix SourceChangeWarning)

def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='show 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('--save-crop', action='store_true', help='save cropped prediction boxes')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 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('--visualize', action='store_true', help='visualize features')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default=ROOT / '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')
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(vars(opt))
    return opt

win = Tk()
win.geometry("700x350")
label = Label(win)
label.grid(row=0, column=0)
cap = cv2.VideoCapture(0)
cap = cv2.imread()

def show_frames():
    cv2image = cv2.cv2Color(cap.read()[1], cv2.COLOR_BGR2RGB)
    img = Image.fromarray(cv2image)

    imgtk = ImageTk.PhotoImage(image=img)
    label.imgtk = imgtk
    label.configure(image=imgtk)

label.after(20, show_frames)

# eel 닫힐때 함수 실행
def close_callback(route, websockets):
    if not websockets:
        run(**vars(opt))

def main(opt):
    check_requirements(exclude=('tensorboard', 'thop'))
    while 1:
        run(**vars(opt))

@eel.expose
def pos():
    global bread_re
    print('인식결과:' + bread_re)
    result = bread_re
    bread_re = ''

    # abc = input("계속 하시겠습니까?")
    # if abc == "n":
    eel.init("www2")
    eel.addText(result)
    eel.start("new.html", close_callback=close_callback, size=(2000, 1500), port=0)

    # else:
    #     return 0

@eel.expose
def reopen():
    executable = sys.executable
    args = sys.argv[:]
    args.insert(0, sys.executable)

    time.sleep(1) #1초후 재실행
    print("프로그램 재 실행")
    os.execvp(executable, args)
    # args = run(sys.argv[1:])
    # if run(**args) == -1:
    #     os.execl(sys.executable, sys.executable, *sys.argv)


@eel.expose
def send():
    f = open('soldlist.txt','r')
    for line in f:
        #eel.init("www2")
        eel.getData(line, '\n')
        #eel.start("data.html", close_callback=close_callback, size=(1000, 800), port=0)

if __name__ == "__main__":
    global opt
    opt = parse_opt()
    main(opt)

仅供参考,我的项目正在检测烘焙食品并进行付款流程。

使用 show_frames, win.mainloop 当我从 Yolov5 运行 detector.py 时,我可以看到相机已打开, 我尝试将 tkinter 与 yolov5 本地相机连接,但仍然不知道如何。 有人成功改过Yolov5相机界面吗?


这是我们应该避免使用通配符的一个经典原因*进口。

原来的问题包含这样的内容:

from tkinter import *
from PIL import Image, ImageTk

通配符*导入所有功能tkinter模块。 其中一项功能是Image.

在下一行中,我们看到Image通过再次导入PIL模块,这将覆盖第一个Image.

正是由于这个原因,我们更喜欢这样的别名:

import tkinter as tk

因为现在我们可以识别“同名”函数的位置,例如Image来自。

一个是tk.Image和另一个image.

这本身并不能解决问题,但是删除错误之一或混乱的来源(以及可能的其他来源)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有谁知道如何将 tkinter 网络摄像头连接到 Yolov5? 的相关文章

随机推荐

  • VStack 中大 Text 和 TextField 之间的 SwiftUI 神秘间距

    我无法弄清楚为什么我的文本下方有一些空格 struct testView View State private var notes var body some View VStack Text Larg Text font system s
  • 为什么这个值是空的?

    我正在成功地制作 保存和检索我的共享偏好mainActivity 但我无法从我的服务中获取它 由于某种原因 当我尝试从后台服务检索它时 我的共享首选项为空 我在 onCreate 中初始化我的首选项 contactsPrefs getSha
  • AngularJS:链接承诺

    遵循以下建议AngularJS 验证和承诺 我想链接确认对话框 从而一次验证多个步骤 根据用户提供的数据 调用API来查看哪些内容需要用户确认 对于每一个需要确认的步骤 提示用户并让他们决定是否进入下一步 如果任何步骤返回 false 则整
  • 如何替换 perl 中的空格

    chomp myString myString s g 我可以用这两个替换吗 myString s s g 有什么区别吗 请解释 您的第一个代码将从 myString 末尾取出换行符 如果存在 然后删除所有 字符 第二行代码将删除所有空白字
  • 为什么整数 0 等于 PHP 中的字符串? [复制]

    这个问题在这里已经有答案了 可能的重复 相等 双等于 和恒等 三等于 比较运算符有何不同 Why this var dump 0 string 输出这个 bool true 上下文不是 运算符应该转换0 into FALSE and str
  • 删除重写方法中的抛出,编译器在调用时需要一个 try/catch 块

    我有一个子类 并且要重写继承的父方法 我要从方法声明中删除 throws 子句 现在 使用多态性 my 实例的运行时类型应该确定方法实现 然而 当我尝试编译时 编译器抱怨并希望在方法调用周围有一个 try catch 块 就好像正在调用超类
  • 尝试从 PHP 运行 jar

    在阅读了该网站上与我遇到的完全相同的问题相关的一些帖子后 我发现它们都没有给我一个成功的结果 如何使用 PHP 从 Web 服务器运行 jar 从网站上的 PHP 脚本运行 Java 类文件 为什么 exec java jar file j
  • 制作特定结构的矩阵

    请注意 我不知道我错在哪里 但我花了一整天的时间试图解决这个问题 因此 我请求不要将其作为重复问题丢弃 并将其视为与矩阵结构相关的非常具体的问题 我有以下数据框 dput c m q structure list ASK Price c 1
  • 为什么 JCheckBox 上的 setSelected 失去作用?

    有人可以向我解释为什么我失去了选择 由setSelected for JCheckBox当我把JOptionPane进入ItemListener 这是一个错误吗 奇怪的是 如果这个过程被延迟invokeLater setSelected 正
  • Firemonkey:如何定义一个包含另一个组件的组件?

    在 Delphi 下 我想创建一个新的 firemonkey 控件 其中将包含另一个 firemonkey 控件 这并不是真正的问题 因为我可以这样做 constructor TMyComponent Create AOwner TComp
  • 更新对象图时实体框架的断开行为

    我目前正在开发一个使用以下技术的项目 ASP net MVC 表示层 数据服务层 WCF 具有 Automapper 的数据传输对象 TO 层 领域层 POCO 代码优先实体框架 存储库层 实体框架4 3 DbContext 我们使用 DT
  • 使用 EF Core 和 NpgSql 过滤 postgres 中 jsonb 列的整数数组

    我想根据 json 整数数组过滤行 例如 我的表如下所示 Id Name TypeJson 1 Name One 1 2 2 Name Two 2 3 3 Name Three 4 7 其中 Id 是 int 类型 Name 文本 Type
  • 在 Octave 中导入 Java 类

    我一直很难弄清楚如何做到这一点 从八度网站 似乎java类是通过类路径找到的 这个堆栈溢出答案表示 静态java路径 是 动态java路径 但我不确定如何设置静态 java 路径 在我感兴趣的特定情况下 我尝试将 javaplex 包与 O
  • 当pdf加载到iframe时如何阻止下载?

    当iframe加载pdf时自动下载pdf文件 我怎样才能防止这种情况 function dialog dialog autoOpen false modal true resizable false width auto show fade
  • 我的输出没有显示完整的数字,但显示 ??反而

    I m trying to do benchmarking with JMH the benchmarking result did come out but not perfectly 不知何故有 在数字中 是否是我的 IDE 的问题 我
  • 大熊猫的大小和数量有什么区别?

    这就是之间的区别groupby x count and groupby x size在熊猫中 size 是否只排除 nil size包括NaN价值观 count才不是 In 46 df pd DataFrame a 0 0 1 2 2 2
  • 过滤 ElementsCollection

    我正在尝试创建一个函数来过滤ElementsCollection 条件是每个元素的子元素而不是元素本身 这是我想出的 public static ElementsCollection filterByChild ElementsCollec
  • 如何在 Amazon EMR 上安装多个版本的 numpy 以及如何删除早期版本?

    我不明白 Python 如何安装单个包的多个版本 或者为什么当我安装了多个版本时 import package没有给我最新的 我正在使用 AWS linux 和 AWS EMR 中的 AWS 存储库 当我安装 Python 3 6 时 它默
  • 尝试使用 AcquireTokenByIntegratedWindowsAuth 时出现 MSAL 错误“parsing_wstrust_response_failed”

    我尝试从 AD 或 Azure AD 获取令牌 但调用 AcquireTokenByIntegratedWindowsAuth 会导致以下结果 MSAL Desktop 4 14 0 0 MsalClientException 错误代码 p
  • 有谁知道如何将 tkinter 网络摄像头连接到 Yolov5?

    现在我正在使用 Yolov5 进行我的小项目 我想将相机界面更改为 tkinter 网络摄像头打开 进行设计 带有本地相机代码的 tkinter 是 from tkinter import Tk Label Image import cv2