python3 calculate the mean and the various types of surface features NDVI NDVI outlier point raster cell is written as vector graphics

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_37970770/article/details/102761571

A job

Please use the following statistical data of various land use types of NDVI average. NDVI values typically ranged from -1 to 1, set the cell location and area specific NDVI values outlier occurs, it generates a point shape file.
Data:
(. 1) Landsat8 surface reflectance file
LC08_L1TP_121041_121042_20190312_T1_sr_scale_mosaic_clip.tif
NDVI Landsat8 the formula: NDVI = (Band5-Band4) / (Band5 + Band4)
land-use maps (2) Meichuan Jiang basin and documentation
landuse30_clip.tif
landuse_lookup. CSV
landuse_readme.txt
inspection points:
write raster file, write vector shape files (ratio required to master)
Numpy skilled applications using meshgrid function (ratio required to master)
Matplotlib drawing (this operation may be optional)
Submit Request :
(1) basic python code file, (2) in ArcMap, land use picture shows the background to the foreground SHAPE point (NDVI positive outlier point is red, negative outlier point of blue) make a figures, copy screen (or export map) to generate a jpg file. If you proactive, we can use matplotlib the land-use maps and NDVI outliers shape files stacked together to produce a jpg file.
(3) The above two files compressed into a rar file, named "Student ID _ name .rar" submitted to the course website, such as: 2019001002_zhangwentian.rar.
Please complete independence, guitar lessons as part of the results.

Title Description

landuse_lookup. csv memory of the "land-use code" and "SWAT vegetation types within the" look-up table. Wherein,
AGRL agricultural
SWRn Grassland
RNGB shrub
WATR water
URHD building land
FRSD deciduous
FRSE evergreen
FRST Mixed
landuse_code SWAT-vegname
10 AGRL
. 11 AGRL
12 is AGRL
30 SWRn
40 RNGB
60 WATR
61 is WATR
63 is WATR
80 URHD
90 URHD
211 FRSD
FRSE 221
230 FRST

Title Code (python3):

# -*- coding: utf-8 -*-
"""
Created on Sat Oct 19 23:27:54 2019

@author: Depei Bai
"""
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
import numpy as np
import os
import osgeo
#tab前进对齐,shift+tab后退对齐

#--------------------------------------read data------------------------------------
#读取土地利用数据
dataset_1 = gdal.Open("landuse30_clip.tif")
d1_samples = dataset_1.RasterXSize
d1_lines = dataset_1.RasterYSize
d1_bands = dataset_1.RasterCount
geotans_1 = dataset_1.GetGeoTransform()
proj_1 = dataset_1.GetProjection() 
data_1 = dataset_1.ReadAsArray(0,0,d1_samples,d1_lines)
del dataset_1
#读取OLI数据,计算NDVI图像
dataset_2 = gdal.Open("LC08_L1TP_121041_121042_20190312_T1_sr_scale_mosaic_clip.tif")
d2_samples = dataset_2.RasterXSize
d2_lines = dataset_2.RasterYSize
d2_bands = dataset_2.RasterCount
geotans_2 = dataset_2.GetGeoTransform() #左上角像元的大地坐标和图像分辨率
# //如果图像不含地理坐标信息,默认返回值是:(0,1,0,0,0,1)
# //In a north up image,
# //左上角点坐标(padfGeoTransform[0],padfGeoTransform[3]);
# //padfGeoTransform[1]是像元宽度(影像在宽度上的分辨率);
# /p/adfGeoTransform[5]是像元高度(影像在高度上的分辨率);
# //如果影像是指北的,padfGeoTransform[2]和padfGeoTransform[4]这两个参数的值为0。
#Fetches the coefficients for transforming between 列/行 (P,L) raster space, and projection coordinates (Xp,Yp) space
#Xp = padfTransform[0] + P*padfTransform[1] + L*padfTransform[2];
#Yp = padfTransform[3] + P*padfTransform[4] + L*padfTransform[5];
#————————————————
#版权声明:本文为CSDN博主「当空月」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
#原文链接:https://blog.csdn.net/yyt_enjoyvc/article/details/7828368
proj_2 = dataset_2.GetProjection() #指椭球体和投影方式
data_2 = dataset_2.ReadAsArray(0,0,d1_samples,d1_lines)#取了所有波段所有行列的数据
del dataset_2

#----------------------------------Calculate NDVI-------------------------------
NDVI = (data_2[4,:,:] * 1.0 - data_2[3,:,:] * 1.0)/(data_2[4,:,:] + data_2[3,:,:])

