Python+Qt身体特征识别人数统计源码窗体程序

news2025/2/4 3:50:34

 程序示例精选

Python+Qt身体特征识别人数统计

如需安装运行环境或远程调试,见文章底部微信名片,由专业技术人员远程协助!

前言

这篇博客针对《PPython+Qt身体特征识别人数统计》编写代码,功能包括了相片,摄像头身体识别,数量统计。代码整洁,规则,易读。应用推荐首选。


文章目录

        一、所需工具软件

        二、使用步骤

                1. 引入库

                2. 识别特征图像

                3. 识别参数定义

                4. 运行结果

         三在线协助


一、所需工具软件

          1. Python3.6以上

          2. Pycharm代码编辑器

          3. PyQt, Torch库

二、使用步骤

1.引入库

代码如下(示例):

import cv2
import torch
from numpy import random
 
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
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

2.识别特征图像

代码如下(示例):

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
    webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
        ('rtsp://', 'rtmp://', 'http://'))
 
    # 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:
        save_img = True
        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()
 
 
                # 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)')
 
 
            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video'
                    if vid_path != save_path:  # new video
                        vid_path = save_path
                        if isinstance(vid_writer, cv2.VideoWriter):
                            vid_writer.release()  # release previous video writer
 
                        fourcc = 'mp4v'  # output video codec
                        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))
                        vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), 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)')
    
    print(opt)
    check_requirements()
 
    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)
            for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
                detect()
                strip_optimizer(opt.weights)
        else:
            detect()

3.识别参数定义:

代码如下(示例):

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default='yolov5_best_road_crack_recog.pt', help='model.pt path(s)')
    parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
    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('--classes', nargs='+', type=int, default='0', 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()
 
    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)
            for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
                detect()
                strip_optimizer(opt.weights)
        else:
            detect()

4.运行结果如下: 

 

三、在线协助: 

如需安装运行环境或远程调试,见文章底部微信名片,由专业技术人员远程协助!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/103558.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Javaweb中的Request(请求)和Response(响应)

目录 一、概念 二、请求(Request) 1.例子简介 2.Request继承体系 3.Request获取请求数据 (1)请求行 (2)请求头 (3)请求体 4.优化请求体参数的获取 5.解决请求参数乱码问…

POSIX Timer

一、特点: 1、使用 POSIX Timer,一个进程可以创建任意多个 Timer。 2、setitmer 计时器时间到达时,可以有多种通知方式,比如信号,或者启动线程。 3、POSIX Timer 则可以使用实时信号。 4、POSIX Timer 是针对有实时要…

leetcode98. 验证二叉搜索树关于递归实现中遇到的global和nonlocal(各种报错分析)

leetcode98. 验证二叉搜索树 题目 给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。 有效 二叉搜索树定义如下: 节点的左子树只包含 小于 当前节点的数。 节点的右子树只包含 大于 当前节点的数。 所有左子树和右子树自身必须也是二…

前端基础(十三)_定位position、定位层级z-index

一、定位position Css的定位机制:普通文档流、浮动、定位 这里主要介绍CSS的定位属性:position: 1、定位原理:允许元素相对于正常位置、或者相对于父元素、浏览器窗口本上的位置 2、元素位置的调整: left|right属性、…

Spring Boot项目使用RabbitMQ队列

Spring Boot项目使用RabbitMQ队列 一、Rabbitmq的安装 RabbitMQ是一个开源的遵循 AMQP协议实现的基于 Erlang语言编写,**即需要先安装部署Erlang环境再安装RabbitMQ环境。 erlang的安装在windows中直接点击安装即可。 安装完erlang后设置erlang的环境变量ERLANG…

CSM32RV20 是 32位低功耗MCU芯片 RISC-V RV32IMAC 内核

CSM32RV20 是 32位低功耗MCU芯片 RISC-V RV32IMAC 内核 CSM32RV20 是基于RISC-V RV32IMAC 内核(2.6 CoreMark/MHz)的32位低功耗MCU芯片,最高主频32MHz,最大支持 40KB 嵌入式FlASH、4KB SRAM和512B NVM,集成ADC和UART、…

如何使用FastReport .NET 从 JetBrains Rider 中创建PDF报告?

