Python+Yolov5墙体桥梁裂缝识别

news2024/9/27 5:51:10

程序示例精选

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/495099.html

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

相关文章

【安装Nginx】

Linux上安装Nginx 文章目录 Linux上安装NginxUbuntuCentOS查看已安装的软件 Ubuntu 在 Ubuntu 上安装 Nginx 非常简单。只需按照以下步骤操作&#xff1a; 打开终端&#xff0c;更新软件包索引&#xff1a; sudo apt update安装 Nginx&#xff1a; sudo apt install nginx安…

2023世界超高清视频产业发展大会博冠8K明星展品介绍

2023世界超高清视频产业发展大会博冠8K明星展品介绍&#xff1a; 一、博冠8K全画幅摄像机B1 这是一款面向广电应用的机型&#xff0c;可适配外场ENG制作轻量化需求&#xff0c;应用于8K单边机位、新闻、专题的拍摄工作&#xff0c;也可应用于体育转播、文艺节目等特殊机位及各…

使用react脚手架初始化项目

1.使用react脚手架初始化项目 1.初始化命令&#xff0c;&#xff08;create-react-app脚手架的名称&#xff0c;my-app项目名称&#xff09; npx create-react-app my-app2.初始化完成之后可以看到Happy hacking&#xff01; 3.启动项目&#xff0c;进去根目录cd my-app &am…

这才是 玩转Github 的正确姿势

这才是 玩转Github 的正确姿势 GitHub各位应该都很熟悉了&#xff0c;全球最大的开源社区&#xff0c;也是全球最大的同性交友网站~~&#xff0c;但是大部分同学使用GitHub应该就是通过别人的开源链接&#xff0c;点进去下载对应的项目&#xff0c;而真正使用Github来查找开源…

RF学习-RF基本概念

射频(RF)指的是无线波的频率在3KHZ~300GHZ&#xff1b; RF系统通常包括以下模块&#xff1a; 本振(LO)放大器(Amplifier)混频器(Mixer)滤波器(Filter)天线(Antenna) RF接收机有如下三种类型&#xff1a; 超外差式接收机(Super heterodyne structure)零中频接收机(Homodyne…

GAN与DCGAN

GAN&#xff1a;生成对抗网络&#xff0c;首先是一个生成模型&#xff0c;区别与之前的辨别模型&#xff0c;对抗体现在生成器与辨别器之间的对抗。 生成器输入的是噪音&#xff0c;通过多层的MLP可以产生图片&#xff0c;将产生的图片和真实图片输入到辨别器&#xff0c;辨别器…

AI绘画5大免费工具

AI现在最火爆的两个方向一个是以ChatGPT为主导的文本生成工具&#xff0c;还有一个就是以Midjourne为主导的文本生成图片工具。 Midjourne 现在基本是都是需要收费的&#xff0c;但确实Midjourne的效果是顶尖的&#xff0c;如果我们只是想试一下 文本生图的过程&#xff0c;这里…

【ArcGIS Pro二次开发】(26):数据筛选器

在使用【OpenItemDialog】打开数据时&#xff0c;其中一个重要的属性【Filter】&#xff0c;可用于筛选要打开的数据。示例代码如下&#xff1a; // 打开文件对话框OpenItemDialog dlg new OpenItemDialog(){Title "选择要打开的文本文件",Filter ItemFilters.Dat…

如何用ChatGPT写专业方向的科普内容?

该场景对应的关键词库&#xff08;13个&#xff09;&#xff1a; 目标用户、科普内容、生活问题、医疗类型、科普文章、病情症状、通俗性、专业名词、背景资质、权威领域、执业范围、证言人、内容形式。 提问模板&#xff08;3个&#xff09;&#xff1a; 第一步&#xff0c;…

打包工具--pyinstaller

下载库 pip install pyinstaller 打包命令 Pyinstaller -D setup.py 打包exePyinstaller -F -w run.py 不带控制台的打包Pyinstaller -F -i xx.ico setup.py 打包指定exe图标打包 ❝ -D&#xff1a;打包为一个文件夹&#xff0c;其中exe文件在文件夹内部&#xff0c;这样子单个…

更换外线和智能电表后家里用电频繁跳闸的检修