#----------------------------------calculate the meam_NDVI_value---------------
#每种地物类型统计其NDVI值的时候均需要取非异常值进行统计,剔除该类型中大于1和小于0的值
#np.where()无法在一个括号中单纯添加多个条件,而是要用多个括号,& 或 | 
#APPEND无返回值,因此不能用赋值符号
#list to numpy.array强制转换时不能在原值的基础上改,只能重新给到新的变量
#用作索引的数组必须是整型或者布尔型,np.array型是不能作为下标的,元组也不可以 
AGRL = np.where(((data_1 == 10)|(data_1 == 11)|(data_1 == 12))&(NDVI > -1)&(NDVI < 1))
mean_agrl = np.mean(NDVI[AGRL])
SWRN = np.where((data_1 == 30)&(NDVI > -1)&(NDVI < 1))
mean_swrn = np.mean(NDVI[SWRN])
RNGB = np.where((data_1 == 40)&(NDVI > -1)&(NDVI < 1))
mean_rngb = np.mean(NDVI[RNGB])
WATR = np.where(((data_1 == 60)|(data_1 == 61)|(data_1 == 63))&(NDVI > -1)&(NDVI < 1))
mean_watr = np.mean(NDVI[WATR])
URHD = np.where(((data_1 == 80)|(data_1 == 90))&(NDVI > -1)&(NDVI < 1))
mean_urhd = np.mean(NDVI[URHD])
FRSD = np.where((data_1 == 211)&(NDVI > -1)&(NDVI < 1))
mean_frsd = np.mean(NDVI[FRSD])
FRSE = np.where((data_1 == 221)&(NDVI > -1)&(NDVI < 1))
mean_frse = np.mean(NDVI[FRSE])
FRST = np.where((data_1 == 230)&(NDVI > -1)&(NDVI < 1))
mean_frst = np.mean(NDVI[FRST])
positive_outlier_index = np.where(NDVI > 1)
negative_outlier_index = np.where(NDVI < -1)

#---------------------------将异常值写入shape文件中------------------------------
osgeo.gdal.SetConfigOption('GDAL_FILENAME_IS_UTF8','NO')#解决中文路径
osgeo.gdal.SetConfigOption('SHAPE_ENCODING','gb2312')#解决SHAPE文件的属性值
filename = 'outlier_point.shp'
driver = ogr.GetDriverByName('ESRI Shapefile')
if os.access(filename,os.F_OK):
    driver.DeleteDataSource(filename)
#以上,如果文件存在,就删除,重新创建
ds = driver.CreateDataSource(filename)
spatialref = osr.SpatialReference(proj_2) #空间参考
#如果直接写spatialref = proj_2会提示错误
#TypeError: in method 'DataSource_CreateLayer', argument 3 of type 'OSRSpatialReferenceShadow *'
#attention: 如果原空间参考是投影坐标那就是4666548,535646这种,如果
#因此要通过osr.SpatialReference将proj_2字符串转为类

#原空间参考是经纬度坐标,则是12.4366655349731,-70.0561218261719这种
#不同的空间参考给出的原点处的位置参数也是不一样的
geomtype = ogr.wkbPoint  #shape类型是点
layer = ds.CreateLayer(filename[:-4],srs = spatialref,geom_type = geomtype)
#layer = ds.CreateLayer(filename[:-4],srs = spatialref,geom_type = geomtype)
#layer图层的名称即.shp之前的字符串,空间参考是spatialref,几何对象是点
loc_p1_line = positive_outlier_index[0][0]#第一个点的行号
loc_p1_sample = positive_outlier_index[1][0]#列号
geo_p1_x = geotans_2[0] +loc_p1_sample*geotans_2[1] + loc_p1_line*geotans_2[2]
geo_p1_y = geotans_2[3] + loc_p1_sample*geotans_2[4] + loc_p1_line*geotans_2[5]
pntp1_wkt = 'POINT('+str(geo_p1_x)+' '+str(geo_p1_y)+')'
#attention:中间的是空格,不能是逗号
loc_p2_line = positive_outlier_index[0][1]
loc_p2_sample = positive_outlier_index[1][1]
geo_p2_x = geotans_2[0] +loc_p2_sample*geotans_2[1] + loc_p2_line*geotans_2[2]
geo_p2_y = geotans_2[3] + loc_p2_sample*geotans_2[4] + loc_p2_line*geotans_2[5]
pntp2_wkt = 'POINT('+str(geo_p2_x)+' '+str(geo_p2_y)+')'

loc_p3_line = positive_outlier_index[0][2]
loc_p3_sample = positive_outlier_index[1][2]
geo_p3_x = geotans_2[0] + loc_p3_sample*geotans_2[1] + loc_p3_line*geotans_2[2]
geo_p3_y = geotans_2[3] + loc_p3_sample*geotans_2[4] + loc_p3_line*geotans_2[5]
pntp3_wkt = 'POINT('+str(geo_p3_x)+' '+str(geo_p3_y)+')'

