本文整理汇总了Python中rasterio.windows.Window方法的典型用法代码示例。如果您正苦于以下问题:Python windows.Window方法的具体用法?Python windows.Window怎么用?Python windows.Window使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rasterio.windows
的用法示例。
在下文中一共展示了windows.Window方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __setitem__
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def __setitem__(self, key, item):
"""Put the data chunk in the image"""
if len(key) == 3:
index_range, y, x = key
indexes = list(
range(index_range.start + 1, index_range.stop + 1,
index_range.step or 1))
else:
indexes = 1
y, x = key
chy_off = y.start
chy = y.stop - y.start
chx_off = x.start
chx = x.stop - x.start
self.dataset.write(
item, window=Window(chx_off, chy_off, chx, chy), indexes=indexes)
示例2: head
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def head(self):
"""Show the head (first rows, first columns) or tail (last rows, last columns)
of pixels.
"""
window = Window(col_off=0, row_off=0, width=20, height=10)
return self.read(window=window)
示例3: tail
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def tail(self):
"""Show the head (first rows, first columns) or tail (last rows, last columns)
of pixels.
"""
window = Window(
col_off=self.width - 20, row_off=self.height - 10, width=20, height=10
)
return self.read(window=window)
示例4: block_shapes
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def block_shapes(self, rows, cols):
"""Generator for windows for optimal reading and writing based on the raster
format Windows are returns as a tuple with xoff, yoff, width, height.
Parameters
----------
rows : int
Height of window in rows.
cols : int
Width of window in columns.
"""
for i in range(0, self.width, rows):
if i + rows < self.width:
num_cols = rows
else:
num_cols = self.width - i
for j in range(0, self.height, cols):
if j + cols < self.height:
num_rows = rows
else:
num_rows = self.height - j
yield Window(i, j, num_cols, num_rows)
示例5: read_raster_band
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def read_raster_band(path, band=1, block_size=1):
"""Read a raster band and return a Dask array
Arguments:
path {string} -- path to the raster file
Keyword Arguments:
band {int} -- number of band to read (default: {1})
block_size {int} -- block size multiplier (default: {1})
"""
def read_window(raster_path, window, band):
with rasterio.open(raster_path) as src:
return src.read(band, window=window)
def resize_window(window, block_size):
return Window(
col_off=window.col_off * block_size,
row_off=window.row_off * block_size,
width=window.width * block_size,
height=window.height * block_size)
def block_windows(dataset, band, block_size):
return [(pos, resize_window(win, block_size))
for pos, win in dataset.block_windows(band)]
with rasterio.open(path) as src:
h, w = src.block_shapes[band - 1]
chunks = (h * block_size, w * block_size)
name = 'raster-{}'.format(tokenize(path, band, chunks))
dtype = src.dtypes[band - 1]
shape = src.shape
blocks = block_windows(src, band, block_size)
dsk = {(name, i, j): (read_window, path, window, band)
for (i, j), window in blocks}
return da.Array(dsk, name, chunks, dtype, shape)
示例6: _get_blocks
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def _get_blocks(extrema):
for j in range(extrema["y"]["max"] - extrema["y"]["min"]):
row = j * 256
for i in range(extrema["x"]["max"] - extrema["x"]["min"]):
col = i * 256
yield (j, i), Window(col_off=col, row_off=row, width=256, height=256)
示例7: rasterio_windows
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def rasterio_windows(totalWidth,totalHeight,subWidth,subHeight):
w_n=list(divide_chunks(list(range(totalWidth)), subWidth))
h_n=list(divide_chunks(list(range(totalHeight)), subHeight))
wins=[Window(w[0],h[0],len(w),len(h)) for h in h_n for w in w_n]
# print(wins)
print("raster windows amount:",len(wins))
return wins
#meter=degree*(2 * math.pi * 6378137.0)/ 360 degree=50/(2 * math.pi * 6378137.0) * 360
示例8: rasterio_windows
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def rasterio_windows(totalWidth,totalHeight,subWidth,subHeight):
w_n=list(divide_chunks(list(range(totalWidth)), subWidth))
h_n=list(divide_chunks(list(range(totalHeight)), subHeight))
wins=[Window(w[0],h[0],len(w),len(h)) for h in h_n for w in w_n]
# print(wins)
'''之下的代码繁复,并无法处理边界高宽问题,弃之'''
# if totalWidth%subWidth==0 and totalHeight%subHeight==0:
# w_n=[subWidth*i for i in range(totalWidth//subWidth)]
# h_n=[subHeight*i for i in range(totalHeight//subHeight)]
# wins=[Window(w,h,subWidth,subHeight) for h in h_n for w in w_n]
# if totalWidth%subWidth==0 and totalHeight%subHeight!=0:
# w_n=[subWidth*i for i in range(totalWidth//subWidth)]
# h_n=[subHeight*i for i in range(totalHeight//subHeight+1)]
# wins=[Window(w,h,subWidth,subHeight) for h in h_n for w in w_n]
# if totalWidth%subWidth!=0 and totalHeight%subHeight==0:
# w_n=[subWidth*i for i in range(totalWidth//subWidth+1)]
# h_n=[subHeight*i for i in range(totalHeight//subHeight)]
# wins=[Window(w,h,subWidth,subHeight) for h in h_n for w in w_n]
# if totalWidth%subWidth!=0 and totalHeight%subHeight!=0:
# w_n=[subWidth*i for i in range(totalWidth//subWidth+1)]
# h_n=[subHeight*i for i in range(totalHeight//subHeight+1)]
# wins=[Window(w,h,subWidth,subHeight) for h in h_n for w in w_n]
print("raster windows amount:",len(wins))
return wins
#testing 测试部分,可丢弃
示例9: rasterio_windows
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def rasterio_windows(totalWidth,totalHeight,subWidth,subHeight):
w_n=list(divide_chunks(list(range(totalWidth)), subWidth))
h_n=list(divide_chunks(list(range(totalHeight)), subHeight))
wins=[Window(w[0],h[0],len(w),len(h)) for h in h_n for w in w_n]
# print(wins)
print("raster windows amount:",len(wins))
return wins
# @njit(parallel=True)
#栅格重分类计算。如果栅格数据很大,采用rasterio的window读取数据,并计算,可以避免内存溢出
示例10: rasterio_windows
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def rasterio_windows(totalWidth,totalHeight,subWidth,subHeight):
w_n=list(divide_chunks(list(range(totalWidth)), subWidth))
h_n=list(divide_chunks(list(range(totalHeight)), subHeight))
wins=[Window(w[0],h[0],len(w),len(h)) for h in h_n for w in w_n]
# print(wins)
print("raster windows amount:",len(wins))
return wins
# @njit(parallel=True)
# @cuda.jit(debug=True)
示例11: download_tile_tms
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def download_tile_tms(tile, imagery, folder, kwargs):
"""Download a satellite image tile from a tms endpoint"""
image_format = get_image_format(imagery, kwargs)
if os.environ.get('ACCESS_TOKEN'):
token = os.environ.get('ACCESS_TOKEN')
imagery = imagery.format_map(SafeDict(ACCESS_TOKEN=token))
r = requests.get(url(tile.split('-'), imagery),
auth=kwargs.get('http_auth'))
tile_img = op.join(folder, '{}{}'.format(tile, image_format))
tile = tile.split('-')
over_zoom = kwargs.get('over_zoom')
if over_zoom:
new_zoom = over_zoom + kwargs.get('zoom')
# get children
child_tiles = children(int(tile[0]), int(tile[1]), int(tile[2]), zoom=new_zoom)
child_tiles.sort()
new_dim = 256 * (2 * over_zoom)
w_lst = []
for i in range (2 * over_zoom):
for j in range(2 * over_zoom):
window = Window(i * 256, j * 256, 256, 256)
w_lst.append(window)
# request children
with rasterio.open(tile_img, 'w', driver='jpeg', height=new_dim,
width=new_dim, count=3, dtype=rasterio.uint8) as w:
for num, t in enumerate(child_tiles):
t = [str(t[0]), str(t[1]), str(t[2])]
r = requests.get(url(t, imagery),
auth=kwargs.get('http_auth'))
img = np.array(Image.open(io.BytesIO(r.content)), dtype=np.uint8)
try:
img = img.reshape((256, 256, 3)) # 4 channels returned from some endpoints, but not all
except ValueError:
img = img.reshape((256, 256, 4))
img = img[:, :, :3]
img = np.rollaxis(img, 2, 0)
w.write(img, window=w_lst[num])
else:
r = requests.get(url(tile, imagery),
auth=kwargs.get('http_auth'))
with open(tile_img, 'wb')as w:
w.write(r.content)
return tile_img
示例12: process_tile
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def process_tile(tile):
"""Process a single MBTiles tile
Parameters
----------
tile : mercantile.Tile
Returns
-------
tile : mercantile.Tile
The input tile.
bytes : bytearray
Image bytes corresponding to the tile.
"""
global base_kwds, resampling, src
# Get the bounds of the tile.
ulx, uly = mercantile.xy(
*mercantile.ul(tile.x, tile.y, tile.z))
lrx, lry = mercantile.xy(
*mercantile.ul(tile.x + 1, tile.y + 1, tile.z))
kwds = base_kwds.copy()
kwds['transform'] = transform_from_bounds(ulx, lry, lrx, uly,
kwds['width'], kwds['height'])
src_nodata = kwds.pop('src_nodata', None)
dst_nodata = kwds.pop('dst_nodata', None)
warnings.simplefilter('ignore')
with MemoryFile() as memfile:
with memfile.open(**kwds) as tmp:
# determine window of source raster corresponding to the tile
# image, with small buffer at edges
try:
west, south, east, north = transform_bounds(TILES_CRS, src.crs, ulx, lry, lrx, uly)
tile_window = window_from_bounds(west, south, east, north, transform=src.transform)
adjusted_tile_window = Window(
tile_window.col_off - 1, tile_window.row_off - 1,
tile_window.width + 2, tile_window.height + 2)
tile_window = adjusted_tile_window.round_offsets().round_shape()
# if no data in window, skip processing the tile
if not src.read_masks(1, window=tile_window).any():
return tile, None
except ValueError:
log.info("Tile %r will not be skipped, even if empty. This is harmless.", tile)
reproject(rasterio.band(src, tmp.indexes),
rasterio.band(tmp, tmp.indexes),
src_nodata=src_nodata,
dst_nodata=dst_nodata,
num_threads=1,
resampling=resampling)
return tile, memfile.read()
示例13: readWriteRasterByBlock
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def readWriteRasterByBlock(rasterFp,saveRasterByBlock_fp):
'''reading and writing single block by para Defination '''
# win=Window(120, 145, 512, 256) # Window(col_off=10, row_off=10, width=80, height=80)
# with rasterio.open(rasterFp) as src:
# w = src.read(1, window=win)
# print(w.shape)
# profile=src.profile
# win_transform=src.window_transform(win)
# profile.update(
# width=512,
# height=256,
# count=1,
# transform=win_transform
# )
# # with rasterio.open(os.path.join(saveRasterByBlock_fp,"testingBlock.tif"), 'w', driver='GTiff' width=512, height=256, count=1,dtype=w.dtype,**profile) as dst:
# with rasterio.open(os.path.join(saveRasterByBlock_fp,"testingBlock.tif"), 'w', **profile) as dst:
# dst.write(w, window=Window(0, 0, 512, 256), indexes=1)
'''reading row by row'''
# with rasterio.open(rasterFp) as src:
# # for i, shape in enumerate(src.block_shapes, 1):
# # print((i, shape))
# i=0
# for ji, window in src.block_windows(1):
# print((ji, window))
# i+=1
# print(i)
with rasterio.open(rasterFp) as src:
i=0
for ji, window in src.block_windows(1):
print((ji, window))
r=src.read(1,window=window)
i+=1
print(r.shape)
break
print(i)
'''multi bands'''
# with rasterio.open('tests/data/RGB.byte.tif') as src:
# assert len(set(src.block_shapes)) == 1
# for ji, window in src.block_windows(1):
# b, g, r = (src.read(k, window=window) for k in (1, 2, 3))
# print((ji, r.shape, g.shape, b.shape))
# break
'''read block by block'''
# @njit(parallel=True)
#比较使用numba库并行计算结果,原始numpy布尔值计算方法,较之np.where采用numba并行计算更快
示例14: RWRasterBlocks
# 需要导入模块: from rasterio import windows [as 别名]
# 或者: from rasterio.windows import Window [as 别名]
def RWRasterBlocks(rasterFp,dataSave_fp, windowsList):
newPath=os.path.join(saveRasterByBlock_fp,"reclassify")
try:
os.mkdir(newPath)
except OSError:
print ("Creation of the directory %s failed" % newPath)
else:
print ("Successfully created the directory %s " % newPath)
a_T = datetime.datetime.now()
i=0
buildingAmount_epochMultiple=0
for win in tqdm(windowsList):
with rasterio.open(rasterFp,"r+") as src:
src.nodata=-1
w = src.read(1, window=win)
# print("_"*50)
# print(w.shape)
profile=src.profile
win_transform=src.window_transform(win)
#计算部分
w=computing(w)
#配置raster属性值,尤其compress和dtype参数部分,可以大幅度降低栅格大小
profile.update(
width=win.width,
height=win.height,
count=1,
transform=win_transform,
compress='lzw',
dtype=rasterio.int8
)
# with rasterio.open(os.path.join(saveRasterByBlock_fp,"testingBlock.tif"), 'w', driver='GTiff' width=512, height=256, count=1,dtype=w.dtype,**profile) as dst:
with rasterio.open(os.path.join(newPath,"buildingHeight_reclassify_%d.tif"%i), 'w', **profile) as dst:
dst.write(w, window=Window(0,0,win.width,win.height), indexes=1)
i+=1
# if i ==2:
# break
# np.save(os.path.join(dataSave_fp,"data_%d.npy"%zValue),buildingAmount_epochMultiple)
# buildingAmount[zValue]=buildingAmount_epochMultiple
# print("_"*50)
# print("%d---zValue has completed!!!"%zValue)
b_T= datetime.datetime.now()
print("time span:", b_T-a_T)
print("_"*50)
# print("total amount:",buildingAmount)
# np.save(os.path.join(dataSave_fp,"buildingFrequency.npy"),buildingAmount)
# return buildingAmount