如何在灰度图像上应用渐变映射

时间:2017-06-02 14:41:38

标签: python numpy image-processing python-imaging-library pillow

我已经搜索过任何可能的解决方案,但所有答案都不是很清楚或不完整。

所以,说我把图片上传到了内存中:

image = Image.open('image.jpg')

如何将此渐变(#582f91应用于#00aeef):

enter image description here

到此图片:

enter image description here

所以它变成了这个:

enter image description here

非常感谢。

2 个答案:

答案 0 :(得分:0)

我之前使用cython脚本解决了这个问题(需要以高帧率更新)来实现这一目标。这里函数的输入cmap是矩阵的平顶数组,其中每一行对应一个颜色并且颜色为R G B值。我用一个网站来生成渐变虽然不记得是哪一个。图像被展平以获得速度,并在0到255个int值之间缩放。

为了能够导入和使用cython函数,一旦你使用pip安装了cython,就需要从命令行运行setup脚本。

pip install cython
pyhton setup.py build_ext --inplace

然后应该生成一个c文件和.so文件。

Cython代码:

import numpy as np
cimport numpy as np
cimport cython

DTYPE1 = np.float
ctypedef np.float_t DTYPE1_t

DTYPE2 = np.int
ctypedef np.int_t DTYPE2_t

@cython.boundscheck(False)
@cython.wraparound(False)

def mat_to_im(np.ndarray[DTYPE2_t, ndim=1] data, np.ndarray[DTYPE2_t, ndim=1] cmap):

    cdef int wid = data.size
    cdef int x, x1, y

    cdef np.ndarray[DTYPE2_t, ndim=1] im = np.zeros([wid*3], dtype=DTYPE2)

    for x in range(wid):

        x1 = x*3
        y = data[x]*3

        im[x1] = cmap[y]
        im[x1+1] = cmap[y+1]
        im[x1+2] = cmap[y+2]

return im

设置文件:

from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy

setup(
    name='image convert',
    version='1',
    description='color map images',
    author='scooper',
    install_requires=['numpy'],
    ext_modules=cythonize([
        Extension("image_convert", ["image_convert.pyx"], include_dirs=[numpy.get_include()])])
)

这应该有助于解决任何问题(我已从较大的代码文件中删除设置并且尚未对其进行测试):http://cython.readthedocs.io/en/latest/src/quickstart/build.html

答案 1 :(得分:0)

只需使用LinearSegmentedColormap

# make a cmap
mycm=matplotlib.colors.LinearSegmentedColormap.from_list('',['#582f91', '#00aeef'])

# apply on a canal
imgrad=mycm(image[:,:,0])