仅个人记录:shp裁剪tif;shp裁剪shp;矢量转栅格;多个shp裁剪shp;栅格边界矢量化。汇总:输入shp和影像,输出影像对应的标签(栅格边界矢量化,shp裁剪shp,shp转tif)_运用shp文件裁剪tif-程序员宅基地

技术标签: 原型模式  

shp裁剪tif

# -*- coding: utf-8 -*-
import os
import numpy as np
from osgeo import gdal, gdalnumeric, ogr, osr, gdal_array
gdal.UseExceptions()

def world2Pixel(geoMatrix, x, y):
  """
  Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
  the pixel location of a geospatial coordinate
  """
  ulX = geoMatrix[0]
  ulY = geoMatrix[3]
  xDist = geoMatrix[1]
  yDist = geoMatrix[5]
  rtnX = geoMatrix[2]
  rtnY = geoMatrix[4]
  pixel = int((x - ulX) / xDist)
  line = int((ulY - y) / xDist)
  return (pixel, line)

#
#  EDIT: this is basically an overloaded
#  version of the gdal_array.OpenArray passing in xoff, yoff explicitly
#  so we can pass these params off to CopyDatasetInfo
#
def OpenArray( array, prototype_ds = None, xoff=0, yoff=0 ):
    # ds = gdal.Open( gdalnumeric.GetArrayFilename(array))
    ds = gdal_array.OpenArray(array)

    if ds is not None and prototype_ds is not None:
        if type(prototype_ds).__name__ == 'str':
            prototype_ds = gdal.Open( prototype_ds )
        if prototype_ds is not None:
            gdalnumeric.CopyDatasetInfo( prototype_ds, ds, xoff=xoff, yoff=yoff )
    return ds


def write_img(filename,im_proj,im_geotrans,im_data):
    if 'int8' in im_data.dtype.name:
        datatype = gdal.GDT_Byte
    elif 'int16' in im_data.dtype.name:
        datatype = gdal.GDT_UInt16
    else:
        datatype = gdal.GDT_Float32

    if len(im_data.shape) == 3:
        im_bands, im_height, im_width = im_data.shape
    else:
        im_bands, (im_height, im_width) = 1,im_data.shape 

    driver = gdal.GetDriverByName("GTiff")
    dataset = driver.Create(filename, im_width, im_height, im_bands, datatype)

    dataset.SetGeoTransform(im_geotrans)
    dataset.SetProjection(im_proj)
    if im_bands == 1:
        dataset.GetRasterBand(1).WriteArray(im_data)
    else:
        for i in range(im_bands):
            dataset.GetRasterBand(i+1).WriteArray(im_data[i])

    del dataset

def shpClipRaster(shapefile_path, raster_path, save_path):
    # Load the source data as a gdalnumeric array
    # srcArray = gdalnumeric.LoadFile(raster_path)

    # Also load as a gdal image to get geotransform
    # (world file) info
    srcImage = gdal.Open(raster_path)
    geoTrans = srcImage.GetGeoTransform()
    geoProj = srcImage.GetProjection()

    # Create an OGR layer from a boundary shapefile
    shapef = ogr.Open(shapefile_path)
    lyr = shapef.GetLayer( os.path.split( os.path.splitext( shapefile_path )[0] )[1] )
    poly = lyr.GetNextFeature()

    # Convert the layer extent to image pixel coordinates
    minX, maxX, minY, maxY = lyr.GetExtent()
    ulX, ulY = world2Pixel(geoTrans, minX, maxY)
    lrX, lrY = world2Pixel(geoTrans, maxX, minY)

    # Calculate the pixel size of the new image
    pxWidth = int(lrX - ulX)
    pxHeight = int(lrY - ulY)

    # clip = srcArray[:, ulY:lrY, ulX:lrX]
    clip = srcImage.ReadAsArray(ulX,ulY,pxWidth,pxHeight)   #***只读要的那块***

    #
    # EDIT: create pixel offset to pass to new image Projection info
    #
    xoffset =  ulX
    yoffset =  ulY
    print ("Xoffset, Yoffset = ( %f, %f )" % ( xoffset, yoffset ))

    # Create a new geomatrix for the image
    geoTrans = list(geoTrans)
    geoTrans[0] = minX
    geoTrans[3] = maxY

    write_img(save_path, geoProj, geoTrans, clip)
    gdal.ErrorReset()

if __name__ == "__main__":
    shp = "dataset/E22_Bound.shp"
    img = "dataset/CGdomYRJ-114(CK0-17)_E_22.tif"
    out = "dataset/E22.tif"

    shpClipRaster(shp,img,out)
    print(img)

shp裁剪shp

import os
from osgeo import gdal, ogr

