基于python的边界提取程序

最近要用到VOC-2012的扩展数据集BSD,但是没有相应的边界图像,遂利用python处理mat文件得到相应的边界图文件。

首先是得到mat文件

import numpy as np
from scipy import io
import scipy.io


def edge(ID):
    ##将语义分割图像转为边界图,ID表示mat文件名,从txt文件中读取
    #加载mat文件
    a = scipy.io.loadmat('D:\\datasets\\cls\\' + ID + '.mat')
    #提取mat文件中的图像矩阵
    b = a['GTcls']['Segmentation']
    d = b[0][0]
    #计算矩阵的大小,长×宽,h×w
    h = len(d)
    w = len(d[0])
    #创建新的0矩阵
    f = np.zeros((h, w), dtype=np.int)

    #遍历d,找出边界点
    for i in range(h - 1):
        for j in range(w - 1):
            if d[i][j] != 0:
                if d[i][j] == d[i - 1][j] == d[i + 1][j] == d[i][j - 1] == d[i][j + 1] == d[i - 1][j - 1] == d[i - 1][j + 1] == d[i + 1][j - 1] == d[i + 1][j + 1]:
                    continue
                else:
                    f[i][j] = 1
                continue
    #将边界矩阵f传回mat文件
    b[0][0] = f
    a['GTcls']['Segmentation'] = b
    #保存新的mat文件
    scipy.io.savemat('D:\\datasets\\edge_val\\' + ID + '.mat', a)

fin = open('D:\\datasets\\val.txt')
for line in fin:
    ID = line.strip()
    edge(ID)
    print(ID)

经过python处理后的mat文件大小会变得很大,可以去matlab中载入重新保存解决(批量代码在另一篇博客中)

由于不需要所有的可视化图像,所以将此程序分开。

from PIL import Image
import scipy.io

_target = Image.fromarray(scipy.io.loadmat('D:\\datasets\\benchmark\\benchmark\\benchmark_RELEASE\dataset\\SBD_edge\\2007_006490.mat')["GTcls"][0]['Segmentation'][0])
######   .convert('L')
_target.save('D:\\datasets\\009.png')
_target.show()

猜你喜欢

转载自blog.csdn.net/qq_36804414/article/details/107891767
今日推荐