【python图像处理】彩色映射

38 篇文章 16 订阅
21 篇文章 3 订阅

在图像处理,尤其是医学图像处理的过程中,我们经常会遇到将灰度图映射成彩色图的情形,如将灰度图根据灰度的高低映射成彩虹色图。这个过程我们通常将之称为伪彩映射,伪彩映射的关键在于找到合适的彩色映射表,即colormap,也称color bar。

前段时间做了一个涉及到伪彩映射的项目,在找colormap的过程中,我发现Python的matplotlib模块中内嵌了一大批常用的colormaps,使用如下代码:

import numpy as np
import matplotlib.pyplot as plt

# Have colormaps separated into categories:
# http://matplotlib.org/examples/color/colormaps_reference.html

cmaps = [('Perceptually Uniform Sequential',
                            ['viridis', 'inferno', 'plasma', 'magma']),
         ('Sequential',     ['Blues', 'BuGn', 'BuPu',
                             'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
                             'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
                             'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
         ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool',
                             'copper', 'gist_heat', 'gray', 'hot',
                             'pink', 'spring', 'summer', 'winter']),
         ('Diverging',      ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr',
                             'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
                             'seismic']),
         ('Qualitative',    ['Accent', 'Dark2', 'Paired', 'Pastel1',
                             'Pastel2', 'Set1', 'Set2', 'Set3']),
         ('Miscellaneous',  ['gist_earth', 'terrain', 'ocean', 'gist_stern',
                             'brg', 'CMRmap', 'cubehelix',
                             'gnuplot', 'gnuplot2', 'gist_ncar',
                             'nipy_spectral', 'jet', 'rainbow',
                             'gist_rainbow', 'hsv', 'flag', 'prism'])]


nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps)
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))


def plot_color_gradients(cmap_category, cmap_list):
    fig, axes = plt.subplots(nrows=nrows)
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
    axes[0].set_title(cmap_category + ' colormaps', fontsize=14)

    for ax, name in zip(axes, cmap_list):
        ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3]/2.
        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axes:
        ax.set_axis_off()

for cmap_category, cmap_list in cmaps:
    plot_color_gradients(cmap_category, cmap_list)

plt.show()

我们可以得到matplotlib中内嵌的colormaps(应该是全部,但不是很确定):








如何获取colormap

如此众多的colormaps,应该能满足我们大部分的需求。当然,我们更关心的是如何将这些colormap中具体的数值导出来,这样使用起来会更加的灵活方便。当然,只要你想做到,是没有什么能够阻拦你的。

以获取最常用的jet映射表为例,我们可以使用如下代码分别获取整型和浮点型的jet map,并将其保存在txt文件中:

from matplotlib import cm

def get_jet():

    colormap_int = np.zeros((256, 3), np.uint8)
    colormap_float = np.zeros((256, 3), np.float)

    for i in range(0, 256, 1):
       colormap_float[i, 0] = cm.jet(i)[0]
       colormap_float[i, 1] = cm.jet(i)[1]
       colormap_float[i, 2] = cm.jet(i)[2]

       colormap_int[i, 0] = np.int_(np.round(cm.jet(i)[0] * 255.0))
       colormap_int[i, 1] = np.int_(np.round(cm.jet(i)[1] * 255.0))
       colormap_int[i, 2] = np.int_(np.round(cm.jet(i)[2] * 255.0))

    np.savetxt("jet_float.txt", colormap_float, fmt = "%f", delimiter = ' ', newline = '\n')
    np.savetxt("jet_int.txt", colormap_int, fmt = "%d", delimiter = ' ', newline = '\n')

    print colormap_int

    return

获取其他种类的colormap与之类似:

def get_spectral():

    colormap_int = np.zeros((256, 3), np.uint8)
    colormap_float = np.zeros((256, 3), np.float)

    for i in range(0, 256, 1):
       colormap_float[i, 0] = cm.spectral(i)[0]
       colormap_float[i, 1] = cm.spectral(i)[1]
       colormap_float[i, 2] = cm.spectral(i)[2]

       colormap_int[i, 0] = np.int_(np.round(cm.spectral(i)[0] * 255.0))
       colormap_int[i, 1] = np.int_(np.round(cm.spectral(i)[1] * 255.0))
       colormap_int[i, 2] = np.int_(np.round(cm.spectral(i)[2] * 255.0))

    np.savetxt("spectral_float.txt", colormap_float, fmt = "%f", delimiter = ' ', newline = '\n')
    np.savetxt("spectral_int.txt", colormap_int, fmt = "%d", delimiter = ' ', newline = '\n')

    print colormap_int

    return

当然,我们也可以根据需要对获得的colormap中的值进行调整。当我们获得心仪的colormap之后,伪彩映射就成了水到渠成的事情了。

下面是用Python写的伪彩映射的代码:

def gray2color(gray_array, color_map):
    
    rows, cols = gray_array.shape
    color_array = np.zeros((rows, cols, 3), np.uint8)

    for i in range(0, rows):
        for j in range(0, cols):
            color_array[i, j] = color_map[gray_array[i, j]]
    
    #color_image = Image.fromarray(color_array)

    return color_array

def test_gray2color():
    gray_image = Image.open('Image.png').convert("L")

    gray_array = np.array(gray_image)
    
    figure()
    subplot(211)
    plt.imshow(gray_array, cmap = 'gray')

    jet_map = np.loadtxt('E:\\Development\\Thermal\\ColorMaps\\jet_int.txt', dtype = np.int)
    color_jet = gray2color(gray_array, jet_map)
    subplot(212)
    plt.imshow(color_jet)

    show()

    return