def ShapeClip(
		baseFilePath,
		maskFilePath,
		saveFolderPath):
	"""
	矢量裁剪
	:param baseFilePath: 要裁剪的矢量文件
	:param maskFilePath: 掩膜矢量文件
	:param saveFolderPath: 裁剪后的矢量文件保存目录
	:return:
	"""
	ogr.RegisterAll()
	gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
	# 载入要裁剪的矢量文件

	baseData = ogr.Open(baseFilePath)
	print(os.path.split( os.path.splitext( baseFilePath )[0] )[1])
	baseLayer = baseData.GetLayer( os.path.split( os.path.splitext( baseFilePath )[0] )[1] )

	spatial = baseLayer.GetSpatialRef()
	geomType = baseLayer.GetGeomType()
	baseLayerName = baseLayer.GetName()
	# 载入掩膜矢量文件
	maskData = ogr.Open(maskFilePath)
	maskLayer = maskData.GetLayer()
	maskLayerName = maskLayer.GetName()
	# 生成裁剪后的矢量文件
	outLayerName = maskLayerName + "_Clip_" + baseLayerName
	outFilePath = saveFolderPath
	gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
	driver = ogr.GetDriverByName("ESRI Shapefile")
	outData = driver.CreateDataSource(outFilePath)
	outLayer = outData.CreateLayer(outLayerName, spatial, geomType)
	baseLayer.Clip(maskLayer, outLayer)
	outData.Release()
	baseData.Release()
	maskData.Release()
	return outFilePath


if __name__ == "__main__":
	baseFilePath = 'dataset/veg_E_22.shp'
	maskFilePath = 'dataset/E22_Bound.shp'
	saveFolderPath = 'dataset/E22.shp'
	outFilePath=ShapeClip(baseFilePath,maskFilePath,saveFolderPath)
	print(outFilePath)

矢量转栅格

from osgeo import gdal, ogr, gdalconst
def shp2Raster(shp,templatePic,output,nodata):
    """
    shp:字符串,一个矢量,从0开始计数,整数
    templatePic:字符串,模板栅格,一个tif,地理变换信息从这里读,栅格大小与该栅格一致
    output:字符串,输出栅格,一个tif
    field:字符串,栅格值的字段
    nodata:整型或浮点型,矢量空白区转换后的值
    """
    ndsm = templatePic
    data = gdal.Open(ndsm, gdalconst.GA_ReadOnly)
    geo_transform = data.GetGeoTransform()
    proj=data.GetProjection()
    #source_layer = data.GetLayer()
    x_min = geo_transform[0]
    y_max = geo_transform[3]
    x_max = x_min + geo_transform[1] * data.RasterXSize
    y_min = y_max + geo_transform[5] * data.RasterYSize
    x_res = data.RasterXSize
    y_res = data.RasterYSize
    mb_v = ogr.Open(shp)
    mb_l = mb_v.GetLayer()
    pixel_width = geo_transform[1]
    #输出影像为24位整型
    target_ds = gdal.GetDriverByName('GTiff').Create(output, x_res, y_res, 1, gdal.GPI_RGB)

    target_ds.SetGeoTransform(geo_transform)
    target_ds.SetProjection(proj)
    band = target_ds.GetRasterBand(1)
    NoData_value = nodata
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(target_ds, [1], mb_l, options=['ALL_TOUCHED=TRUE'])

    target_ds = None

if __name__ == "__main__":
    shp = "dataset/E22.shp"
    templatePic= "dataset/E22.tif"
    output = "dataset/E22_mask.tif"
    nodata=0
    shp2Raster(shp,templatePic,output,nodata)
    

多个shp裁剪shp

import os
import os
import numpy as np
from osgeo import gdal, gdalnumeric, ogr, osr, gdal_array
gdal.UseExceptions()

def world2Pixel(geoMatrix, x, y):
  """
  Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
  the pixel location of a geospatial coordinate
  """
  ulX = geoMatrix[0]
  ulY = geoMatrix[3]
  xDist = geoMatrix[1]
  yDist = geoMatrix[5]
  rtnX = geoMatrix[2]
  rtnY = geoMatrix[4]
  pixel = int((x - ulX) / xDist)
  line = int((ulY - y) / xDist)
  return (pixel, line)

#
#  EDIT: this is basically an overloaded
#  version of the gdal_array.OpenArray passing in xoff, yoff explicitly
#  so we can pass these params off to CopyDatasetInfo
#
def OpenArray( array, prototype_ds = None, xoff=0, yoff=0 ):
    # ds = gdal.Open( gdalnumeric.GetArrayFilename(array))
    ds = gdal_array.OpenArray(array)

    if ds is not None and prototype_ds is not None:
        if type(prototype_ds).__name__ == 'str':
            prototype_ds = gdal.Open( prototype_ds )
        if prototype_ds is not None:
            gdalnumeric.CopyDatasetInfo( prototype_ds, ds, xoff=xoff, yoff=yoff )
    return ds


def write_img(filename,im_proj,im_geotrans,im_data):
    if 'int8' in im_data.dtype.name:
        datatype = gdal.GDT_Byte
    elif 'int16' in im_data.dtype.name:
        datatype = gdal.GDT_UInt16
    else:
        datatype = gdal.GDT_Float32

    if len(im_data.shape) == 3:
        im_bands, im_height, im_width = im_data.shape
    else:
        im_bands, (im_height, im_width) = 1,im_data.shape 

    driver = gdal.GetDriverByName("GTiff")
    dataset = driver.Create(filename, im_width, im_height, im_bands, datatype)

    dataset.SetGeoTransform(im_geotrans)
    dataset.SetProjection(im_proj)
    if im_bands == 1:
        dataset.GetRasterBand(1).WriteArray(im_data)
    else:
        for i in range(im_bands):
            dataset.GetRasterBand(i+1).WriteArray(im_data[i])

    del dataset

