将灰色图像转换为蓝色和红色图像

时间:2020-09-25 21:44:36

标签: python opencv

我想知道如何拍摄灰度图像,然后将黑色像素变成红色,白色像素变成蓝色?所有其他看起来为灰色的像素(不完全是黑色或白色)应该是从红色到蓝色的过渡。

我尝试了以下方法:拍摄灰度图像,将其转换为RGB,然后尝试去除绿色通道。但是图像看起来只是粉红色的:

im = cv2.imread('grey_img.jpg')
im[:,:,1] = 0

那么如何将灰色图像变成蓝色到红色图像?

3 个答案:

答案 0 :(得分:4)

我学过一些数学方面的东西,它们很优雅:

img = cv2.imread('images/lena.png', cv2.IMREAD_GRAYSCALE)

# find some percentiles for grayscale range of src image
percentiles = np.percentile(img, [0, 25, 75, 100])

# define the same count of values to further interpolation
targets = np.geomspace(10, 255, 4)

# use interpolation from percentiles to targets for blue and red
b = np.interp(img, percentiles, targets).astype(np.uint8)
g = np.zeros_like(img)
r = np.interp(img, percentiles, targets[::-1]).astype(np.uint8)

# merge channels to BGR image
result = cv2.merge([b, g, r])

结果:

logspace interpolation result

您可以通过更改百分位数或目标空间点来调整亮度

答案 1 :(得分:2)

删除色带将无法完成您所描述的内容,因为您要使图像着色而不是使图像褪色。一个像素级函数来决定如何处理每个像素是解决此问题的好方法。

enter image description here

from PIL import Image

def pixop_redblue(pixel):
    pixel, alpha = pixel[:3], pixel[3:]
    grey = sum(pixel) // len(pixel)
    redvalue = 255 - grey  # "darkness"
    bluevalue = grey  # "brightness"
    return (redvalue, 0, bluevalue) + alpha


img = Image.open('trees.jpg')
img2 = img.copy()
img2.putdata([pixop_redblue(pixel) for pixel in img.getdata()])
img2.show()

enter image description here

答案 2 :(得分:2)

这是一种使用Python / OpenCV将渐变颜色应用于灰度图像的方法。

 - Load the grayscale image

 - Convert it to 3 equal channels (only if image is 1 channel grayscale already)

 - Create a 1 pixel red image

 - Create a 1 pixel blue image

 - Concatenate the two

 - Resize linearly to 256 pixels as a Lookup Table (LUT)

 - Apply the LUT

 - Save the result

输入:

enter image description here

import cv2
import numpy as np

# load image as grayscale
img = cv2.imread('lena_gray.png', cv2.IMREAD_GRAYSCALE)

# convert to 3 equal channels (only if img is already 1 channel grayscale)
img = cv2.merge((img, img, img))

# create 1 pixel red image
red = np.zeros((1, 1, 3), np.uint8)
red[:] = (0,0,255)

# create 1 pixel blue image
blue = np.zeros((1, 1, 3), np.uint8)
blue[:] = (255,0,0)

# append the two images
lut = np.concatenate((red, blue), axis=0)

# resize lut to 256 values
lut = cv2.resize(lut, (1,256), interpolation=cv2.INTER_CUBIC)

# apply lut
result = cv2.LUT(img, lut)

# save result
cv2.imwrite('lena_red_blue_lut_mapped.png', result)

# display result
cv2.imshow('RESULT', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here