0


LabelImg标注的YOLO格式txt标签中心坐标和物体边界框长宽的转换

Opencv+YOLO-V3实现目标跟踪

YOLO-V3实时检测实现(opencv+python实现)——改进——>更加的易懂

YOLO-V3实时检测实现(opencv+python实现)

1.LabelImg标注的YOLO格式的TXT标签

关于LabelImg下载及使用:标注工具 labelImg 的下载安装及使用

首先标注一张图片:

查看标签.txt文件:

提示:如果我们要进行训练的话,那么需要上面的坐标进行变换一下,得到框的左上角的坐标和右下角的坐标。

现在我们要根据中心坐标和边框得到左上角(xmin,ymin)和右下角(xmax,ymax)坐标:

变换公式如下:

提示:现在已经知道坐标之间的关系了,那么可以使用python进行求解:

  • 第一步从标注的.txt文件中读取数据;
  • 第二步将读取的数据利用上面的公式进行转换;
def Xmin_Xmax_Ymin_Ymax(img_path,txt_path):
    """
    :param img_path: 图片文件的路径
    :param txt_path: 坐标文件的路径
    :return:
    """
    img = cv2.imread(img_path)
    # 获取图片的高宽
    h, w, _ = img.shape
    #读取TXT文件 中的中心坐标和框大小
    with open(txt_path,"r") as fp:
        #以空格划分
        contline=fp.readline().split(' ')
        #contline : class  x_center y_center width height
        print(contline)
    #计算框的左上角坐标和右下角坐标,使用strip将首尾空格去掉
    xmin=float((contline[1]).strip())-float(contline[3].strip())/2
    xmax=float(contline[1].strip())+float(contline[3].strip())/2

    ymin = float(contline[2].strip()) - float(contline[4].strip()) / 2
    ymax = float(contline[2].strip()) + float(contline[4].strip()) / 2

    #将坐标(0-1之间的值)还原回在图片中实际的坐标位置
    xmin,xmax=w*xmin,w*xmax
    ymin,ymax=h*ymin,h*ymax

    #返回:类别,xleft,yleft,xright,yright
    return (contline[0],xmin,xmax,ymin,ymax)

将返回的坐标利用opencv将框绘制出来:

def draw(tupelist):
    img_path = "data/train/000_0.png"
    img = cv2.imread(img_path)

    xmin=tupelist[1]
    xmax=tupelist[2]
    ymin=tupelist[3]
    ymax=tupelist[4]
    cv2.rectangle(img,(int(xmin),int(ymin)),(int(xmax),int(ymax)),(255,0,255),2)

    cv2.imshow('img',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
import cv2
import os
import numpy as np

if __name__ == '__main__':
    tuplelist=Xmin_Xmax_Ymin_Ymax()
    draw(tuplelist)
#将所有转换之后的实际坐标保存到一个.txt文件当中
def writeXYToTxt():
    """
    :return:
    """
    imgsPath='data/train/person'
    txtsPath='data/XML/person'
    imgs=os.listdir(imgsPath)
    txts=os.listdir(txtsPath)
    for img_,txt_ in zip(imgs,txts):
        img_path=os.path.join(imgsPath,img_)
        txt_path=os.path.join(txtsPath,txt_)
        tupelist=Xmin_Xmax_Ymin_Ymax(img_path=img_path,txt_path=txt_path)
        datasets=str(tupelist[0])+' '+str(tupelist[1])+' '+str(tupelist[2])+' '+str(tupelist[3])+' '+str(tupelist[4])
        with open(txt_,'w') as fp:
            fp.write(datasets)


本文转载自: https://blog.csdn.net/Keep_Trying_Go/article/details/128224748
版权归原作者 Keep_Trying_Go 所有, 如有侵权,请联系我们删除。

“LabelImg标注的YOLO格式txt标签中心坐标和物体边界框长宽的转换”的评论:

还没有评论