参考:[https://blog.csdn.net/weixin_41443908/article/details/88638953](BSDS500分割数据集的下载及简单处理)
但是博主的代码运行不出来,因此我上传修改后可运行的代码及解释。
BSDS500数据集下载地址:下载BSDS500
因为BSDS500的原始文件是全部保存在Access数据库中的,但是想要应用它,就必须转换成普通的图像格式,例如.jpg、.png等。
(1)下载后的文件:
直接打开BSDS500/data 文件夹,由2部分组成:
我们这里只用到了groundTruth文件,代码中的bsdsRoot就用到了这个groundTruth所在文件夹的地址。
(2)新建文件夹:
在groundTruth文件夹下新建2个文件,分别命名为contour、segementation,分别表示将真值文件转换为轮廓图和区域分割图。
因为轮廓图和区域分割图分别分为3个步骤:训练、测试和验证,因此还需要在contour和segementation文件夹下再分别新建3个文件夹:train、test、val来分别存放训练、测试、验证的图像。
from scipy import io
import scipy
import os
###运行时需要改变root值为BSD500所在的相应根目录
root = 'E:\DataSets\BSR\BSDS500\data'
PATH = os.path.join(root,'data\\groundTruth')
for sub_dir_name in ['train','test','val']:
sub_pth = os.path.join(PATH,sub_dir_name)
##为生成的图片新建个文件夹保存
save_pth = os.path.join(root,'data\\GT_convert',sub_dir_name)
os.makedirs(save_pth,exist_ok=True)
print('开始转换'+sub_dir_name+'文件夹中内容')
for filename in os.listdir(sub_pth):
# 读取mat文件中所有数据
#mat文件里面是以字典形式存储的数据
#包括 dict_keys(['__globals__', 'groundTruth', '__header__', '__version__'])
#如果要用到'groundTruth']中的轮廓
#x['groundTruth'][0][0][0][0][1]为轮廓
#x['groundTruth'][0][0][0][0][0]为分割图
data = io.loadmat(os.path.join(sub_pth,filename))
edge_data = data['groundTruth'][0][0][0][0][1]
#存储的是归一化后的数据:0
BSDS中每张图片对应5个真值,为5个人标注的真值,训练时真值可采用平均值或者用来扩充数据。
源代码中的[0][0][0][0][1]代表轮廓图。[0][0][0][0][0]代表生成分割图。
% contour.m
% bsdsRoot 变量的值为包含train、test、val文件夹的地址
%在处理时应当提前在train、test、和val下新建文件夹contour,contour里需要新建train、test、val3个子文件夹
state = 'test';%修改为test或train或val,分别处理3个文件夹
bsdsRoot='E:\daily personal thing\Direction\3.18cob-thinking\code\BSDS500\BSR_bsds500\BSR\BSDS500\data\groundTruth';
file_list = dir(fullfile(bsdsRoot,state,'*.mat'));%获取该文件夹中所有jpg格式的图像
for i=1:length(file_list)
%mat = load(file_list(i).name);
mat = load(fullfile(bsdsRoot,state,file_list(i).name))
[~,image_name,~] = fileparts(file_list(i).name);
gt = mat.groundTruth;
for gtid=1:length(gt)
bmap = gt{gtid}.Boundaries;
if gtid==1
image = bmap;
else
image(bmap==true)=true;
end
end
%黑底白边
imwrite(double(image),fullfile(bsdsRoot,'contour',state,[image_name '.jpg']));
%白底黑边
%imwrite(1-double(image),fullfile(bsdsRoot,'contour',state,[image_name '.jpg']));
end
% segementation.m
% bsdsRoot 变量的值为包含train、test、val文件夹的地址
%在处理时应当提前在groundTruth下新建文件夹segementation,segementation里需要新建train、test、val三个子文件夹
%将state依次修改为test、train、val,即可完成对groundTruth下三个文件夹的处理并生成相应的jpg文件
state = 'test';
bsdsRoot='E:\daily personal thing\Direction\3.18cob-thinking\code\BSDS500\BSR_bsds500\BSR\BSDS500\data\groundTruth';
file_list = dir(fullfile(bsdsRoot,state,'*.mat'));%获取该文件夹中所有.mat格式的图像
for i=1:length(file_list)
mat = load(fullfile(bsdsRoot,state,file_list(i).name));
[~,image_name,~] = fileparts(file_list(i).name);
gt = mat.groundTruth;
for gtid=1:length(gt)
seg = double(gt{gtid}.Segmentation);
seg = seg/max(max(seg));
if gtid == 1
image = seg;
else
image = image+seg;
end
end
image = image/length(gt);
imwrite(double(image),fullfile(bsdsRoot,'segementation',state,[image_name '.jpg']));
end