栅格处理(杂):栅格重分类或特定值转图层(批处理)

今天与同学交流的一个问题:如果提取一个栅格数据tif中特定的值并生成新的栅格数据,其他值设为空,这和重分类比较像,存放一下代码实现。

栅格读写tif的参考这,关于并行的看一下multiprocessing多进程,先看一下电脑的最大核数。关于tif压缩格式可以看之前笔记最底部的测试。

非并行

代码逻辑比较直白。这里提取的是[10,20,30,40],空值设为了0,新文件名称这里直接将默认值添加到了后缀,可自行修改,代码测试无误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'''
@File : reclass_tif.py
@Time : 2022/08/30 21:15:45
@Author : huangsh
@Version : 1.0
@Contact : 1126456109@qq.com
@Desc : None
'''
#未安装包可以先安装 conda install -c conda-forge rasterio
import rasterio
from glob import glob
import os
import numpy as np

path = r"C:\Users\huangs\Desktop\test\inpath\\"
files = glob(path+"*.tif")
print(files)
outpath = r"C:\Users\huangs\Desktop\test\outpath\\"
for file in files:
with rasterio.open(file) as src_dataset:
profiles = src_dataset.profile
band = src_dataset.read(1)
# 目标值更新
for value in [10,20,30,40]:
band_up = np.array(band)
band_up[band_up!=value] = 0
# 设置输出文件路径,压缩格式可以选择'DEFLATE'
outfile = outpath+os.path.basename(file).replace(".tif","_"+str(value)+".tif")
profiles.update(nodata=0,compress='LZW')
with rasterio.open(outfile, 'w', **profiles) as dst:
dst.write(band_up, 1)

并行

multiprocessing多进程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*-coding:utf-8 -*-
'''
@File : reclass_tif.py
@Time : 2022/08/30 21:15:45
@Author : huangsh
@Version : 1.0
@Contact : 1126456109@qq.com
@Desc : None
'''
# conda install -c conda-forge rasterio
import rasterio
from glob import glob
import os
import numpy as np
from multiprocessing import Pool


outpath = r"C:\Users\huangs\Desktop\test\outpath\\"
def reclass(file):
with rasterio.open(file) as src_dataset:
profiles = src_dataset.profile
band = src_dataset.read(1)
# 目标值更新
for value in [10,20,30,40]:
band_up = np.array(band)
band_up[band_up!=value] = 0
# 设置输出文件路径,压缩格式可以选择'DEFLATE'
outfile = outpath+os.path.basename(file).replace(".tif","_"+str(value)+".tif")
profiles.update(nodata=0,compress='LZW')
with rasterio.open(outfile, 'w', **profiles) as dst:
dst.write(band_up, 1)
if __name__ == '__main__':
path = r"C:\Users\huangs\Desktop\test\inpath\\"
files = glob(path+"*.tif")
print(files)

pool = Pool(8)
# files是一个参数列表list,[file1, file2, ...]
pool.map(reclass, files)