假设我有一个形状为512x512的图像,我应该再添加8行和8列,以使其形状为520x520。这样就可以将图像分成40x40形状的段。
使用代码:
import numpy as np
from skimage.util.shape import view_as_blocks
import gdal
ds = gdal.Open('D:\512.tiff')
band = ds.GetRasterBand(1)
arr1 = band.ReadAsArray()
arr1.shape
>>(512,512)
arr2 = np.zeros((8,512), dtype='float32')
arr3=np.vstack((arr1,arr2))
arr4=np.zeros((520,8), dtype='float32')
arr=np.hstack((arr3,arr4))
arr.shape
>>(520,520)
#Now, I can use this command to divide the image in to segements each of shape of 40x40 :
img= view_as_blocks(arr, block_shape=(40,40))
在这里,我的问题是,我总是想将图像分成40x40的形状,但是我的输入图像的大小总是不相同(512x512)。可以是(512x516)(529x517)或其他任何值。
所以我的代码要求是代码应该能够读取输入图像的形状,并且必须自动将“ n”个行和列的编号添加到使图像变为40x40形状的段中
答案 0 :(得分:0)
您可以为此使用天花板功能:
import math
import numpy as np
new_width = int(math.ceil(float(arr1.shape[1])/segment_width)*segment_width)
new_height = int(math.ceil(float(arr1.shape[0])/segment_height)*segment_height)
new_arr1 = np.zeros((new_height, new_width), dtype=arr1.dtype)
new_arr1[:arr1.shape[0], :arr1.shape[1]] = arr1
float
转换只是为了确保存在float
除法,而在python 3中则不需要。