老家的电路老是跳闸。今天检修了老家的线路&#xff0c;故障就是更换了外线路后&#xff0c;家里烧水或者用电磁炉就频繁跳闸。其实也说不清楚&#xff0c;因为最近又改了智能表嘛。 到电表处观察&#xff0c;是插卡智能表&#xff0c;电表进线有个空开C63A。电表出来有个空开C…

万字长文 - Nature 综述系列 - 给生物学家的机器学习指南 4 (生物应用的挑战)...

万字长文 - Nature 综述系列 - 给生物学家的机器学习指南 1 万字长文 - Nature 综述系列 - 给生物学家的机器学习指南 2 &#xff08;传统机器学习方法如何选择&#xff09; 万字长文 - Nature 综述系列 - 给生物学家的机器学习指南 3 &#xff08;人工神经网络&#xff09; 生…

C++实践模拟(stack,queue priority_queue,仿函数)

stack和queue的实现&#xff0c;不同于vector和list那般复杂&#xff0c;如果你经历过vector和list的洗礼&#xff0c;那么当你看到stack和queue的大致实现时&#xff0c;你可能会惊叹&#xff0c;怎么能这么简洁。其原因有很多方面的&#xff0c;比如stack和queue不需要实现迭…

第11届蓝桥杯国赛真题剖析-2020年10月31日Scratch编程初中级组

[导读]&#xff1a;超平老师的《Scratch蓝桥杯真题解析100讲》已经全部完成&#xff0c;后续会不定期解读蓝桥杯真题&#xff0c;这是Scratch蓝桥杯真题解析第129讲。 第11届蓝桥杯Scratch国赛真题&#xff0c;这是2020年10月31日举办的全国总决赛&#xff0c;由于疫情影响&am…

【图像】图像格式(3) : BMP

1. 背景 BMP可以说是图像中最简单的格式了&#xff0c;没有图像压缩算法&#xff0c;基本可以看做图像的RGB裸数据加了一些基本的metadata构成。 这也导致了bmp的文件一般都是非常的大&#xff0c;除了windows原生的支持之外&#xff08;从1990年的windows3.0开始&#xff09;…

破事精英2◎爬向未来

胡强的2033未免有些过去可怕&#xff0c;海星果然又是反派。 只剩“脑子”的胡强 400百斤只剩“嘴”的庞小白 将自己身体分成一个个“方块”的苏克杰 苍蝇满天飞“衣服堆”的金若愚 “脑子”送到月球打两份工的沙乐乐 有机器人或者分身帮我们干活赚钱&#xff0c;我们去吃喝玩…

FM33A048B 红外调制

TZBRG寄存器保存一个 11 位的分频系数 X &#xff0c;其值为 0~2047 之间的任一整数。 6 路 UART 共用一个红外调制频率发生器。 红外调制频率计算公式&#xff1a; FIR FAPBCLK/ (TZBRGTZBRG 1) 红外调制的方式为&#xff1a;发送数据0 时调制红外频率&#xff0c;发送数据 1…

JavaScript实现输入两个数比较两个数的大小,输出个人信息的两个程序代码

以下为实现输入两个数比较两个数的大小&#xff0c;输出个人信息的两个程序代码和运行截图 目录 前言 一、实现输入两个数比较两个数的大小 1.1 运行流程及思想 1.2 代码段 1.3 JavaScript语句代码 1.4 运行截图 二、输出个人信息 2.1 运行流程及思想 2.2 代码段 2.3…

Java每日一练(20230506) 全排列II、岛屿数量、有效数独

目录 1. 全排列 II &#x1f31f;&#x1f31f; 2. 岛屿数量 &#x1f31f;&#x1f31f; 3. 有效的数独 &#x1f31f;&#x1f31f; &#x1f31f; 每日一练刷题专栏 &#x1f31f; Golang每日一练 专栏 Python每日一练 专栏 C/C每日一练 专栏 Java每日一练 专栏 …

atbf中imu数据读取逻辑分析仪抓取

一、说明 使用逻辑分析仪抓区imu的spi和中断io的信号&#xff0c;从而侧面描述atbf在imu上的数据读取方式&#xff1b; 二、硬件说明 1、硬件材料 1、mcu at32F437开发板 2、imu icm42688p 3、逻辑分析仪 梦源逻辑分析仪 4、调试器 jlink 2、原理图 3、实物图 4、固…