pre_path='dataset/pre/'
labellist = filter(lambda x: x.find('label')!=-1, os.listdir(pre_path))
list1 = list(map(lambda x: x[:], labellist))
label_name=pre_path +  list1[0]

boundarylist = filter(lambda x: x.find('shp')!=-1, os.listdir(pre_path+'boundary/'))
list2 = list(map(lambda x: x[:], boundarylist))


imagelist = filter(lambda x: x.find('tif')!=-1, os.listdir(pre_path))
list3 = list(map(lambda x: x[:], imagelist))
img_path=pre_path +  list3[0]


"""
矢量裁剪
:param label_name: 要裁剪的矢量文件
:param boundary_name: 掩膜矢量文件
img_path: 影像
:param saveFolderPath: 裁剪后的矢量文件保存目录
:return:
"""
ogr.RegisterAll()
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
# 载入要裁剪的矢量文件

labelData = ogr.Open(label_name)

labelLayer = labelData.GetLayer( os.path.split( os.path.splitext( label_name )[0] )[1] )

spatial = labelLayer.GetSpatialRef()
geomType = labelLayer.GetGeomType()


# 载入掩膜矢量文件

def new_func(outLayerName):
    return outLayerName

for i in list2:
    boundary_name=pre_path+'boundary/'+ i
    maskData = ogr.Open(boundary_name)
    maskLayer = maskData.GetLayer()
    #裁剪shp
    # 生成裁剪后的矢量文件
    save_shp_dir='./dataset/pre/shp/'
    if not os.path.exists(save_shp_dir):
        os.mkdir(save_shp_dir)
    outLayerName = (save_shp_dir+i)
    gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
    driver = ogr.GetDriverByName("ESRI Shapefile")
    outData = driver.CreateDataSource(outLayerName)
    outLayer = outData.CreateLayer(new_func(outLayerName), spatial, geomType)
    labelLayer.Clip(maskLayer, outLayer)
    outData.Release()
    maskData.Release()

    #裁剪tif

    shp = "dataset/E22_Bound.shp"
    img = "dataset/CGdomYRJ-114(CK0-17)_E_22.tif"
    out = "dataset/E22.tif"
    # Load the source data as a gdalnumeric array
    # srcArray = gdalnumeric.LoadFile(raster_path)

    # Also load as a gdal image to get geotransform
    # (world file) info
    srcImage = gdal.Open(raster_path)
    geoTrans = srcImage.GetGeoTransform()
    geoProj = srcImage.GetProjection()

    # Create an OGR layer from a boundary shapefile
    shapef = ogr.Open(shapefile_path)
    lyr = shapef.GetLayer( os.path.split( os.path.splitext( shapefile_path )[0] )[1] )
    poly = lyr.GetNextFeature()

    # Convert the layer extent to image pixel coordinates
    minX, maxX, minY, maxY = lyr.GetExtent()
    ulX, ulY = world2Pixel(geoTrans, minX, maxY)
    lrX, lrY = world2Pixel(geoTrans, maxX, minY)

    # Calculate the pixel size of the new image
    pxWidth = int(lrX - ulX)
    pxHeight = int(lrY - ulY)

    # clip = srcArray[:, ulY:lrY, ulX:lrX]
    clip = srcImage.ReadAsArray(ulX,ulY,pxWidth,pxHeight)   #***只读要的那块***

    #
    # EDIT: create pixel offset to pass to new image Projection info
    #
    xoffset =  ulX
    yoffset =  ulY
    print ("Xoffset, Yoffset = ( %f, %f )" % ( xoffset, yoffset ))

    # Create a new geomatrix for the image
    geoTrans = list(geoTrans)
    geoTrans[0] = minX
    geoTrans[3] = maxY

    write_img(save_path, geoProj, geoTrans, clip)
    gdal.ErrorReset()
labelData.Release()

汇总:输入shp和影像,输出影像对应的标签

#影像裁剪shp,转为栅格,为该影像标签
#输入:存放影像文件夹dataset/sat_train,存放标签矢量文件夹dataset/mask_shp
#输出:标签(栅格),存放在dataset/mask_train

from osgeo import gdal, ogr, osr, gdalconst
import fnmatch
import os

