Python+Yolov5水稻病害侦测识别

news2024/10/6 18:21:48

程序示例精选

Python+Yolov5水稻病害侦测识别

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

前言

这篇博客针对<<Python+Yolov5水稻病害侦测识别>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。


文章目录

一、所需工具软件

二、使用步骤

        1. 引入库

        2. 代码实现

        3. 运行结果

三、在线协助

一、所需工具软件

1. Python,Pycharm

2. Yolov5

二、使用步骤

1.引入库

import argparse
import time
from pathlib import Path

import cv2
import torch
import torch.backends.cudnn as cudnn
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()
        # 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'
                    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)')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default='yolov5_crack_wall_epoach150_batchsize5.pt', help='model.pt path(s)')
    parser.add_argument('--source', type=str, default='data/images', 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.4, help='object confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
    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='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('--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()

    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. 运行结果

三、在线协助:

如需安装运行环境或远程调试,见文章底部个人 QQ 名片,由专业技术人员远程协助!
1)远程安装运行环境,代码调试
2)Qt, C++, Python入门指导
3)界面美化
4)软件制作

博主推荐文章:python人脸识别统计人数qt窗体-CSDN博客

博主推荐文章:Python Yolov5火焰烟雾识别源码分享-CSDN博客

                         Python OpenCV识别行人入口进出人数统计_python识别人数-CSDN博客

个人博客主页:alicema1111的博客_CSDN博客-Python,C++,网页领域博主

博主所有文章点这里:alicema1111的博客_CSDN博客-Python,C++,网页领域博主

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

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

相关文章

gcc/g++ 、Make/Makefile、CMake/CMakeLists.txt、qmake关系简述

1、gcc与g 首先来了解下编译器的主要工作流程&#xff1a; 源码&#xff08;Source Code&#xff09;>> 预处理器&#xff08;Preprocessor&#xff09;>> 编译器&#xff08;Compiler&#xff09; >> 汇编程序&#xff08;Assembler&#xff09;>> …

深度学习踩坑经验沉淀【持续更新】

背景 在深度学习炼丹过程中&#xff0c;总会遇到各种奇怪问题&#xff0c;这个时候总会在csdn和知乎平台找到答案&#xff0c;那每次遇到的问题是解决了&#xff0c;但没有记录起来&#xff0c;确实太可惜&#xff0c;因为未来某个时间或者某个人会遇到类似问题&#xff0c;所…

HBase应用场景和最佳实践

HBase 作为 Apache 基金会的 Hadoop 项目的一部分&#xff0c;将 HDFS 作为文件存储系统&#xff0c;使用 MapReduce 进行分布式的数据批量处理&#xff08;非实时数据批量处理&#xff09;、利用Zookeeper提供协同管理服务&#xff0c;为 Hadoop 提供海量数据管理服务&#xf…

ROS学习(5)——话题消息与服务

节点之间的消息通信分为几种形式&#xff1a; 话题(topic):单向消息发送/接收方式服务(service):双向消息请求/响应方式动作(action):双向消息目标(goal)/结果(result)/反馈(feedback)方式参数服务器(参数共享模式) 种类区别话题异步单向连续单向的发送/接收数据的情况服务同步…

【重生之我是蜘蛛侠】手把手教你用python爬虫,跟着做就好了

&#x1f4af; 博客内容&#xff1a;【LeetCode训练营】用栈来实现队列用队列来实现栈 详解 &#x1f600; 作  者&#xff1a;陈大大陈 &#x1f680; 个人简介&#xff1a;一个正在努力学技术的准前端&#xff0c;专注基础和实战分享 &#xff0c;欢迎私信&#xff01; &am…

高可用架构之异地多活

大家好&#xff0c;我是易安&#xff01; 当谈到架构的高可用时&#xff0c;无论是高可用计算架构&#xff0c;还是高可用存储架构&#xff0c;其本质的设计目的都是为了解决部分服务器故障的场景下&#xff0c;如何保证系统能够继续提供服务。但在一些极端场景下&#xff0c;有…

MySQL高级篇第一天

目录 一、索引 二、索引结构 三、索引分类 四、索引语法 五、索引设计原则 六、视图 七、存储过程与概述 八、触发器 九、总结 一、索引 &#xff08;一&#xff09;索引概述 索引是一种能够帮组Mysql高效的从磁盘上查询数据的一种数据结构&#xff0c;这些数据结构以某…

Life of a Packet in Kubernetes - Calico网络进阶(注解版)

目录 Topics — Part 2 CNI Requirements BIRD (BGP) ConfD Felix Routing Modes IP-in-IP (Default) NoEncapMode VXLAN Demo — IPIP and UnEncapMode Demo — VXLAN Disclaimer References As we discussed in Part 1, CNI plugins play an essential role in …

【面试题】Redis过期删除与内存淘汰

