Python+Yolov8目标识别特征检测
创始人
2024-05-31 09:28:21
0

Yolov8目标识别特征检测

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

前言

这篇博客针对<>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。

文章目录

一、所需工具软件

二、使用步骤

1. 引入库

2. 识别图像特征

3. 参数设置

4. 运行结果

三、在线协助

一、所需工具软件

1. Pycharm, Python

2. Yolov8, OpenCV

二、使用步骤

1.引入库

代码如下(示例):

import torchfrom ultralytics.yolo.engine.predictor import BasePredictor
from ultralytics.yolo.engine.results import Results
from ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops
from ultralytics.yolo.utils.plotting import Annotator, colors, save_one_box

2.识别图像特征

代码如下(示例):

class DetectionPredictor(BasePredictor):def get_annotator(self, img):return Annotator(img, line_width=self.args.line_thickness, example=str(self.model.names))def preprocess(self, img):img = torch.from_numpy(img).to(self.model.device)img = img.half() if self.model.fp16 else img.float()  # uint8 to fp16/32img /= 255  # 0 - 255 to 0.0 - 1.0return imgdef postprocess(self, preds, img, orig_img):preds = ops.non_max_suppression(preds,self.args.conf,self.args.iou,agnostic=self.args.agnostic_nms,max_det=self.args.max_det,classes=self.args.classes)results = []for i, pred in enumerate(preds):orig_img = orig_img[i] if isinstance(orig_img, list) else orig_imgshape = orig_img.shapepred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], shape).round()results.append(Results(boxes=pred, orig_img=orig_img, names=self.model.names))return resultsdef write_results(self, idx, results, batch):p, im, im0 = batchlog_string = ''if len(im.shape) == 3:im = im[None]  # expand for batch dimself.seen += 1imc = im0.copy() if self.args.save_crop else im0if self.source_type.webcam or self.source_type.from_img:  # batch_size >= 1log_string += f'{idx}: 'frame = self.dataset.countelse:frame = getattr(self.dataset, 'frame', 0)self.data_path = pself.txt_path = str(self.save_dir / 'labels' / p.stem) + ('' if self.dataset.mode == 'image' else f'_{frame}')log_string += '%gx%g ' % im.shape[2:]  # print stringself.annotator = self.get_annotator(im0)det = results[idx].boxes  # TODO: make boxes inherit from tensorsif len(det) == 0:return log_stringfor c in det.cls.unique():n = (det.cls == c).sum()  # detections per classlog_string += f"{n} {self.model.names[int(c)]}{'s' * (n > 1)}, "# writefor d in reversed(det):cls, conf = d.cls.squeeze(), d.conf.squeeze()if self.args.save_txt:  # Write to fileline = (cls, *(d.xywhn.view(-1).tolist()), conf) \if self.args.save_conf else (cls, *(d.xywhn.view(-1).tolist()))  # label formatwith open(f'{self.txt_path}.txt', 'a') as f:f.write(('%g ' * len(line)).rstrip() % line + '\n')if self.args.save or self.args.save_crop or self.args.show:  # Add bbox to imagec = int(cls)  # integer classname = f'id:{int(d.id.item())} {self.model.names[c]}' if d.id is not None else self.model.names[c]label = None if self.args.hide_labels else (name if self.args.hide_conf else f'{name} {conf:.2f}')self.annotator.box_label(d.xyxy.squeeze(), label, color=colors(c, True))if self.args.save_crop:save_one_box(d.xyxy,imc,file=self.save_dir / 'crops' / self.model.model.names[c] / f'{self.data_path.stem}.jpg',BGR=True)return log_string

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()

4.运行结果如下

三、在线协助:

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

博主推荐文章:https://blog.csdn.net/alicema1111/article/details/123851014

个人博客主页:https://blog.csdn.net/alicema1111?type=blog

博主所有文章点这里:https://blog.csdn.net/alicema1111?type=blog

相关内容

热门资讯

初一写景作文250字通用63... 初一写景作文250字 第一篇什么是和谐?和谐是春天的第一缕阳光,第一片绿叶,第一滴雨滴,最清新的空气...
难忘的敏特英语学习初中作文(... 难忘的敏特英语学习初中作文 篇一初中时期,我曾经参加过一次难忘的敏特英语学习活动。这次活动不仅让我提...
初一开学第一篇作文(精彩3篇... 初一开学第一篇作文 篇一:新的起点开学第一天,我怀着激动的心情来到了新的学校。这是我人生中的一个新的...
我是中学生了感觉真棒作文(经... 我是中学生了感觉真棒作文 篇一终于,我升入了中学,成为了一名中学生。这是我人生中的重要转折点,我感到...
我的札记本作文(精简5篇) 我的札记本作文 篇一我的札记本是我生活中的得力助手。它陪伴我度过了许多美好的时光,记录了许多珍贵的回...
鸡年春节歌曲:迎春花歌词(精... 鸡年春节歌曲:迎春花歌词 篇一《迎春花》是一首充满喜庆和欢乐气氛的鸡年春节歌曲。这首歌曲以迎春花为主...
少年的模样-记叙文【精彩5篇... 少年的模样-记叙文 篇一夏日的阳光透过窗帘洒在地板上,照亮了少年的脸庞。他身穿一件白色的T恤,牛仔裤...
初中英语作文:蘑菇 Mush... 初中英语作文:蘑菇 Mushrooms 篇一Mushrooms are a type of fung...
遇见作文【通用6篇】 遇见作文 篇一近年来,作文成为了学生们备受关注的一项重要考试内容。然而,对于很多学生来说,作文却是一...
游藏龙百瀑初一作文【优选6篇... 游藏龙百瀑初一作文 篇一游藏龙百瀑初一作文 篇一游藏龙是我国著名的风景名胜区之一,位于贵州省黔东南苗...
初中的军训作文600字(精选... 初中的军训作文600字 篇一初中的军训是一次难忘的经历初中的军训是每个初中生都会经历的一段时光。我记...
我的未来我做主初一作文(精选... 我的未来我做主初一作文 篇一我的未来我做主未来,是一个充满无限可能的词汇。在这个时代,我们都有自己的...
同上一堂课雷锋告诉我作文(通... 篇一:同上一堂课雷锋告诉我雷锋是一位伟大的人物,他的事迹深深地感动了我。上一堂课,我们学习了雷锋的故...
水仙初一作文(优质5篇) 水仙初一作文 篇一我的初一生活初一,是一个全新的开始,也是我人生中的一个重要阶段。我迎来了初中生活,...
从前的我们的作文500字【优... 从前的我们的作文500字 篇一过去的我们总是无忧无虑地生活着,那是我们最纯真的时光。回想起那些年,我...
我庆幸我是中国人初一作文55... 我庆幸我是中国人初一作文550字 篇一作为一个初一学生,我庆幸自己是中国人。中国是一个拥有五千年文明...
初中作文题材万能素材积累【精... 初中作文题材万能素材积累 篇一 随着社会的发展,人们对于环境保护的意识越来越强烈。环境污染已经成为...
亲切的怀恋作文(优选3篇) 亲切的怀恋作文 篇一怀恋已逝的时光记忆是一扇扇窗户,打开时可以穿越时光,回到过去。尽管时间已经过去了...
我真开心初一范文63篇 我真开心初一范文 第一篇我相信大家对于那些能够让自己开心快乐的事情肯定不会淡忘。在去年的时候,尤其是...
天堂寨之行初一作文(优质3篇... 天堂寨之行初一作文 篇一天堂寨之行初一暑假,我和家人一起来到了著名的旅游景点——天堂寨。这是一个位于...