def ShapeClip(
		baseFilePath,
		maskFilePath,
		saveFolderPath):
	"""
	矢量裁剪
	:param baseFilePath: 要裁剪的矢量文件
	:param maskFilePath: 掩膜矢量文件
	:param saveFolderPath: 裁剪后的矢量文件保存目录
	:return:
	"""
	ogr.RegisterAll()
	gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
	# 载入要裁剪的矢量文件

	baseData = ogr.Open(baseFilePath)
	baseLayer = baseData.GetLayer( os.path.split( os.path.splitext( baseFilePath )[0] )[1] )

	spatial = baseLayer.GetSpatialRef()
	geomType = baseLayer.GetGeomType()
	baseLayerName = baseLayer.GetName()
	# 载入掩膜矢量文件
	maskData = ogr.Open(maskFilePath)
	maskLayer = maskData.GetLayer()
	maskLayerName = maskLayer.GetName()
	# 生成裁剪后的矢量文件
	outLayerName = maskLayerName + "_Clip_" + baseLayerName
	outFilePath = saveFolderPath
	gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
	driver = ogr.GetDriverByName("ESRI Shapefile")
	outData = driver.CreateDataSource(outFilePath)
	outLayer = outData.CreateLayer(outLayerName, spatial, geomType)
	baseLayer.Clip(maskLayer, outLayer)
	outData.Release()
	baseData.Release()
	maskData.Release()
	return outFilePath

def shp2Raster(shp,templatePic,output,nodata):
    """
    shp:字符串,一个矢量,从0开始计数,整数
    templatePic:字符串,模板栅格,一个tif,地理变换信息从这里读,栅格大小与该栅格一致
    output:字符串,输出栅格,一个tif
    field:字符串,栅格值的字段
    nodata:整型或浮点型,矢量空白区转换后的值
    """
    ndsm = templatePic
    data = gdal.Open(ndsm, gdalconst.GA_ReadOnly)
    geo_transform = data.GetGeoTransform()
    proj=data.GetProjection()
    #source_layer = data.GetLayer()
    x_min = geo_transform[0]
    y_max = geo_transform[3]
    x_max = x_min + geo_transform[1] * data.RasterXSize
    y_min = y_max + geo_transform[5] * data.RasterYSize
    x_res = data.RasterXSize
    y_res = data.RasterYSize
    mb_v = ogr.Open(shp)
    mb_l = mb_v.GetLayer()
    pixel_width = geo_transform[1]
    #输出影像为24位整型
    target_ds = gdal.GetDriverByName('GTiff').Create(output, x_res, y_res, 1, gdal.GPI_RGB)

    target_ds.SetGeoTransform(geo_transform)
    target_ds.SetProjection(proj)
    band = target_ds.GetRasterBand(1)
    NoData_value = nodata
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(target_ds, [1], mb_l, options=['ALL_TOUCHED=TRUE'])

    target_ds = None

print("开始制作标签")
ogr.RegisterAll()
img_path="dataset/sat_train/" #影像所在的文件夹
mask_shp_path="dataset/mask_shp/" #原始标签shp位置

shape_path="dataset/mask_boundary_shp/" #shape输出位置
mask_clip_path='dataset/mask_clip_train/'#裁剪后shp
mask_train_path='dataset/mask_train/'#最终输出标签文件夹
if not os.path.exists(shape_path):
    os.mkdir(shape_path)
if not os.path.exists(mask_clip_path):
    os.mkdir(mask_clip_path)

imagelist = filter(lambda x: x.find('shp')!=-1, os.listdir(mask_shp_path))
list = list(map(lambda x: x[:], imagelist))
mask_shp_name=mask_shp_path +  list[0]
img_list = fnmatch.filter(os.listdir(img_path), '*.tif')
for img in img_list:
    p_img=img_path+img
    outfilename = shape_path+img[:-4]+".shp"
    dataset = gdal.Open(p_img)
    oDriver = ogr.GetDriverByName('ESRI Shapefile')
    oDS = oDriver.CreateDataSource(outfilename)
    srs = osr.SpatialReference(wkt=dataset.GetProjection())
    geocd = dataset.GetGeoTransform()
    oLayer = oDS.CreateLayer("polygon", srs, ogr.wkbPolygon)
    oDefn = oLayer.GetLayerDefn()
    row = dataset.RasterXSize
    line = dataset.RasterYSize
    geoxmin = geocd[0]
    geoymin = geocd[3]
    geoxmax = geocd[0] + (row) * geocd[1] + (line) * geocd[2]
    geoymax = geocd[3] + (row) * geocd[4] + (line) * geocd[5]
    ring = ogr.Geometry(ogr.wkbLinearRing)
    ring.AddPoint(geoxmin, geoymin)
    ring.AddPoint(geoxmax, geoymin)
    ring.AddPoint(geoxmax, geoymax)
    ring.AddPoint(geoxmin, geoymax)
    ring.CloseRings()
    poly = ogr.Geometry(ogr.wkbPolygon)
    poly.AddGeometry(ring)
    outfeat = ogr.Feature(oDefn)
    outfeat.SetGeometry(poly)
    oLayer.CreateFeature(outfeat)
    outfeat = None
    oDS.Destroy()
    mask_train_name = mask_clip_path+img[:-4]+".shp"
    #裁剪
    outFilePath=ShapeClip(mask_shp_name,outfilename, mask_train_name)
    #矢量转栅格
    output = mask_train_path + img
    nodata=0
    shp2Raster(mask_train_name,p_img,output,nodata)
    print(output)
    