loc_p4_line = positive_outlier_index[0][3]
loc_p4_sample = positive_outlier_index[1][3]
geo_p4_x = geotans_2[0] + loc_p4_sample*geotans_2[1] + loc_p4_line*geotans_2[2]
geo_p4_y = geotans_2[3] + loc_p4_sample*geotans_2[4] + loc_p4_line*geotans_2[5]
pntp4_wkt = 'POINT('+str(geo_p4_x)+' '+str(geo_p4_y)+')'

loc_p5_line = positive_outlier_index[0][4]
loc_p5_sample = positive_outlier_index[1][4]
geo_p5_x = geotans_2[0] + loc_p5_sample*geotans_2[1] + loc_p5_line*geotans_2[2]
geo_p5_y = geotans_2[3] + loc_p5_sample*geotans_2[4] + loc_p5_line*geotans_2[5]
pntp5_wkt = 'POINT('+str(geo_p5_x)+' '+str(geo_p5_y)+')'
#负异常值坐标求解
loc_n1_line = negative_outlier_index[0][0]
loc_n1_sample = negative_outlier_index[1][0]
geo_n1_x = geotans_2[0] + loc_n1_sample*geotans_2[1] + loc_n1_line*geotans_2[2]
geo_n1_y = geotans_2[3] + loc_n1_sample*geotans_2[4] + loc_n1_line*geotans_2[5]
pntn1_wkt = 'POINT('+str(geo_n1_x)+' '+str(geo_n1_y)+')'

#-------------------------------write geomlist--------------------------
#geomlist是一个里面,里面存放着字符串,因此需要将此六个点放入这个list中
#geomlist存放的是几何形状,点线面的几何构成坐标
geomlist = [pntp1_wkt,pntp2_wkt,pntp3_wkt,pntp4_wkt,pntp5_wkt,pntn1_wkt]

#---------------------write field list-------------------------------
#field list 是个列表,列表里面是每一个feature的属性,是个字典型,如下:
#{'name': 'FIPS_CNTRY', 'type': 4, 'width': 2, 'decimal': 0}
#因此只需将异常值点字段信息按照列表中字典的形式写入这个列表供后面使用即可
fieldlist = [{'name':'outlier_pt','type':4,'width':4,'decimal':0},\
             {'name':'code','type':4,'width':2,'decimal':0},\
             {'name':'color','type':4,'width':4,'decimal':0}] #创建字段list
#字段列表里每一个{}的内容即为shape属性表头一行的名称及其详细规定
#type: 0 int ;1 longinteger ;2 float ; 3 double; 4 text;5 date
#name 字段名称长度不能超过11个字母
#------------------------------------------------------------------
#本实验添加了三个字段,一个是“异常点”,一个是编码,一个是颜色
#用pi表示正异常值,i from 1 to n,代号1 ,颜色red
#用nj表示负异常值,j from 1 to m,代号-1,颜色blue
#geolocation = np.ones([2,6],dtype = float)
#------------------------------------------------------------------
#python也是先行后列
for fd in fieldlist:
    field = ogr.FieldDefn(fd['name'],fd['type'])
    if 'width' in fd:
        field.SetWidth(fd['width'])
    if 'decimal' in fd:
        field.SetPrecision(fd['decimal'])
    layer.CreateField(field)
#-------------------------------write reclist-------------------------
#reclist为每个几何图形对应三个字段fieldlist的具体值
#如第一个图形outlierpoints叫p1,code为1,颜色是红色,是具体值
#如最后一个图形outlierpoints叫n1,code为-1,颜色是蓝色,是具体值
#本实验中的图形均为点
reclist = [{'outlier_pt':'p1','code':1,'color':'red'},\
           {'outlier_pt':'p2','code':1,'color':'red'},\
           {'outlier_pt':'p3','code':1,'color':'red'},\
           {'outlier_pt':'p4','code':1,'color':'red'},\
           {'outlier_pt':'p5','code':1,'color':'red'},\
           {'outlier_pt':'n1','code':-1,'color':'blue'}]
#给出所创建好的图形(geomlist)中的字段(fieldlist)的具体值(reclist)

#----------------------------------write shape------------------------
for j in range(len(reclist)):
    feat = ogr.Feature(layer.GetLayerDefn())
    geom = ogr.CreateGeometryFromWkt(geomlist[j])
    feat.SetGeometry(geom)
    for f_d in fieldlist:
        feat.SetField(f_d['name'],reclist[j][f_d['name']])
    layer.CreateFeature(feat)
ds.Destroy()

result

Here Insert Picture Description

Which belongs to the author white white _ all, reproduced, please indicate the link to the source!

Guess you like

Origin blog.csdn.net/qq_37970770/article/details/102761571
Recommended