使用Yolov5进行目标检测,比对txt标签,标记不合格产品。
以上回复有部分引自免费微信小程序:皆我百晓生。 如问题尚未解决,还请稍待,如有疑问请回复进一步沟通。
为了根据TXT标签文件中的信息来判断产品是否合格,并在相应的图片上标注产品和不合格结果,你需要进行以下几个步骤:
pip install torch torchvision
git clone https://github.com/ultralytics/yolov5.git
cd yolov5
pip install -e .
准备数据: 确保你有一个包含图片和对应TXT标签文件的数据集。TXT文件应该有两列,第一列是图片名称(不带扩展名),第二列是标签。
编写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)
python label_images.py
这将遍历数据集中所有TXT文件,根据标签判断产品是否合格,并在原图上标注产品及其是否合格。标注后的图片将以原始图片名称加上"_labeled.jpg"的形式保存到同一目录下。
注意:这个示例脚本假设TXT文件中每个标签都是有效的,并且图像和TXT文件之间是一对一的关系。如果你的数据结构不同,可能需要修改脚本来适应你的需求。同时,YOLOv5模型默认使用的是s.pt权重文件,你可以根据需要更改模型权重。
以下内容由CHATGPT及笑面虎共同生成、有用望采纳:
您的目的是要使用YOLOv5模型来根据文本文件(txt)中的标签判断产品是否合格,并将判断结果标注在与txt文件相对应的图片上。
这个问题出现的原因是您需要自动化图像中产品质量的检测过程,并且需要将检测结果可视化地标注在图片上。这通常用于质量控制、自动化检测等领域。
为了解决这个问题,您需要执行以下步骤:
以下是一个简化的代码示例,展示了如何使用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) # 打印类别名称
# 这里添加代码将标注绘制到图像上
# 保存标注后的图像
# 这里添加代码保存图像
.py文件。代码将处理指定路径中的图片,使用YOLOv5模型进行预测,并将合格与否的标注绘制在图片上。处理后的图像将被保存。
请注意,上述代码是一个简化的示例,您需要根据实际的txt文件格式和标注需求进行相应的修改。