print('标签制作完成')

 做mask

'根据多个给定范围shp,对画好的标签进行裁剪并转栅格,做为标签样本,对影像进行裁剪,作为影像样本'
'输入:'
'输出'
import os
import os
import numpy as np
from osgeo import gdal, gdalnumeric, ogr, osr, gdal_array
gdal.UseExceptions()

def world2Pixel(geoMatrix, x, y):
  """
  Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
  the pixel location of a geospatial coordinate
  """
  ulX = geoMatrix[0]
  ulY = geoMatrix[3]
  xDist = geoMatrix[1]
  yDist = geoMatrix[5]
  rtnX = geoMatrix[2]
  rtnY = geoMatrix[4]
  pixel = int((x - ulX) / xDist)
  line = int((ulY - y) / xDist)
  return (pixel, line)

#
#  EDIT: this is basically an overloaded
#  version of the gdal_array.OpenArray passing in xoff, yoff explicitly
#  so we can pass these params off to CopyDatasetInfo
#
def OpenArray( array, prototype_ds = None, xoff=0, yoff=0 ):
    # ds = gdal.Open( gdalnumeric.GetArrayFilename(array))
    ds = gdal_array.OpenArray(array)

    if ds is not None and prototype_ds is not None:
        if type(prototype_ds).__name__ == 'str':
            prototype_ds = gdal.Open( prototype_ds )
        if prototype_ds is not None:
            gdalnumeric.CopyDatasetInfo( prototype_ds, ds, xoff=xoff, yoff=yoff )
    return ds


def write_img(filename,im_proj,im_geotrans,im_data):
    if 'int8' in im_data.dtype.name:
        datatype = gdal.GDT_Byte
    elif 'int16' in im_data.dtype.name:
        datatype = gdal.GDT_UInt16
    else:
        datatype = gdal.GDT_Float32

    if len(im_data.shape) == 3:
        im_bands, im_height, im_width = im_data.shape
    else:
        im_bands, (im_height, im_width) = 1,im_data.shape 

    driver = gdal.GetDriverByName("GTiff")
    dataset = driver.Create(filename, im_width, im_height, im_bands, datatype)

    dataset.SetGeoTransform(im_geotrans)
    dataset.SetProjection(im_proj)
    if im_bands == 1:
        dataset.GetRasterBand(1).WriteArray(im_data)
    else:
        for i in range(im_bands):
            dataset.GetRasterBand(i+1).WriteArray(im_data[i])

    del dataset


def shp2Raster(shp,templatePic,output,nodata):
    """
    shp:字符串,一个矢量,从0开始计数,整数
    templatePic:字符串,模板栅格,一个tif,地理变换信息从这里读,栅格大小与该栅格一致
    output:字符串,输出栅格,一个tif
    field:字符串,栅格值的字段
    nodata:整型或浮点型,矢量空白区转换后的值
    """
    ndsm = templatePic
    data = gdal.Open(ndsm, gdalconst.GA_ReadOnly)
    geo_transform = data.GetGeoTransform()
    proj=data.GetProjection()
    #source_layer = data.GetLayer()
    x_min = geo_transform[0]
    y_max = geo_transform[3]
    x_max = x_min + geo_transform[1] * data.RasterXSize
    y_min = y_max + geo_transform[5] * data.RasterYSize
    x_res = data.RasterXSize
    y_res = data.RasterYSize
    mb_v = ogr.Open(shp)
    mb_l = mb_v.GetLayer()
    pixel_width = geo_transform[1]
    #输出影像为24位整型
    target_ds = gdal.GetDriverByName('GTiff').Create(output, x_res, y_res, 1, gdal.GPI_RGB)
 
    target_ds.SetGeoTransform(geo_transform)
    target_ds.SetProjection(proj)
    band = target_ds.GetRasterBand(1)
    NoData_value = nodata
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(target_ds, [1], mb_l, options=['ALL_TOUCHED=TRUE'])
 
    target_ds = None


pre_path='dataset/pre/'

mask_train_path='dataset/mask_train/'#最终输出标签文件夹

labellist = filter(lambda x: x.find('label')!=-1, os.listdir(pre_path))
list1 = list(map(lambda x: x[:], labellist))
label_name=pre_path +  list1[0]

boundarylist = filter(lambda x: x.find('.shp')!=-1, os.listdir(pre_path+'boundary/'))
list2 = list(map(lambda x: x[:], boundarylist))


imagelist = filter(lambda x: x.find('tif')!=-1, os.listdir(pre_path+'img'))
list3 = list(map(lambda x: x[:], imagelist))
img_path=pre_path +  list3[0]


"""
矢量裁剪
:param label_name: 要裁剪的矢量文件
:param boundary_name: 掩膜矢量文件
img_path: 影像
:param saveFolderPath: 裁剪后的矢量文件保存目录
:return:
"""
print('开始用矢量范围裁剪影像')
ogr.RegisterAll()
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
# 载入要裁剪的矢量文件

labelData = ogr.Open(label_name)

labelLayer = labelData.GetLayer( os.path.split( os.path.splitext( label_name )[0] )[1] )

