如何在matplotlib中平滑2D色彩映射

时间:2017-03-17 18:32:41

标签: python dictionary matplotlib 2d pixels

我的问题是,是否有任何方法可以使用matplotlib来平滑2D色彩图?我的代码:

def map():
    # setup parameters
    j = 0
    N = 719
    N2 = 35
    x = np.linspace(190, 800, N) 
    y = np.linspace(10, 360, N2) # (1,2,3), 1 - start Temp, 2- end temp + 10K, 3 - how many steps to reach it
    z = []
    A = np.zeros([35,719]) # [1 2], 1 - number of spectras, 2 - delta wavelength
    # run
    for i in range(10,360,10):
            Z = []
            file_no = (str(0) + str(i))[-3:]
            data = np.genfromtxt('C:\\Users\\micha_000\\Desktop\\Measure\\' + '160317_LaPONd_g500_%s_radio.txt'%file_no,skip_header = 12)
            for line in data:
                Z.append(line[1]-6000)
            A[j,:] = Z
            j = j+1
    X, Y = np.meshgrid(x,y)
    fig, ax = plt.subplots()
    cs = ax.contourf(X, Y, A, cmap=cm.viridis)
    norm = colors.Normalize(vmin = 0, vmax = 1)
    plt.xlabel('wavelength [nm]')
    plt.ylabel('temperature [K]')
    plt.title('LaPONd_g500')
    cbar = fig.colorbar(cs, norm = norm)
    plt.savefig('C:\\Users\\micha_000\\Desktop\\Measure\\LaPONd_g500_radio_map.png')
    plt.show()
    plt.close()

以下是我收到的一个例子: enter image description here

有没有什么方法可以通过平滑像素过渡使其看起来更好?

2 个答案:

答案 0 :(得分:4)

问题不在于调色板(在matplotlib中都是平滑的),但事实上你正在使用contourf(),它生成一组有限的countours,每个都有一个颜色,因此不是平滑的。默认值类似于10个计数器。

一个快速解决方案:通过指定级别来增加轮廓级别的数量(您还可以给出要包含哪些级别的数组):

cs = ax.contourf(X, Y, A, cmap=cm.viridis, levels=100)

更好的是,由于您的数据数据似乎已经在网格上(例如每个像素的X,Y,Z值),您应该使用pcolormesh(X,Y,A)而不是轮廓来绘制它。这将绘制完全连续的值,而不是步骤。

答案 1 :(得分:0)

将png作为数组打开,并使用平均值过滤器对其进行模糊处理。搜索卷积滤镜以了解更多信息。我刚刚使用了25像素的平方滤波器,但您可以使用高斯分布使其看起来更平滑..

import numpy as np
from scipy import ndimage, signal, misc

img = ndimage.imread('C:/.../Zrj50.png')

#I used msPaint to get coords... there's probably a better way
x0, y0, x1, y1 = 87,215,764,1270 #chart area (pixel coords)

#you could use a gaussian filter to get a rounder blur pattern
kernel = np.ones((5,5),)/25 #mean value convolution

#convolve roi with averaging filter
#red
img[x0:x1, y0:y1, 0] = signal.convolve2d(img[x0:x1, y0:y1, 0], kernel, mode='same', boundary='symm')
#green
img[x0:x1, y0:y1, 1] = signal.convolve2d(img[x0:x1, y0:y1, 1], kernel, mode='same', boundary='symm')
#blue
img[x0:x1, y0:y1, 2] = signal.convolve2d(img[x0:x1, y0:y1, 2], kernel, mode='same', boundary='symm')

#do it again for ledgend area
#...

misc.imsave('C:/.../Zrj50_blurred.png', img)

使用高斯相当容易:

#red
img[x0:x1, y0:y1, 0] = ndimage.gaussian_filter(img[x0:x1, y0:y1, 0], 4, mode='nearest')