Matrix2RGB

 1 def matrix2gray(mat):
 2     """
 3     convert matrix image into gray image
 4     :param mat: matrix (n x m) with numpy type
 5     :return:  mat
 6     """
 7     min_v = int(mat.min())
 8     max_v = int(mat.max())
 9     # 0--255
10     gray = (mat - min_v) / (max_v - min_v) * 255
11     return gray.astype(np.uint8)
12         
13 
14 def gray2rgb(gray, node_seg, color_dict):
15     """
16     convert c into RGB image
17     :param gray: single channel image with numpy type
18     :param color_dict: color map
19     :return:  rgb image
20     """
21     point0 = node_seg[0]
22     point1 = node_seg[0]
23     point2 = node_seg[0]
24     point3 = node_seg[0]
25     # 1:创建新图像容器
26     rgb_image = np.zeros(shape=(*gray.shape, 3))
27     # 2: 遍历每个像素点
28     for i in range(rgb_image.shape[0]):
29         for j in range(rgb_image.shape[1]):
30             # 3:对不同的灰度值选择不同的颜色
31             if gray[i, j] <= point0:
32                 rgb_image[i, j, :] = color_dict["color0"]
33             elif point1 >= gray[i, j] > point0:
34                 rgb_image[i, j, :] = color_dict["color1"]
35             elif point2 >= gray[i, j] > point1:
36                 rgb_image[i, j, :] = color_dict["color2"]
37             elif point3 >= gray[i, j] > point2:
38                 rgb_image[i, j, :] = color_dict["color2"]
39             else:
40                 rgb_image[i, j, :] = color_dict["color4"]
41     return rgb_image.astype(np.uint8)
42     
43 
44 Mod_t = OD_24h_day[:, :, t]
45 # 颜色
46 color_dict_O_D = {"color0": [234, 253, 196], # E8FFBD
47                           "color1": [251, 208, 84],  # FAD154
48                           "color2": [240, 168, 48],  # F0A82E
49                           "color3": [171, 84, 17],#AD5311
50                           "color4": [109, 0, 0]}#630300
51 # 颜色分段
52 node_seg = (np.array([0, 5, 20]) - min_v) / (max_v - min_v) * 255
53 node_seg = node_seg.astype(np.uint8)
54 
55 # 0--255
56 gray = matrix2gray(Mod_t)
57 
58 # gray2rgb保存成png图像
59 rgb_image = gray2rgb(gray, node_seg, color_dict_O_D)
60 
61 # 保存成彩色图片
62 plt.imshow(rgb_image)  # Needs to be in row, col order
63 filename = './rgb.png'
64 plt.axis('off')
65 plt.savefig(filename, dpi=600, transparent=True)
66 plt.show()

 

posted @ 2021-08-08 14:48  土博姜山山  阅读(86)  评论(0编辑  收藏  举报