spatial = labelLayer.GetSpatialRef()
geomType = labelLayer.GetGeomType()


# 载入掩膜矢量文件

def new_func(outLayerName):
    return outLayerName

for i in list2:
    boundary_name=pre_path+'boundary/'+ i
    maskData = ogr.Open(boundary_name)
    maskLayer = maskData.GetLayer()
    #裁剪shp
    # 生成裁剪后的矢量文件
    save_shp_dir='./dataset/pre/shp/'
    if not os.path.exists(save_shp_dir):
        os.mkdir(save_shp_dir)
    outLayerName = (save_shp_dir+i)
    gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
    driver = ogr.GetDriverByName("ESRI Shapefile")
    outData = driver.CreateDataSource(outLayerName)
    outLayer = outData.CreateLayer(new_func(outLayerName), spatial, geomType)
    labelLayer.Clip(maskLayer, outLayer)

    lyr = maskData.GetLayer( os.path.split( os.path.splitext( boundary_name )[0] )[1] )
    shpminX, shpmaxX, shpminY, shpmaxY = lyr.GetExtent()



    #裁剪tif
    flag=0
    for j in list3:
        raster_path = pre_path+'img/'+j
        srcImage = gdal.Open(raster_path)
        geocd = srcImage.GetGeoTransform()
        geoProj = srcImage.GetProjection()
        row = srcImage.RasterXSize
        line = srcImage.RasterYSize
        tifxmin = geocd[0]
        tifymin = geocd[3]
        tifxmax = geocd[0] + (row) * geocd[1] + (line) * geocd[2]
        tifymax = geocd[3] + (row) * geocd[4] + (line) * geocd[5]
        if shpminX>=tifxmin and shpmaxX<=tifxmax and shpminY<=tifymin and shpmaxY>=tifymax:
            ulX, ulY = world2Pixel(geocd, shpminX, shpmaxY)
            lrX, lrY = world2Pixel(geocd, shpmaxX, shpminY)
            # Calculate the pixel size of the new image
            pxWidth = int(lrX - ulX)
            pxHeight = int(lrY - ulY)
            clip = srcImage.ReadAsArray(ulX,ulY,pxWidth,pxHeight)   #***只读要的那块***
            xoffset =  ulX
            yoffset =  ulY
            geoTrans = list(geoTrans)
            geoTrans[0] = shpminX
            geoTrans[3] = shpmaxY
            save_path='dataset/sat_train/'+i[:-4]+'.tif'
            write_img(save_path, geoProj, geoTrans, clip)
            gdal.ErrorReset()
            outData.Release()
            maskData.Release()
            flag=1
            output = mask_train_path + i[:-4] +'.tif'
            nodata=0
            shp2Raster(outLayerName,save_path,output,nodata)
    if flag==0:
        print(raster_path+"没有制作")
    else:
        print(raster_path)
labelData.Release()
    




 做了一半的

import os
import os
import numpy as np
from osgeo import gdal, gdalnumeric, ogr, osr, gdal_array
gdal.UseExceptions()

def world2Pixel(geoMatrix, x, y):
  """
  Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
  the pixel location of a geospatial coordinate
  """
  ulX = geoMatrix[0]
  ulY = geoMatrix[3]
  xDist = geoMatrix[1]
  yDist = geoMatrix[5]
  rtnX = geoMatrix[2]
  rtnY = geoMatrix[4]
  pixel = int((x - ulX) / xDist)
  line = int((ulY - y) / xDist)
  return (pixel, line)

#
#  EDIT: this is basically an overloaded
#  version of the gdal_array.OpenArray passing in xoff, yoff explicitly
#  so we can pass these params off to CopyDatasetInfo
#
def OpenArray( array, prototype_ds = None, xoff=0, yoff=0 ):
    # ds = gdal.Open( gdalnumeric.GetArrayFilename(array))
    ds = gdal_array.OpenArray(array)

    if ds is not None and prototype_ds is not None:
        if type(prototype_ds).__name__ == 'str':
            prototype_ds = gdal.Open( prototype_ds )
        if prototype_ds is not None:
            gdalnumeric.CopyDatasetInfo( prototype_ds, ds, xoff=xoff, yoff=yoff )
    return ds


def write_img(filename,im_proj,im_geotrans,im_data):
    if 'int8' in im_data.dtype.name:
        datatype = gdal.GDT_Byte
    elif 'int16' in im_data.dtype.name:
        datatype = gdal.GDT_UInt16
    else:
        datatype = gdal.GDT_Float32

    if len(im_data.shape) == 3:
        im_bands, im_height, im_width = im_data.shape
    else:
        im_bands, (im_height, im_width) = 1,im_data.shape 

    driver = gdal.GetDriverByName("GTiff")
    dataset = driver.Create(filename, im_width, im_height, im_bands, datatype)

    dataset.SetGeoTransform(im_geotrans)
    dataset.SetProjection(im_proj)
    if im_bands == 1:
        dataset.GetRasterBand(1).WriteArray(im_data)
    else:
        for i in range(im_bands):
            dataset.GetRasterBand(i+1).WriteArray(im_data[i])

    del dataset

