1

我已經搜索了任何可能的解決方案,但所有答案都不是很清晰或不完整。如何將梯度圖應用於灰度圖像

所以,說我已經上傳到內存中的圖像:

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

我如何應用此梯度(#582f91到#00aeef):

enter image description here

到該圖像:

enter image description here

所以我T成爲這樣的:提前

enter image description here

感謝。

回答

0

我用用Cython腳本之前解決了這個問題(如需要在高幀速率更新)來實現這一目標。這裏輸入cmap到功能是一個矩陣的平面陣列,其中每一行對應於一個顏色,並且對應於R G B值。我用一個網站來生成漸變,雖然不記得哪一個。圖像被平滑以獲得速度並在0到255的int值之間縮放。

爲了能夠導入和使用用Cython功能,您將需要從命令行運行安裝腳本,一旦你有安裝用Cython使用PIP即

pip install cython 
pyhton setup.py build_ext --inplace 

這則應該產生交流文件和.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

+0

所以基本上不得不使用映射單獨重新分配像素值。返回的圖像然後重新成形爲原始圖像尺寸。 – samocooper

+0

謝謝你。現在讓我試試看。 –

+0

恩,好的。我以前從未使用過Cython。你能給我一個快速指南,我如何使用你的功能? –

0

只需使用LinearSegmentedColormap

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

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