文章目录 Redis过期删除策略&#x1f64e;‍♂️面试官&#xff1a;如何设置key的过期时间&#xff1f;&#x1f64e;‍♂️面试官&#xff1a;什么是Redis过期删除策略&#xff1f;&#x1f64e;‍♂️面试官&#xff1a;过期的key存放到哪里/如何判断key是否过期&#xff1f;…

又到了择业的时候

前言 记得2020年的时候&#xff0c;第一次买房背上贷款&#xff0c;一共一百多万连利息将近两百万&#xff0c;突然就有了危机感&#xff0c;不自觉的会考虑如果我的人生有什么重大变故&#xff0c;我的家人会怎么办&#xff1f;他们承担每个月的房贷月供吗&#xff1f;还是被…

ciscn_2019_es_2

小白垃圾做题笔记&#xff0c;不及建议阅读。 声明&#xff0c;exp来自网络&#xff0c;调试过程自己调试&#xff0c;对于题目的理解仅供参考。由于本人也是小白&#xff0c;且pwn全靠自己摸索&#xff0c;所以有很多理解不到位的地方。如有错误&#xff0c;欢迎指正。 1.做…

新星计划2023【网络应用领域基础】——————Day1

网络应用基础讲解 前言 什么是网络&#xff1f; 什么是网络&#xff0c;网络是什么&#xff1f;能为我们做什么&#xff1f;带着疑问博主一一给你解决 这一章我将带你了解古代人是如何利用“网络”通信的&#xff0c;网络的发展史&#xff0c;osi七层模型&#xff0c;带你了解T…

【2023/05/21】simula

Hello&#xff01;大家好&#xff0c;我是霜淮子&#xff0c;2023倒计时第16天。 本文将讨论一个广泛关注的话题&#xff0c;即在信息安全领域中如何使用Simula工具进行攻击模拟和威胁情报分析。在这篇文章中&#xff0c;我们将介绍Simula的概念、原理和应用&#xff0c;评价其…

RK3568平台开发系列讲解(驱动基础篇)RK平台RTC的使用

🚀返回专栏总目录 文章目录 一、HYM8563模块二、HYM8563模块三、接口使用3.1 sysfs 接口3.2 procfs 接口3.3 ioctl 接口沉淀、分享、成长,让自己和他人都能有所收获!😄 📢本篇将对RK RTC的使用进行学习。 一、HYM8563模块 ROC-RK3568-PC开发板采用HYM8563作为RTC(Rea…

Android Codelabs

Android Codelabs 提供引导式、教程式、实践编码体验。将引导您完成构建小型应用程序或向现有应用程序添加新功能的过程。该项目将持续收集并整理有关 Android Codelabs 相关文章&#xff0c;提供给感兴趣的读者进行阅读。 使用 Kotlin 进行高级 Android 开发 本课程提供了一…

gcc确认编译器默认头文件

文章目录 1. 背景2. gcc 空编译查看3. 总结 gcc确认编译器默认头文件 1. 背景 linux下查看编译时依赖的头文件&#xff0c;可以直接使用 -Iinclude_path进行指定&#xff0c;没有指定的会从默认头文件位置去查找&#xff0c;如果还找不到&#xff0c;就会报错。那么&#xff0c…

【C++进阶】多态详解(下)

文章目录 单继承中的虚函数表多继承中的虚函数表动态绑定与静态绑定问题探究第一步&#xff1a;观察普通调用的汇编代码第二步&#xff1a;观察ptr1的汇编代码&#xff1a;第三步:观察ptr2的汇编代码&#xff1a;总结&#xff1a; 继承和多态常见的面试问题 单继承中的虚函数表…

Linux:shell之编程免交互

Linux&#xff1a;shell之编程免交互 一、Here Document 免交互1.1 Here Document 免交互概述1.2 语法格式1.3 操作 二、Expect 命令2.1 Expect 概述2.2 基本命令2.3 操作 一、Here Document 免交互 1.1 Here Document 免交互概述 使用I/O重定向的方式将命令列表提供给交互式…

ACM 1011 | 最大公约数与最小公倍数

文章目录 0x00 前言 0x01 题目描述 0x02 问题分析 0x03 代码设计 0x04 完整代码 0x05 运行效果 0x06 总结 0x00 前言 C 语言网不仅提供 C 语言&#xff0c;还包括 C 、 java 、算法与数据结构等课程在内的各种入门教程、视频录像、编程经验、编译器教程及软件下载、题解博…

2023上海市大学生网络安全大赛—ssql题解

Part1前言 上海市大学生网络安全大赛的一道 pwn 题目&#xff0c;题目用了双向链表&#xff08;猜到是 Unlink 漏洞&#xff09;。 还算比较简单&#xff0c;主要是分析代码比较复杂。分析完后漏洞限制条件少&#xff0c;题目给了 libc2.31&#xff0c;利用比较灵活。 这题白天…