在进行遥感图像语义分割时,找到的标签数据都是方便给大家看的RGB数据,对于怎么将RGB转换成灰度数据我整了半天,编程水平太差了。文章仅记录自己的学习过程,路过的大佬轻喷,小菜鸡在此谢过了。第一次用博客记录自己的学习过程,还不太会用哈哈哈。
#导入相关包
import matplotlib.pyplot as plt
import numpy as np
import glob
import scipy.misc
from PIL import Image
import re
#这是我的标签数据对应像素值
label2color_dict = {
0:[0,0,0],
1:[200,0,0],
2:[250,0,150],
3:[200,150,150],
4:[250,150,150],
5:[0,200,0],
6:[150,250,0],
7:[150,200,150],
8:[200,0,200],
9:[150,0,250],
10:[150,150,250],
11:[250,200,0],
12:[200,200,0],
13:[0,0,200],
14:[0,150,200],
15:[0,200,250]
}
def get_keys(value):
'''
获取图片各像素value对应的key值
'''
p=0
i=0
for k,v in label2color_dict.items():
if v == value:
p = k
break
i += 1
if i > 15:
p = 0
return p
#glob.glob方法获取全部文件名
img_path = glob.glob("E:\BaiduNetdiskDownload\classif_dataset\*.png")
img_path = sorted(img_path, key=lambda img_path:int(re.search(r'(\d+)',img_path).group()))
for k in range(0, 10000):
img = img_path[k]
img = plt.imread(img)*255.0
img = img[:,:,:3]
img_label = np.zeros((img.shape[0],img.shape[1]),np.uint8)
img_new_label = np.zeros((img.shape[0],img.shape[1]),np.uint8)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
value = list(img[i,j,:])
img_label[i,j] = get_keys(value)
img_new_label[i,j] = img_label[i,j]
label0 = Image.fromarray(np.uint8(img_new_label))
p = str(k)
scipy.misc.toimage(img_label).save("E:\BaiduNetdiskDownload\classif_dataset\\"+p+".jpg")
代码有空优化,太啰嗦了,执行起来很慢很慢。。。。。