BSD500 mat 转化为 jpg 或者 png

BSD500 mat 转化为 jpg 或者 png

from PIL import Image
from matplotlib import pyplot as plt
import numpy as np
from scipy import io
import os
###运行时需要改变root值为BSD500所在的相应根目录
root = './data_and_code/BSDS500'
PATH = os.path.join(root,'groundTruth')

def convert(root, PATH):
    for sub_dir_name in ['train','test','val']:
        sub_pth = os.path.join(PATH,sub_dir_name)
        ##为生成的图片新建个文件夹保存
        save_pth = os.path.join(root,'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
            #因此需要还原回0
            edge_data_255 = edge_data * 255
            new_img_name = filename.split('.')[0]+'.jpg'
            print(new_img_name, type(new_img_name))

            dir = save_pth + "/" + new_img_name
            # print("savedir:",dir)
            new_img_name = Image.fromarray(edge_data_255)
            new_img_name.save(dir)

            # plt.imshow(new_img_name)
            # plt.show()

读取数据

# img = "./data_and_code/BSDS500/GT_convert/image/2092.jpg"
# label = "./data_and_code/BSDS500/GT_convert/train/2092.jpg"
#
# img = Image.open(img)
# label = Image.open(label)
# # print(np.max(label),np.min(label))
# label = np.array(label)
# f = open('a.txt', 'w')
# for i in range(label.shape[0]):
#     # f.write('\n')
#     for j in range(label.shape[1]):
#         print(label[i,j])
#         f.write(str(label[i,j]))
# f.close()


# plt.figure(figsize=(10, 10))
# plt.subplot(1, 2, 1)
# plt.imshow(img)
# plt.title("original ground")
#
# plt.subplot(1, 2, 2)
# plt.imshow(label)
# plt.title("label img")
# plt.show()

你可能感兴趣的:(RockPro,python,numpy)