Fastreport是目前世界上主流的图表控件,具有超高性价比,以更具成本优势的价格,便能提供功能齐全的报表解决方案,连续三年蝉联全球文档创建组件和库的“ Top 50 Publishers”奖。 FastReport.NET官方版下载(qun&#x…

了解什么是架构基本概念和架构本质

什么是架构和架构本质 在软件行业,对于什么是架构,都有很多的争论,每个人都有自己的理解。此君说的架构和彼君理解的架构未必是一回事。因此我们在讨论架构之前,我们先讨论架构的概念定义,概念是人认识这个世界的基础&…

Note that you can also install from a tarball 处理

近期使用 npm publish 发布依赖包时,始终遇到 npm 404 报错,错误信息是 “Note that you can also install from a tarball”,尝试更换网络,更换代理服务器等操作,都无效,npm 报错如下 问题原因&#xff1a…

python通过字典来替代if..else

在应对多策略的场景下,大量使用if...else...不仅提高了后期的维护成本,还降低了运行效率。通过字典做映射就可以更好的优化代码。 比如这样一个模拟场景,根据用户的VIP等级,发放奖励。在大量使用if...else...时就会变成如下状态&…

nodejs篇 内置模块http 常用api

文章目录前提创建一个最基本的http服务器req有哪些值得关注的信息res常用的apihttp.request(options[, callback])server事件监听checkContinuecheckExpectationcloseconnect前提 如果你觉得nodejs官方文档给的api太多,不知道哪些重要,请看下去&#xf…

TensorRT全方位概览笔记

TensorRT (基于8.2.3)1.简介1.export1.1 使用tensorrt API 搭建1.2 使用parser1.3 使用框架内 tensorrt 接口1.4 注意事项2.开发辅助工具2.1 trtexec2.2 Netron2.3 onnx-graphsurgeon2.4 polygraphy2.5 Nsight Systems3. plugin3.1 plugin3.2 使用3.3 类…

就离谱!使用机器学习预测2022世界杯:小组赛挺准,但冠亚季军都错了 ⛵

💡 作者:韩信子ShowMeAI 📘 数据分析实战系列:https://www.showmeai.tech/tutorials/40 📘 机器学习实战系列:https://www.showmeai.tech/tutorials/41 📘 本文地址:https://www.sho…

C2. Potions (Hard Version)(可以后悔的选取 + 一种新奇的优先队列用法)

Problem - 1526C2 - Codeforces 这是该问题的困难版本。唯一不同的是,在这个版本中,n≤200000。只有当两个版本的问题都解决了,你才能进行黑客攻击。 有n个药水排成一行,最左边是药水1,最右边是药水n。每种药水在喝下…

Eclipse安装和环境的基本配置

Eclipse安装 安装包 链接:https://pan.baidu.com/s/13LXiyGmgdAQ2MYXhim1WMg 提取码:WADS 不会安装的可以参考这篇文章 链接: 安装教程文章 eclipse怎么更改存储位置 1.1 file-> Switch Workspace ->Other 打开后可以看到保存文件的路径也可以…

疫情之下连锁餐饮行业积极求变,集团采购协同管理系统重构企业采购数字化

2019年底至今,新冠肺炎疫情已进入了第三个年头。作为接触性、聚集性行业,国内餐饮业持续承压,经历了一系列的波折。尤其2022年以来,国内多地出现了此起彼伏的疫情,给餐企带来了较大冲击,餐饮行业整体营收收…

【推荐】安全访问服务边缘(SASE)资料汇总合集24篇

Secure Access Service Edge (SASE) 是Gartner推出的一个新的技术理念。SASE将 SD-WAN和网络安全解决方案(FWaaS、CASB、SWG 和ZTNA)融合到统一的云原生服务中。SASE是Gartner最新提出的一个技术理念,SASE用于从分布式云服务交付聚合的企业网…

Web前端105天-day49-jQuery

jQuery02 目录 前言 一、复习 二、标签内容 三、get请求 四、新增子元素 五、委托 六、克隆 七、加载HTML 八、准备就绪 九、Node.js 十、js中提示jQuery的方案 十一、location 十二、根据地址栏参数加载页面 十三、全局样式变量 总结 前言 jQuery02学习开始 一…

vi\vim编辑器的使用及命令、快捷键

vi\vim编辑器 1、vi\vim编辑器介绍 vi\vim是visual interface的简称,是Linux中最经典的文本编辑器。 同图形化界面中的文本编辑器一样,vi是命令行下对文本文件进行编辑的绝佳选择。 vim是vi的加强版本,兼容vi的所有指令,不仅能…

信息化时代,相比于人工服务客户更喜欢自助式服务

对于SaaS产品,为客户提供自助式服务,帮助客户能够自行完成任务和解决问题,给到客户更好的使用体验,对于SaaS产品,搭建一个自助式知识库门户和产品知识库尤为重要。在选购产品后,如果没有获得很好的客户服务…