• (标签-yolo|关键词-上标)


    关注 码龄 粉丝数 原力等级 -- 被采纳 被点赞 采纳率 普通网友 2024-05-14 20:03 采纳率: 25% 浏览 1 首页/ 编程语言 / (标签-yolo|关键词-上标) python yolov5 根据txt标签里面的标签判断产品合不合格 并在txt所对应的图片上标注产品和不合格 收起 写回答 好问题 0 提建议 追加酬金 关注问题 微信扫一扫 点击复制链接 分享 邀请回答 编辑 收藏 删除 结题 收藏 举报 追加酬金 (90%的用户在追加酬金后获得了解决方案) 当前问题酬金 ¥ 0 (可追加 ¥500) ¥ 15¥ 20¥ 50¥ 100¥ 200 支付方式 扫码支付 二维码出错 点击刷新 支付金额 15 元 提供问题酬金的用户不参与问题酬金结算和分配 支付即为同意 《付费问题酬金结算规则》 结题 再想想 删除 再等等

    2条回答 默认 最新

    • 专家-皆知 2024-05-14 20:03
      关注

      使用Yolov5进行目标检测,比对txt标签,标记不合格产品。

      以上回复有部分引自免费微信小程序:皆我百晓生。 如问题尚未解决,还请稍待,如有疑问请回复进一步沟通。

      评论
      专家-皆知 回复 普通网友 2024-05-14 20:04

      为了根据TXT标签文件中的信息来判断产品是否合格,并在相应的图片上标注产品和不合格结果,你需要进行以下几个步骤:

      1. 安装依赖库: 确保已经安装了PyTorch、YOLOv5和其他相关库。如果没有安装,可以使用以下命令安装:
      pip install torch torchvision
      git clone https://github.com/ultralytics/yolov5.git
      cd yolov5
      pip install -e .
      
      1. 准备数据: 确保你有一个包含图片和对应TXT标签文件的数据集。TXT文件应该有两列,第一列是图片名称(不带扩展名),第二列是标签。

      2. 编写Python脚本: 创建一个名为label_images.py的文件,然后添加以下代码:

      import os
      import cv2
      from PIL import Image, ImageDraw, ImageFont
      from typing import List
      from yolov5.utils.datasets import LoadImages, LoadStreams
      from yolov5.models.common import DetectMultiBackend
      from yolov5.utils.general import check_img_size, non_max_suppression, scale_coords, xyxy2xywh, plot_one_box
      
      
      def draw_boxes(image_path: str, labels: List[str], scores: List[float]):
          img = cv2.imread(image_path)
          height, width = img.shape[:2]
      
          # Create a blank image for drawing the bounding boxes
          draw_image = Image.fromarray(img)
          draw = ImageDraw.Draw(draw_image)
      
          font = ImageFont.truetype("arial.ttf", 14)
      
          for label, score in zip(labels, scores):
              if score < 0.5:  # 可以根据需要调整阈值
                  text = f"{label} (不合格)"
              else:
                  text = f"{label} (合格)"
      
              # Convert YOLO's xyxy format to OpenCV's xywh format
              box = [int(coord * width) for coord in scale_coords((width, height), (0, 0, 1, 1), (labels[0].shape[1], labels[0].shape[2]))]
              x, y, w, h = box
      
              # Draw the rectangle and text
              draw.rectangle(box, outline=(0, 255, 0) if score >= 0.5 else (0, 0, 255))
              draw.text((x, y - 5), text, fill=(0, 255, 0) if score >= 0.5 else (0, 0, 255), font=font)
      
          result = np.array(draw_image)
          cv2.imwrite(os.path.splitext(image_path)[0] + "_labeled.jpg", result)
      
      
      if __name__ == "__main__":
          data_dir = "path/to/your/data/directory"  # 替换为你的数据集路径
          txt_files = [os.path.join(data_dir, f) for f in os.listdir(data_dir) if f.endswith(".txt")]
      
          for txt_file in txt_files:
              with open(txt_file, "r") as file:
                  lines = file.readlines()
      
              image_names = []
              labels = []
              for line in lines:
                  parts = line.strip().split()
                  image_names.append(parts[0])
                  labels.append(parts[1])
      
              model = DetectMultiBackend(weights="yolov5s.pt", device="cuda")
              imgsz = check_img_size(None, s=model.stride.max())  # Use default size
      
              for i, (path, img) in enumerate(LoadImages(txt_files=image_names, img_size=imgsz)):
                  outputs = model(img, augment=False, visualize=True)[0]
                  boxes, scores, classes, nums = non_max_suppression(outputs, conf_thres=0.5, iou_thres=0.5)
      
                  draw_boxes(path, classes, scores)
      
      1. 运行脚本: 在终端中运行以下命令:
      python label_images.py
      

      这将遍历数据集中所有TXT文件,根据标签判断产品是否合格,并在原图上标注产品及其是否合格。标注后的图片将以原始图片名称加上"_labeled.jpg"的形式保存到同一目录下。

      注意:这个示例脚本假设TXT文件中每个标签都是有效的,并且图像和TXT文件之间是一对一的关系。如果你的数据结构不同,可能需要修改脚本来适应你的需求。同时,YOLOv5模型默认使用的是s.pt权重文件,你可以根据需要更改模型权重。

      回复
    • 笑面虎 2024-05-14 20:03
      关注

      以下内容由CHATGPT及笑面虎共同生成、有用望采纳:


      您想要解决的问题

      您的目的是要使用YOLOv5模型来根据文本文件(txt)中的标签判断产品是否合格,并将判断结果标注在与txt文件相对应的图片上。

      问题出现原因

      这个问题出现的原因是您需要自动化图像中产品质量的检测过程,并且需要将检测结果可视化地标注在图片上。这通常用于质量控制、自动化检测等领域。

      问题解决方案

      为了解决这个问题,您需要执行以下步骤:

      1. 数据准备:确保您的txt文件中的标签格式与YOLOv5模型的输入格式兼容。
      2. 模型训练:如果需要,训练YOLOv5模型以识别合格与不合格的产品。
      3. 图像标注:编写脚本使用YOLOv5模型对图像进行预测,并将预测结果标注在图像上。

      提供代码

      以下是一个简化的代码示例,展示了如何使用YOLOv5进行图像标注:

      import torch
      from PIL import Image
      from models.experimental import attempt_load
      from utils.datasets import LoadStreams
      from utils.general import check_img_size, scale_coords
      from utils.torch_utils import select_device
      from utils.torch_utils import select_device
      from utils.torch_utils import scale_coords
      from utils.datasets import LoadImages
      from utils.datasets import LoadStreams
      from utils.general import scale_coords, check_img_size
      from utils.torch_utils import select_device
      
      weights = 'yolov5s.pt'  # 模型权重文件
      device = select_device('')  # 选择设备,CPU或GPU
      model = attempt_load(weights, map_location=device)  # 加载模型
      stride = int(model.stride.max())  # 模型的stride
      imgsz = check_img_size(640, s=stride)  # 检查图像大小
      names = model.module.names if hasattr(model, 'module') else model.names  # 获取类别名称
      
      # 加载图片和txt标签
      dataset = LoadImages('path_to_images', imgsz, stride=stride)
      txt_labels = "path_to_txt_file"  # txt文件路径
      
      for img_path, img, im0s, vid_cap in dataset:
          img = torch.from_numpy(img).to(device)
          img = img.float()  # uint8 to fp16/32
          img /= 255.0  # 图像归一化
          if img.ndimension() == 3:
              img = img.unsqueeze(0)
      
          # 推理
          pred = model(img, augment=False)[0]
      
          # 处理预测结果
          for i, det in enumerate(pred):  # 检测每个图像
              scale_coords(img.shape[2:], det[:, :4], im0s[i])
      
              # 标注不合格产品
              # 这里需要您根据txt文件中的标签来决定哪些产品是不合格的
              # 以下代码仅为示例,您需要根据实际情况进行修改
              if det[5:].tolist() != [0, 0, 0, 0, 0]:  # 假设txt文件中的标签是这样的格式
                  label = "不合格" if det[5:].tolist() 不符合合格条件 else "合格"
                  det[:, 5] = label
      
              # 将标注绘制到图像上
              for *xyxy, conf, cls, xywh, label in reversed(det):
                  label = names[int(cls)]
                  print(label)  # 打印类别名称
                  # 这里添加代码将标注绘制到图像上
      
      # 保存标注后的图像
      # 这里添加代码保存图像
      

      代码运行方式

      1. 确保您的环境中安装了Python和必要的库,如PyTorch和PIL。
      2. 将上述代码保存为.py文件。
      3. 在命令行中,使用Python运行该脚本。

      代码预期运行结果

      代码将处理指定路径中的图片,使用YOLOv5模型进行预测,并将合格与否的标注绘制在图片上。处理后的图像将被保存。

      推荐相关链接

      请注意,上述代码是一个简化的示例,您需要根据实际的txt文件格式和标注需求进行相应的修改。

      展开全部

      评论 编辑记录
    编辑
    预览

    报告相同问题?

  • 相关阅读:
    蓝桥杯每日一题2023.10.4
    ModuleNotFoundError: No module named ‘pyLDAvis.gensim‘解决方案
    vivado时序分析-3时序分析关键概念
    Maven Helper 安装使用
    你的关联申请已发起,请等待企业微信的管理员确认你的申请
    企业级logstash简单使用(ELK)
    SpringMVC如何在web.xml中配置DispatcherServlet呢?
    在 uniapp 里面使用 unocss
    设计模式之代理模式
    C/C++ 泛型模板约束
  • 原文地址:https://ask.csdn.net/questions/8103451