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

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

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

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

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


当年话下
浏览 560回答 3
3回答

SMILET

我接触到了一些数学方面的东西,它们很优雅:img = cv2.imread('images/lena.png', cv2.IMREAD_GRAYSCALE)# find some percentiles for grayscale range of src imagepercentiles = np.percentile(img, [0, 25, 75, 100])# define the same count of values to further interpolationtargets = np.geomspace(10, 255, 4)# use interpolation from percentiles to targets for blue and redb = 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 imageresult = cv2.merge([b, g, r])结果:您可以通过更改百分位数或目标空间点来调整亮度

慕工程0101907

删除色带不会实现您所描述的效果,因为您正在尝试对图像进行着色,而不是对其进行脱色。决定如何处理每个像素的像素级函数是解决此问题的好方法。from PIL import Imagedef 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) + alphaimg = Image.open('trees.jpg')img2 = img.copy()img2.putdata([pixop_redblue(pixel) for pixel in img.getdata()])img2.show()

FFIVE

以下是使用 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输入:import cv2import numpy as np# load image as grayscaleimg = 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 imagered = np.zeros((1, 1, 3), np.uint8)red[:] = (0,0,255)# create 1 pixel blue imageblue = np.zeros((1, 1, 3), np.uint8)blue[:] = (255,0,0)# append the two imageslut = np.concatenate((red, blue), axis=0)# resize lut to 256 valueslut = cv2.resize(lut, (1,256), interpolation=cv2.INTER_CUBIC)# apply lutresult = cv2.LUT(img, lut)# save resultcv2.imwrite('lena_red_blue_lut_mapped.png', result)# display resultcv2.imshow('RESULT', result)cv2.waitKey(0)cv2.destroyAllWindows()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python