偶然间看到一个博文(https://blog.csdn.net/kimol_justdo/article/details/113774790),正好手里有1990-2015年的年均气温TIF图,也想尝试一下,看看中国近些年的温度变化情况。下图是所有文件:
1.基本情况介绍
下图是“中国1980年以来逐年年平均气温空间插值数据集”(详见资源环境科学与数据中心:http://www.resdc.cn/data.aspx?DATAID=228)
黑白&彩色图
2.代码实现过程
(1)代码
利用gdal.Info函数查看影像信息:
# 导入相应模块
import os
import cv2
import imageio
# import cv2 as cv
from PIL import Image
# step1:raster data to graydata
# 定义函数1:寻找影像的最大最小值
def MinMaxValue(img, tmin, tmax):
for i in range(img.shape[0]):
for j in range(img.shape[1]):
# 当设置为img[i,j]!=-3.40282299999999995e+38时,tmin最小值还是背景值;所以设置了一个范围-1000-1000,数据单位是0.1℃,中国应该不会超过这个温度范围。
# 或者用gdal.Info函数查看大小值等具体信息
if (img[i, j] > -1000) & (img[i, j] < 1000):
if img[i, j] >= tmax:
tmax = img[i, j]
for i in range(img.shape[0]):
for j in range(img.shape[1]):
# 当设置为img[i,j]!=-3.40282299999999995e+38时,tmin最小值还是背景值;所以设置了一个范围-1000-1000,数据单位是0.1℃,中国应该不会超过这个温度范围。
# 或者用gdal.Info函数查看大小值等具体信息
if (img[i, j] > -1000) & (img[i, j] < 1000):
if img[i, j] < tmin:
tmin = img[i, j]
return tmin,tmax
# 定义函数2:归一化处理
def Normalize(img,tmin,tmax):
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if (img[i, j] > -1000) & (img[i, j] < 1000):
# 归一化
img[i,j]=(img[i,j]-tmin)*255/(tmax-tmin)
else:
img[i,j]=0
return img
# step2:gray to Pseudo color
# 定义函数:灰度转伪彩色
def trans_color(img):
'''
将灰度图转为伪彩色:此部分红黄绿的颜色设置没有弄清楚
'''
for x in range(img.shape[0]):
for y in range(img.shape[1]):
if img[x][y][0] == 0 and img[x][y][1] == 0 and img[x][y][2] == 0: # 边缘区域跳过
continue
gray = img[x][y][0]
if gray <= 110: # 红
img[x][y][0] = 0
img[x][y][1] = 255
img[x][y][2] = 127-(127*gray/85)
elif gray <= 200: # 黄
gray -= 85
img[x][y][0] = 0
img[x][y][1] = 255
img[x][y][2] = 255-(127*gray/85)
else: # 绿
gray -= 170
img[x][y][0] = 0
img[x][y][1] = gray*1.5
img[x][y][2] = 255
return img
# step3 定义函数:PNGtoJPG
def PNG_JPG(PngPath):
img = cv2.cv.imread(PngPath, 0)
w, h = img.shape[::-1]
infile = PngPath
outfile = os.path.splitext(infile)[0] + ".jpg"
img = Image.open(infile)
img = img.resize((int(w / 2), int(h / 2)), Image.ANTIALIAS)
try:
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
img.convert('RGB').save(outfile, quality=70)
os.remove(PngPath)
else:
img.convert('RGB').save(outfile, quality=70)
os.remove(PngPath)
return outfile
except Exception as e:
print("PNG转换JPG 错误", e)
# step4:合成为gif图
# 定义函数:合成gif图
def create_gif(image_list, gif_name, duration=0.35):
'''
生成gif
'''
frames = []
for image_name in image_list:
frames.append(imageio.imread(image_name))
imageio.mimsave(gif_name, frames, 'GIF', duration=duration)
return
# 后续执行:
# 一、栅格转灰度
# 创建文件夹用于存储灰度图
grayPath = r'D:\ProfessionalProfile\TemperaturePrecipitationData\tem\.gray'
if not os.path.exists(grayPath):
# 以数字权限模式创建目录
os.mkdir(grayPath)
# 遍历tif文件
tifPath = r'D:\ProfessionalProfile\TemperaturePrecipitationData\tem\tem1990-2015'
# 返回指定路径下的文件和文件夹列表。
for file in os.listdir(tifPath):
if file.endswith('.tif'):
# flag = 2,原深度, 1通道;
img0 = cv2.imread('%s/%s' % (tifPath, file), 2)
# 调用函数1:寻找影像的最大最小值
tmin,tmax=MinMaxValue(img0,0,0)
# 调用函数2:归一化
img = Normalize(img0,tmin,tmax)
cv2.putText(img, 'Year %s' % file[9:13], (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1,
cv2.LINE_AA) # 加入年份说明
cv2.imwrite('%s/%s.png' % (grayPath, file.split('.')[0]), img)
print('"%s"处理完毕!' % file)
# 二、灰度转伪彩色
# 创建文件夹用于存储彩色图
rgbPath = r'D:\ProfessionalProfile\TemperaturePrecipitationData\tem\.rgb'
if not os.path.exists(rgbPath):
os.mkdir(rgbPath)
# 将灰度图转为彩色图
for file in os.listdir(grayPath):
img = cv2.imread('%s/%s' % (grayPath, file))
trans_color(img) # 转换
cv2.imwrite('%s/%s' % (rgbPath, file), img)
print('"%s"转换完毕!' % file)
# 三、转换图片格式:PNG——JPG
# os.getcwd() 方法用于返回当前工作目录。
path_root = os.getcwd()
# rgb的PNG格式图片路径
Path = r'D:\ProfessionalProfile\TemperaturePrecipitationData\tem\.rgb'
img_dir = os.listdir(Path)
for img in img_dir:
if img.endswith('.png'):
# python中路径问题参考:https://www.cnblogs.com/wangyueyouyi/p/9050266.html
PngPath= Path + '/' + img
# 调用格式转换函数
PNG_JPG(PngPath)
# os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
img_dir = os.listdir(Path)
for img in img_dir:
print(img)
# 四、合成gif图
images_list = []
for file in os.listdir(rgbPath):
images_list.append('%s/%s'%(rgbPath, file))
create_gif(images_list, 'tem.gif')
(2)得到的结果
第一部分:栅格转灰度
第二部:灰度转伪彩色转换结果
GIF图:链接:https://pan.baidu.com/s/1LEOeVUEuUY5LxxpKQKc_SQ 提取码:d2cn
(3)步骤:PNG图转JPG图
由于PNG图太大(218M),尝试将其转为jpg格式(50.6M)的再上传,没想到还是很大,无法上传。
希望了解的大神不吝赐教~
3.参考
(1)博文
https://blog.csdn.net/kimol_justdo/article/details/113774790
https://blog.csdn.net/weixin_40446557/article/details/104059660
https://www.cnblogs.com/wangyueyouyi/p/9050266.html
(2)数据
http://www.resdc.cn/data.aspx?DATAID=228