pre_path='dataset/pre/'
labellist = filter(lambda x: x.find('label')!=-1, os.listdir(pre_path))
list1 = list(map(lambda x: x[:], labellist))
label_name=pre_path +  list1[0]

boundarylist = filter(lambda x: x.find('.shp')!=-1, os.listdir(pre_path+'boundary/'))
list2 = list(map(lambda x: x[:], boundarylist))


imagelist = filter(lambda x: x.find('tif')!=-1, os.listdir(pre_path+'img'))
list3 = list(map(lambda x: x[:], imagelist))
img_path=pre_path +  list3[0]


"""
矢量裁剪
:param label_name: 要裁剪的矢量文件
:param boundary_name: 掩膜矢量文件
img_path: 影像
:param saveFolderPath: 裁剪后的矢量文件保存目录
:return:
"""
print('开始用矢量范围裁剪影像')
ogr.RegisterAll()
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
# 载入要裁剪的矢量文件

labelData = ogr.Open(label_name)

labelLayer = labelData.GetLayer( os.path.split( os.path.splitext( label_name )[0] )[1] )

spatial = labelLayer.GetSpatialRef()
geomType = labelLayer.GetGeomType()


# 载入掩膜矢量文件

def new_func(outLayerName):
    return outLayerName

for i in list2:
    boundary_name=pre_path+'boundary/'+ i
    maskData = ogr.Open(boundary_name)
    maskLayer = maskData.GetLayer()
    #裁剪shp
    # 生成裁剪后的矢量文件
    save_shp_dir='./dataset/pre/shp/'
    if not os.path.exists(save_shp_dir):
        os.mkdir(save_shp_dir)
    outLayerName = (save_shp_dir+i)
    gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
    driver = ogr.GetDriverByName("ESRI Shapefile")
    outData = driver.CreateDataSource(outLayerName)
    outLayer = outData.CreateLayer(new_func(outLayerName), spatial, geomType)
    labelLayer.Clip(maskLayer, outLayer)
    
    lyr = maskData.GetLayer( os.path.split( os.path.splitext( boundary_name )[0] )[1] )
    shpminX, shpmaxX, shpminY, shpmaxY = lyr.GetExtent()



    #裁剪tif
    flag=0
    for j in list3:
        raster_path = pre_path+'img/'+j
        srcImage = gdal.Open(raster_path)
        geocd = srcImage.GetGeoTransform()
        geoProj = srcImage.GetProjection()
        row = srcImage.RasterXSize
        line = srcImage.RasterYSize
        tifxmin = geocd[0]
        tifymin = geocd[3]
        tifxmax = geocd[0] + (row) * geocd[1] + (line) * geocd[2]
        tifymax = geocd[3] + (row) * geocd[4] + (line) * geocd[5]
        if shpminX>=tifxmin and shpmaxX<=tifxmax and shpminY<=tifymin and shpmaxY>=tifymax:
            ulX, ulY = world2Pixel(geocd, shpminX, shpmaxY)
            lrX, lrY = world2Pixel(geocd, shpmaxX, shpminY)
            # Calculate the pixel size of the new image
            pxWidth = int(lrX - ulX)
            pxHeight = int(lrY - ulY)
            clip = srcImage.ReadAsArray(ulX,ulY,pxWidth,pxHeight)   #***只读要的那块***
            xoffset =  ulX
            yoffset =  ulY
            geocd = list(geocd)
            geocd[0] = shpminX
            geocd[3] = shpmaxY
            save_path='dataset/sat_train/'+i[:-4]+'.tif'
            write_img(save_path, geoProj, geocd, clip)
            gdal.ErrorReset()
            outData.Release()
            maskData.Release()
            flag=1
    if flag==0:
        print(raster_path+"没有制作")
    else:
        print(raster_path)
labelData.Release()
    




版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_61235989/article/details/130709482

智能推荐

ad19原理图标注_AD19中原理图的模板如何进行编辑?-程序员宅基地

文章浏览阅读8.5k次,点赞3次,收藏28次。我们在进行原理图设计的时候,有时候不想去用软件自带默认的模板,想要用自己设计的模板,就涉及到我们的模板怎么去编辑的呢?我们应该如何去编辑原理图自己设计的模板?操作步骤是怎么的呢?我们今天就以AD19为例去进行原理图的如何进行编辑的教程。1.首先我们需要把原理图的默认模板给取消掉,在属性框中找到“Title Bloc”前面的√给去掉即可,一下为对比图:那么,我们的默认模板就已经消失了。2.默认消..._ad19原理图标题栏修改

【漏洞复现】Apache系列(二)之Solr漏洞复现-程序员宅基地

文章浏览阅读7.1k次。【漏洞复现】Apache系列(二)之Solr漏洞复现_solr漏洞

规范字体:font-family 的用法-程序员宅基地

文章浏览阅读949次,点赞16次,收藏20次。一些前端UI库例如bootstrap会给根节点(例如/)设置类似这样(font-family: sans-serif;无衬线字体)的字体规范,以防止页面字体不统一。_font-family

