本文介绍了使用numpy将图像转换为灰度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由矩阵 nxm 三元组(r,g,b)并且我想使用自己的函数将其转换为灰度。

I have an image represented by a numpy.array matrix nxm of triples (r,g,b) and I want to convert it into grayscale, , using my own function.

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

My attempts fail converting the matrix nxmx3 to a matrix of single values nxm, meaning that starting from an array [r,g,b] I get [gray, gray, gray] but I need gray.

ie初始颜色通道: [150 246 98]
转换为灰色后: [134 134 134]
我需要什么: 134

i.e. Initial colour channel : [150 246 98]. After converting to gray : [134 134 134]. What I need : 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


推荐答案

以下是工作代码:

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

这篇关于使用numpy将图像转换为灰度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 11:13