赋予灰度图像颜色

时间:2019-09-27 13:50:42

标签: python numpy opencv image-processing numpy-ndarray

edited image after assignment statement

我想为黑白图像添加颜色,我认为更改像素的值应该可以。

for rows in rgb:
    for e in rows:
        for i in range(len(e)):
            max_val = e.max()
            min_val = e.min()
            if e[i] == max_val:
                e[i] * 2.5
            if e[i] == min_val:
                e[i] * 0.75
            else:
                e[i] * 1.5

该代码不会返回错误,但也不会更改值。我希望数字被同一数组相乘并重新分配

2 个答案:

答案 0 :(得分:0)

我们可以手动使用Numpy的broadcasting功能,而不必手动遍历运行效率低的O(n^3)的每个像素。


我们首先使用cv2.split()将灰度图像分成单独的BGR个通道。这将为我们提供单独的BGR通道,每个通道都具有相同的值。接下来,我们使用np.multiply()将每个通道与标量值相乘。最后,我们使用cv2.merge()将每个通道合并为彩色图像,以创建单个多通道阵列


之前

>>> print(before.shape)
(331, 500, 3)

您可能想知道为什么图像尽管明显是灰度的却具有三个通道。嗯,是因为每个频道都有相同的值,范围从[0 ... 255]

之后

>>> print(after.shape)
(331, 500, 3)

同样,频道数相同,但是我们修改了每个频道

TLDR:要为黑白图像添加颜色,我们必须提取每个单独的BGR通道,修改每个通道,然后重建图像

import cv2
import numpy as np

before = cv2.imread('2.png')
b, g, r = cv2.split(before)

np.multiply(b, 1.5, out=b, casting="unsafe")
np.multiply(g, .75, out=g, casting="unsafe")
np.multiply(r, 1.25, out=r, casting="unsafe")

after = cv2.merge([b, g, r])

cv2.imshow('before', before)
cv2.imshow('after', after)
cv2.waitKey()

答案 1 :(得分:0)

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

Load the grayscale image

Convert it to 3 equal channels

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


输入:

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
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

如果需要,可以将要形成彩虹LUT的许多不同颜色的像素串联起来。

相关问题