最近下载美国马萨诸塞州道路数据集后发现训练集中有大量空白区域,参考使用该数据集的论文,均对训练集进行挑选过滤,于是写此代码过滤含有大量空白区域的数据
如图
筛选前
筛选后
代码部分如下
代码注释掉的部分是为了保存影像所对应的标签,如果有需要的同学可以取消注释。使用时需要输入影像路径和过滤后保存的路径,空白阈值根据不同数据集的具体情况可以自己调整,我这里使用的10%,空白区域超过10%的影像将被过滤掉。
import os
import cv2
import numpy as np
import shutil
#影像路径
img_path = r''
#标签路径
#label_path = r''
#筛选影像保存路径
imsa_path = r''
#对应标签保存路径
#lasa_path = r''
#空白阈值,这里我设置为0.1,可根据数据集调整
rat = 0.1
name = os.listdir(img_path)
fuhe = []
for i in name:
img = cv2.imread(img_path+'/'+ i,-1)
img = np.array(img)
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.uint32)
# img = np.float32(img)
cd = np.unique(img)
# xx 为统计各个像素值的数量列表
xx = np.bincount(img.flatten(),minlength=256)
cout = xx[255]
zong = img.shape[0]*img.shape[1]
if cout/zong < rat:
fuhe.append(i)
#创建保存文件夹路径
if not os.path.exists(imsa_path):
os.makedirs(imsa_path)
#if not os.path.exists(lasa_path):
#os.makedirs(lasa_path)
for i in fuhe:
#移动
# shutil.move(img_path,imsa_path)
# shutil.move(label_path,lasa_path)
#复制完移动
shutil.copyfile(img_path+'/'+i,imsa_path+'/'+i)
#shutil.copyfile(label_path+'/'+i.replace('.tiff','.tif'),lasa_path+'/'+i)