PASCAL VOC数据集下载,分析,可视化

1. 如何获取VOC数据集:参考博客

2. VOC数据集详细分析:参考博客

3. 把标注框画到图上

       在做目标检测时,首先要检查标注数据。一方面是要了解标注的情况,另一方面是检查数据集的标注和格式是否正确,只有正确的情况下才能进行下一步的训练。

# --------------------------------------------------------
# Check the VOC data used by detect project
# Written by Guo Pei in 20191106
# --------------------------------------------------------

from __future__ import print_function
import os
import sys
import cv2
import random
from tqdm import tqdm
import numpy as np
import argparse
import xml.etree.ElementTree as ET


def xml_reader(filename):
    """ Parse a PASCAL VOC xml file """
    tree = ET.parse(filename)
    objects = []
    for obj in tree.findall('object'):
        obj_struct = {}
        obj_struct['name'] = obj.find('name').text
        bbox = obj.find('bndbox')
        obj_struct['bbox'] = [int(bbox.find('xmin').text),
                              int(bbox.find('ymin').text),
                              int(bbox.find('xmax').text),
                              int(bbox.find('ymax').text)]
        objects.append(obj_struct)

    return objects


def get_image_list(image_dir, suffix=['jpg','png']):
    '''get all image path ends with suffix'''
    if not os.path.exists(image_dir):
        print("PATH:%s not exists" % image_dir)
        return []
    imglist = []
    for root, sdirs, files in os.walk(image_dir):
        if not files:
            continue
        for filename in files:
            filepath = os.path.join(root, filename)
            if filename.split('.')[-1] in suffix:
                imglist.append(filepath)
    return imglist



if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='check data')
    parser.add_argument('--input', dest='input', help='The input dir of images', type=str)
    parser.add_argument('--output', dest='output',default='temp', help='The output dir of images', type=str)
    parser.add_argument('--num', dest='num', default=50, help='The number of images you want to check', type=int)
    args = parser.parse_args()

    if not os.path.exists(args.output):
        os.makedirs(args.output)

    img_list = get_image_list(args.input)
    img_list = random.sample(img_list, args.num)

    for img_path in tqdm(img_list):
        img = cv2.imread(img_path)
        if img is None or not img.any():
            continue
        xml_path = img_path.replace("JPEGImages", "Annotations").replace(".jpg", ".xml").replace(".png", ".xml")
        objects = xml_reader(xml_path)
        if len(objects) == 0:
            continue
        
        # draw box and name
        for obj in objects:
            name = obj['name']
            box = obj['bbox']
            p1 = (box[0], box[1])
            p2 = (box[2], box[3])
            p3 = (max(box[0], 15), max(box[1], 15))
            cv2.rectangle(img, p1, p2, (0, 0, 255), 2)
            cv2.putText(img, name, p3, cv2.FONT_ITALIC, 1, (0, 255, 0), 2)

        img_name = os.path.basename(img_path)
        cv2.imwrite(os.path.join(args.output, img_name), img)
python detect_data_check.py --input VOCdevkit/VOC2007/JPEGImages

  运行上面的代码,就会在当前目录下创建一个temp文件夹,里面的有50张画框的图片。如图:

Caption

里面的图片如下:

Caption
Caption

今天就介绍到这里,用voc做你的研究吧!喜欢就关注一下博主!!!

 

 如果可视化yolo的标签,可参考以下代码:

import os
import cv2
import random
import glob


def draw_img(img, txt_file):
    h, w, _ = img.shape
    with open(txt_file, "r") as f:
        lines = f.readlines()
    for line in lines:
        label, cx, cy, cw, ch = [float(i) for i in line.rstrip().split(" ")]
        x = int((cx-0.5*cw)*w)
        y = int((cy-0.5*ch)*h)
        x2 = int((cx+0.5*cw)*w)
        y2 = int((cy+0.5*ch)*h)
        cv2.rectangle(img, (x,y), (x2, y2), (0,0,255), 2)
    return img

if __name__ == "__main__":
    # 获得图片
    img_list = glob.glob("images/train/*.jpg")
    img_list = random.sample(img_list, 50)
    for img_path in img_list:
        img = cv2.imread(img_path)
        txt_file = img_path.replace('images', 'labels').replace('.jpg', '.txt')
        img_new = draw_img(img, txt_file)

        cv2.imshow("test", img_new)

        if cv2.waitKey(10000) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值