Keras神经网络深度学习提取水体,采用了面状样本,简化了采样过程,结果为水体可能性。
1、原图
?2、面状样本? 0为非水体,1为水体
3、水体提取结果:从红色到蓝色(从0-1),是水体的可能性逐步增加。
?4、部分代码
# 获取世界文件
src_img1 = gdal.Open(raster1)
geo_trans1 = src_img1.GetGeoTransform()
nBands1 = src_img1.RasterCount
nBands=nBands1
# 使用pyshp
m_shp = shapefile.Reader("{}.shp".format(shp)) # 打开shp
# 将图层扩展转换为像素坐标
min_x, min_y, max_x, max_y = m_shp.bbox
ul_x, ul_y = world2pixel(geo_trans1, min_x, max_y)
lr_x, lr_y = world2pixel(geo_trans1, max_x, min_y)
# 计算新图片像素尺寸
px_wid = int(lr_x - ul_x)
px_hei = int(lr_y - ul_y)
clip_img = src_arr[:, ul_y:lr_y, ul_x:lr_x]
# 为图片创建一个新的geomatrix对象以便附加地理参考数据
geo_trans = list(geo_trans1)
geo_trans[0] = min_x
geo_trans[3] = max_y
s=0#循环指针
TrainData = np.empty(shape=[0, nBands])
TrainLabel=[]
while s<m_shp.numRecords:
pixels = []
for p in m_shp.shape(s).points:
pixels.append(world2pixel(geo_trans, p[0], p[1]))
raster_poly = Image.new('L', (px_wid, px_hei), 1)
# 使用PIL创建一个空白图片
raster_rize = ImageDraw.Draw(raster_poly)
raster_rize.polygon(pixels, 0)
# 将PIL转换为numpy
mask_arr = img2array(raster_poly)
# 裁剪
clip_arr = gdal_array.numpy.choose(mask_arr, (clip_img, 0)).astype(gdal_array.numpy.uint16)
clip_arr = changeDimension(clip_arr)
a2=clip_arr[~(clip_arr==0).all(1)]
TrainData = np.append(TrainData, a2, axis=0)
#读取样本标注信息,查找起来太麻烦,直接读取最后一位
value=m_shp.record(s)[-1]
lable= np.array([value for j in range(0, len(a2))])#for i in range(0, 1
TrainLabel=np.append(TrainLabel,lable,axis=0)
s=s+1
# 开始使用深度学习模型
# 数据数归一化
TrainData = normalization(TrainData)#xTrain / 255.0
TrainLabel = normalization(TrainLabel)#xTest / 255.0
源码下载地址:
https://download.csdn.net/download/sailingw/20818136
|