欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 图片数据集批量打标签

程序员文章站 2022-04-30 09:26:04
...

1.数据集介绍

OutdoorScene数据集:http://people.csail.mit.edu/torralba/code/spatialenvelope/

This dataset contains 8 outdoor scene categories: coast, mountain, forest, open country, street, inside city, tall buildings and highways.

There are 2688 color images, 256x256 pixels. All the objects and regions in this dataset have been fully labeled. There are more than 29.000 objects. The annotations are available in LabelMe format.

下载数据集并解压以后是这个样子的:

python 图片数据集批量打标签
部分数据集图片

 2.python实现批量打类别标签

可以看到数据集中的图片按 类别_编号.jpg 统一命名,用sqlit切割文件名,再判断他们属于哪一类,将结果保存到矩阵中,写入csv文件中即可。

import os
import numpy as np
import csv
'''
将outdoorscene数据集中的8类图片分别打标签
directory_name:数据集路径
'''
def read_directory(directory_name):
    
    i = 0
    print('文件个数:',len(os.listdir(directory_name)))
    img_target = np.zeros((len(os.listdir(directory_name)),8),dtype=int)

    for filename in os.listdir(directory_name):
       
        category = filename.split('_',1)[0]

        if category == 'coast':
            img_target[i,0]=1
        elif category == 'forest':
            img_target[i,1]=1
        elif category == 'highway':
            img_target[i,2]=1
        elif category == 'insidecity':
            img_target[i,3]=1
        elif category == 'mountain':
            img_target[i,4]=1
        elif category == 'opencountry':
            img_target[i,5]=1
        elif category == 'street':
            img_target[i,6]=1
        elif category == 'tallbuilding':
            img_target[i,7]=1            
        
        i=i+1

    return img_target

csvFile = open('target.csv','w', newline='')
writer = csv.writer(csvFile)
writer.writerows(list(read_directory("D:\spatial_envelope_256x256_static_8outdoorcategories")))
csvFile.close()

程序执行结果:

python 图片数据集批量打标签
csv文件