基于虚拟相机的人脸识别 (视频) - Face recognition based on virtual camera_虚拟摄像头人脸识别教程-程序员宅基地

文章浏览阅读1.4w次,点赞12次,收藏57次。利用虚拟相机破解人脸识别 _虚拟摄像头人脸识别教程

使用OpenSSL实现https_openssl发起请求-程序员宅基地

文章浏览阅读1.5k次。一、配置OpenSSL生成证书1、由于是实验,所以要自己安装OpenSSL(官方地址https://www.openssl.org)生成证书,其版本号分为1.1和1.0两个大分支,Centos 7开始使用1.0.2k版本,如果配置的SSL需要达到苹果要求也需要1.0.2版本。1.1依赖的libssl也是1.1版本的,而系统默认的libsso库是1.0版本(ls /usr/lib64/libssl..._openssl发起请求

物联网平台系列 - 开源技术平台_开源物联网平台框架-程序员宅基地

文章浏览阅读2.4k次,点赞2次,收藏4次。物联网正在快速发展。许多组织和公司推出了各自的开源技术平台,这里对几个影响力比较大的平台做一下介绍。AllJoynAllJoyn是一个由Allseen联盟赞助的开源软件框架,基于邻近感应,支持互操作性,各种设备都可以直接相互查找、连接和通信,而无需借助中间服务器。- 许可协议:Apache2.0、BSD- 开发语言:C,C ++,OBJ-C,Java- _开源物联网平台框架

随便推点

Unity 2019 Android与Unity通信 UnityPlayerActivity找不到相关问题记录_unity导出android工程报错unityplayeractivity找不到unityplaye-程序员宅基地

文章浏览阅读4.9k次,点赞2次,收藏7次。解决思路:https://blog.csdn.net/LM514104/article/details/108518253需将C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Source\com\unity3d\player下的UnityPlayerActivity直接拖入安卓工程MainActivity(继承于UnityPlayerActivity)的目录下。之后打包出的arr只需获取里面的AndroidMani_unity导出android工程报错unityplayeractivity找不到unityplayer

Efficient detection under varying illumination conditions and image plane rotations_人脸光照不变特征-程序员宅基地

文章浏览阅读596次。摘要本文主要研究了不同光照和姿态下的兰伯曲面目标的检测问题。我们提供了一种新的检测方法,该方法通过对训练集中少量图像的不同光照进行建模;这将自动消除光照效果,允许快速的光照不变检测,而不需要创建一个大型的训练集。实验证明,该方法很好地“适应”了之前关于在不同光照下建模物体外观集的工作。在实验中,即使在存在显著阴影的情况下,在45范围内的图像平面旋转和各种不同光照下,也能正确地检测到目标。1、简介姿态和光照的微小变化会产生物体外观的巨大变化。在[9,16,19,20]中研究了不同类别几何变换或不同_人脸光照不变特征

【ROS2机器人入门到实战】_ros2机器人编程实战 pdf-程序员宅基地

文章浏览阅读1.3w次,点赞35次,收藏421次。1.ROS2前世今生2.ROS与ROS2对比3.动手安装ROS24.ROS2初体验。_ros2机器人编程实战 pdf

Android Studio 控制台中文乱码,解决方案都在这里了,完美解决_android studio 乱码-程序员宅基地

文章浏览阅读1.3w次,点赞24次,收藏35次。android studio 中文乱码问题,统一设置 UTF-8_android studio 乱码

第4章-Quartus 软件和 USB-Blaster 驱动安装_fpga的usb blaster安装驱动-程序员宅基地

文章浏览阅读1.9k次。接下来,我们以 Quartus II 13.0 版本为例,手把手教会各位实现 Quartus II 开发软件的。芯片,所以要使用 Altera 提供的配套开发软件 Quartus II,我们使用的是 13.0 版本---如图 4-11 所示,安装信息包括 Quartus II 软件。先, QaurtusII_13.0 版本是众多初学者习惯使用的版本,操作界面比较传统,众多教程都针。立安装器件库,组件的选择不包括器件库,如图 4-10 所示。另一种是独立安装,开发软件安装完毕后再进行器件库的安装,独。_fpga的usb blaster安装驱动

2024届【校招】安全面试题和岗位总结(字节、百度、腾讯、美团等大厂)_百度安全工程师面试笔试-程序员宅基地

文章浏览阅读1.5w次,点赞8次,收藏64次。个人强烈感觉面试因人而异,对于简历上有具体项目经历的同学,个人感觉面试官会着重让你介绍自己的项目,包括但不限于介绍一次真实攻防/渗透/挖洞/CTF/代码审计的经历 => 因此对于自己的项目,面试前建议做一次复盘,最好能用文字描述出细节,在面试时才不会磕磕绊绊、或者忘了一些自己很得意的细节面试题会一直更新(大概,直到我毕业或者躺平为止吧...)包括一些身边同学(若他们同意的话)和牛客上扒拉下来的(若有,会贴出链接)还有自己的一些经历。_百度安全工程师面试笔试

推荐文章

热门文章

相关标签