利用opencv在图片中绘制YOLO标签文件中的矩形框

利用opencv在图片中绘制YOLO标签文件(.txt)中的矩形框:

import cv2
import os


def cut_one_image(img_path, txt_path):
    # 读取txt文件信息
    def read_list(txt_path):
        pos = []
        with open(txt_path, 'r') as file_to_read:
            while True:
                lines = file_to_read.readline()  # 整行读取数据
                if not lines:
                    break
                    pass
                # 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
                p_tmp = [float(i) for i in lines.split(' ')]
                pos.append(p_tmp)  # 添加新读取的数据
                # Efield.append(E_tmp)
                pass
        return pos

    # txt转换为box
    def convert(size, box):
        print(size)    # h,w
        xmin = (box[1] - box[3] / 2.) * size[1]
        xmax = (box[1] + box[3] / 2.) * size[1]
        ymin = (box[2] - box[4] / 2.) * size[0]
        ymax = (box[2] + box[4] / 2.) * size[0]
        box = (int(xmin), int(ymin), int(xmax), int(ymax))

        return box

    image = cv2.imread(img_path)
    pos = read_list(txt_path)

    for i in range(len(pos)):
        box = convert(image.shape, pos[i])
        image = cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 1)
    cv2.imshow('000001', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
        # save_path = path + '_' + str(i) + '.jpg'
        # print(save_path)
        # img = image[box[1]:box[3], box[0]:box[2]]
        # cv2.imwrite(save_path, img)


def choose_one(img_folder, label_folder, i):
    # img_list = os.listdir(img_folder)
    # img_list.sort()
    #
    # label_list = os.listdir(label_folder)
    # label_list.sort()
    #
    # img_path = img_folder + "/" + img_list[i]
    # path1 = img_path.split(".")[0].split("/")[1]
    # print(path1)
    # txt_path = label_folder + "/" + label_list[i]
    cut_one_image(img_path=img_folder, txt_path=label_folder)

if __name__ == '__main__':
    choose_one(img_folder="train/image/000001.jpg", label_folder = "train/labels/000001.txt", i=0)
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用YOLOv7检测图像的物体并输出检测框心点坐标和宽高的Python代码示例: ``` import torch import cv2 import numpy as np from yolov7.utils.datasets import letterbox from yolov7.models.experimental import attempt_load from yolov7.utils.general import non_max_suppression, scale_coords, xyxy2xywh # 加载YOLOv7模型 weights = 'yolov7s.pt' device = 'cuda:0' if torch.cuda.is_available() else 'cpu' model = attempt_load(weights, map_location=device) # 加载物体类别标签 classes = [] with open("coco.names", "r") as f: classes = [line.strip() for line in f.readlines()] # 设置输入图像尺寸和缩放因子 input_size = 640 scale_factor = 1/255.0 # 读取图像并进行预处理 image = cv2.imread("image.jpg") height, width = image.shape[:2] image = letterbox(image, new_shape=input_size)[0] image = image[:, :, ::-1].transpose(2, 0, 1).copy() image = torch.from_numpy(image).float().div(255.0).unsqueeze(0) # 将预处理后的图像输入到网络进行推理 model.eval() with torch.no_grad(): output = model(image.to(device))[0] output = non_max_suppression(output, conf_thres=0.5, iou_thres=0.5) # 解析输出层并筛选出置信度较高的物体框 boxes = [] confidences = [] class_ids = [] if output[0] is not None: for detection in output[0]: x1y1 = (detection[:2] * input_size).int() x2y2 = (detection[2:4] * input_size).int() box = torch.cat([x1y1, x2y2], dim=-1).float() box = scale_coords(image.shape[2:], box, image.shape[2:]).tolist() x, y, w, h = xyxy2xywh(torch.tensor(box))[0].tolist() center_x = x + w/2 center_y = y + h/2 boxes.append([x, y, w, h]) confidences.append(float(detection[4])) class_ids.append(int(detection[5])) # 应用非最大抑制(NMS)算法筛选出重叠度较小的物体框 indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # 绘制筛选后的物体框并输出心点坐标和宽高 for i in indices: i = i[0] x, y, w, h = boxes[i] center_x = x + w/2 center_y = y + h/2 print(classes[class_ids[i]], center_x, center_y, w, h) cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 255, 0), 2) cv2.putText(image, classes[class_ids[i]], (int(x), int(y)-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # 显示输出图像 cv2.imshow("YOLOv7 Object Detection", image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 其,`yolov7s.pt`是YOLOv7模型的权重文件,`coco.names`是物体类别标签文件,`image.jpg`是待检测的图像。可以根据实际需求修改这些文件的路径和名称。在运行代码前需要确保已安装PyTorch库、OpenCV库和Numpy库,并将yolov7目录添加到Python路径

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值