这一篇先就介绍到这里,后面一篇将向大伙介绍如何使用python生成自定义的colormap。


  • 29
    点赞
  • 118
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: 将灰度图像转换为彩色图像需要使用颜色映射技术。在Python中,我们可以使用OpenCV库来实现这一过程。 首先,使用OpenCV库加载灰度图像并将其转换为彩色图像。可以使用cv2.imread()函数来读取灰度图像文件。将灰度图像传递给cv2.applyColorMap()函数,该函数将应用到灰度图像上的颜色映射。 我们可以使用以下代码将灰度图像转换为彩色图像: import cv2 # Load grayscale image gray_image = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE) # Apply color map to grayscale image colored_image = cv2.applyColorMap(gray_image, cv2.COLORMAP_JET) # Display the colored image cv2.imshow('Colored Image', colored_image) cv2.waitKey(0) cv2.destroyAllWindows() 在上面的代码中,cv2.applyColorMap()函数使用cv2.COLORMAP_JET参数将灰度图像转换为彩色图像。还有其他颜色映射选项,例如cv2.COLORMAP_AUTUMN、cv2.COLORMAP_BONE等等。 最后,在使用cv2.imshow()函数显示彩色图像之前,我们可以使用cv2.imwrite()函数将其保存为图像文件。 这就是将灰度图像转换为彩色图像的Python实现方法。 ### 回答2: 1. 理论基础 灰度图片每个像素点的灰度值表示了它的亮度。彩色图片则由红绿蓝三个通道组成,每个像素点的颜色由三个通道的数值组成。因此,将灰度图片转化为彩色图片,需要为每个像素点确定一种颜色,即分配三个通道的数值。 2. 方法一:基于色相、饱和度和明度的转换 由于灰度图像只有明度通道,没有饱和度和色相通道,因此可以使用一个常量色相和饱和度的值,将灰度值映射到明度通道。具体的映射函数如下: r = g = b = gray_value h, s, v = constant_hue, constant_saturation, gray_value r, g, b = hsv_to_rgb(h, s, v) 其中,gray_value表示像素点的灰度值,constant_hue和constant_saturation是色相和饱和度常量,hsv_to_rgb是将色相、饱和度、明度值转化为RGB颜色的函数。 通过这种方法,灰度图片可以变得具有颜色,但是颜色不够丰富,因为所有颜色都是由相同的色相和饱和度组成的。 3. 方法二:基于颜色映射表的转换 另一种方法是使用颜色映射表。颜色映射表是一种关联了灰度值和颜色的表格。可以使用以下步骤将灰度图形变为彩色图像: (1) 创建颜色映射表,将灰度值与颜色值关联起来。 (2) 将灰度图片中的每个像素点的灰度值与颜色映射表中的颜色值对应起来。 (3) 将彩色像素点替换灰度像素点,形成彩色图像。 颜色映射表可以使用手动设计或者基于数据训练的方法得到。基于数据的方法可以使用机器学习技术,如卷积神经网络(CNN),学习颜色映射表,并将其应用于灰度图像。这种方法可以得到更加准确和丰富的彩色图像。 综上所述,将灰度图像转换为彩色图像可以使用两种方法:基于色相、饱和度和明度的转换和基于颜色映射表的转换。每种方法都有其优缺点,需要根据需求来选择不同的方法。 ### 回答3: 在计算机图像处理中,有很多方法可以将灰度图像转换为彩色图像。其中一种常用的方法是使用伪彩色或颜色映射技术。本文将介绍如何使用Python实现将灰度图像转换为彩色图像的过程。 颜色映射技术是一种将灰度值映射到特定颜色的过程。为了将灰度图像变为彩色图像,我们需要定义一种映射方式,将每个灰度值映射到相应的RGB颜色值。 首先,我们需要导入Python中的PIL库,PIL是Python Imaging Library的缩写,它是Python中处理图像的常用库。 ``` from PIL import Image ``` 然后,我们需要打开一张灰度图像,使用PIL库中的Image模块来打开灰度图像。 ``` image_gray = Image.open("test_gray.jpg") ``` 为了获得彩色图像,我们需要创建一个与灰度图像相同大小的空白RGB图像,使用PIL库中的Image模块创建。 ``` image_color = Image.new("RGB", image_gray.size) ``` 接下来,我们需要设计一种映射方式。假设我们将灰度值为0映射为红色,灰度值为255映射为蓝色。这样就可以将每个像素的灰度值与RGB值进行映射。 ``` def color_map(gray_value): if gray_value < 128: return (255, 0, 0) # 映射为红色 else: return (0, 0, 255) # 映射为蓝色 ``` 最后,我们需要将映射后的RGB值在空白图像中填充到像素中,使用PIL库中的ImageDraw模块即可。 ``` from PIL import ImageDraw draw = ImageDraw.Draw(image_color) width, height = image_color.size for x in range(width): for y in range(height): gray_value = image_gray.getpixel((x, y)) color_value = color_map(gray_value) draw.point([x, y], color_value) ``` 最后,我们将生成的彩色图像保存到本地文件中。 ``` image_color.save("test_color.jpg") ``` 这样,我们就可以使用Python实现将灰度图像变为彩色图像的过程。相信读者在实践中一定能够更加深入地理解和掌握这种技术。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值