首页 > 解决方案 > 使用 numpy 将图像转换为灰度

问题描述

我有一个由三元组numpy.array矩阵nxm(r,g,b)表示的图像,我想使用我自己的函数将其转换为灰度。

我的尝试将矩阵nxmx3转换为单值矩阵nxm失败,这意味着从[r,g,b]我得到[gray, gray, gray]但我需要的数组开始gray

即初始颜色通道:[150 246 98]。转换为灰色后:[134 134 134]。我需要的 : 134

我怎样才能做到这一点?

我的代码:

def grayConversion(image):
    height, width, channel = image.shape
    for i in range(0, height):
        for j in range(0, width):
            blueComponent = image[i][j][0]
            greenComponent = image[i][j][1]
            redComponent = image[i][j][2]
            grayValue = 0.07 * blueComponent + 0.72 * greenComponent + 0.21 * redComponent
            image[i][j] = grayValue
    cv2.imshow("GrayScale",image)
    return image

标签: pythonarraysnumpyopencv

解决方案


这是一个工作代码:

def grayConversion(image):
    grayValue = 0.07 * image[:,:,2] + 0.72 * image[:,:,1] + 0.21 * image[:,:,0]
    gray_img = grayValue.astype(np.uint8)
    return gray_img

orig = cv2.imread(r'C:\Users\Jackson\Desktop\drum.png', 1)
g = grayConversion(orig)

cv2.imshow("Original", orig)
cv2.imshow("GrayScale", g)
cv2.waitKey(0)
cv2.destroyAllWindows()

推荐阅读