我正在尝试通过覆盖多边形来提取像素值。我在Patrick Gray(http://patrickgray.me/open-geo-tutorial/chapter_5_classification.html)之后使用代码。当我用形状特征遮盖图像时,得到了out_image。然后,下一步是删除0,这将完全弄乱数组,因为根据频段不存在值。我只编码了一个月,我尝试了多种方法来删除0并根据类保持band值的顺序。在R中,我可以毫无问题地做到这一点,当我将数据导出为CSV并训练算法时,在Python环境中一切正常。
如何提取像素值并保持数字级别和类级别?
X = np.array([], dtype=np.int8).reshape(0,8) # pixels for training
y = np.array([], dtype=np.string_) # labels for training
with rasterio.open(img_fp) as src:
band_count = src.count
for index, geom in enumerate(geoms):
feature = [mapping(geom)]
# the mask function returns an array of the raster pixels within this feature
out_image, out_transform = mask(src, feature, crop=True)
# eliminate all the pixels with 0 values for all 8 bands - AKA not actually part of the shapefile
out_image_trimmed = out_image[:,~np.all(out_image == 0, axis=0)]
# eliminate all the pixels with 255 values for all 8 bands - AKA not actually part of the shapefile
out_image_trimmed = out_image_trimmed[:,~np.all(out_image_trimmed == 255, axis=0)]
# reshape the array to [pixel count, bands]
out_image_reshaped = out_image_trimmed.reshape(-1, band_count)
# append the labels to the y array
y = np.append(y,[shapefile["Classname"][index]] * out_image_reshaped.shape[0])
# stack the pizels onto the pixel array
X = np.vstack((X,out_image_reshaped))
非常感谢您的提示!
消除所有8个波段的0值的所有像素-AKA实际上不是shapefile的一部分:
out_image_trimmed = out_image[:,~np.all(out_image == 0, axis=0)]
消除所有8个波段的255个值的所有像素-AKA实际上不是shapefile的一部分:
out_image_trimmed = out_image_trimmed[:,~np.all(out_image_trimmed == 255, axis=0)]