图像来源于Python读取16位的多光谱遥感图像中得到的三通道16位图像
形状在此(提取码:vnym)
# 参考《python地理空间分析指南》
from osgeo import gdal, gdal_array, osr
import numpy as np
import operator
import shapefile
import cv2
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
raster = 'phase2/stretched.tif' # 上一步导出的tif作为用于裁剪的栅格图像
shp = 'phase2/mask' # 用于裁剪的shp
output = 'phase2/maskcliped.tif' # 裁剪后的栅格文件名
# 影像库数组转化为gdal_array图片
def img2array(img):
ima = gdal_array.numpy.fromstring(img.tobytes(), 'b')
ima.shape = img.im.size[1], img.im.size[0]
return ima
# 计算地理坐标的像素位置
def world2pixel(geo_mat, x, y):
ul_x, x_dist, rtn_x, ul_y, rtn_y, y_dist = [geo_mat[i] for i in range(6)]
pixel = int((x - ul_x) / x_dist)
line = int((ul_y - y) / abs(y_dist))
return pixel, line
src_arr = gdal_array.LoadFile(raster) # 载入数据
# 获取世界文件
src_img = gdal.Open(raster)
geo_trans = src_img.GetGeoTransform()
# 使用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_trans, min_x, max_y)
lr_x, lr_y = world2pixel(geo_trans, 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_trans)
geo_trans[0] = min_x
geo_trans[3] = max_y
# 边界线
pixels = []
for p in m_shp.shape(0).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_img = gdal_array.numpy.choose(mask_arr, (clip_img, 0)).astype(gdal_array.numpy.uint16)
# 保存为tiff
out = gdal_array.SaveArray(clip_img, output, format='GTiff', prototype=raster)
out = None
D:\Anaconda\ProgramData\Anaconda3\envs\geopy\lib\site-packages\ipykernel_launcher.py:3: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
This is separate from the ipykernel package so we can avoid doing imports until
# 加载图像康康
NUMS = 65536
cliped = gdal_array.LoadFile(output)
clip_arr = cv2.merge((cliped[0]/float(NUMS), cliped[1]/float(NUMS), cliped[2]/float(NUMS)))
plt.figure(figsize=(10, 10))
plt.imshow(clip_arr)
plt.show()