在Python中手动将RGB图像转换为灰度(不使用外部库)

2024-09-28 20:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我将每个像素的红色、绿色和蓝色值相加,并将总和除以3:

gray_image = (image[:,:,0] + image[:,:,1] + image[:,:,2]) / 3

这就是我得到的:

我的代码是:

import matplotlib.image as pltim
import matplotlib.pyplot as plt
import numpy as np

def rgb2gray(image):
    imageHeight = len(image)
    imageWidth = len(image[0])
    grayImage = np.empty([imageHeight, imageWidth], dtype=np.uint8)

    for i in range(imageHeight):
        for j in range(imageWidth):
            grayImage[i][j] = int((image[i][j][0] + image[i][j][1] + image[i][j][2]) / 3)
    return grayImage


class RetargetedImage:
    imageDirectory = ""
    image = None
    grayImage = None

    def __init__(self, imageDirectory):
        self.imageDirectory = imageDirectory
        self.image = pltim.imread(self.imageDirectory)
        self.grayImage = rgb2gray(self.image)

    def showOriginalImage(self):
        plt.imshow(self.image)
        plt.show()

    def showGrayImage(self):
        plt.imshow(self.grayImage)
        plt.show()


example1 = RetargetedImage("treeMedium.jpg")
example1.showGrayImage()

这是原始图像:

我哪里做错了


Tags: imageimportselflenmatplotlibdefasnp
2条回答

Here is the documentation of the imshow method

The input may either be actual RGB(A) data, or 2D scalar data, which will be rendered as a pseudocolor image. Note: For actually displaying a grayscale image set up the color mapping using the parameters cmap='gray', vmin=0, vmax=255

要以灰度显示图像,请执行以下操作:

def showGrayImage(self):
    plt.imshow(self.grayImage, cmap='gray', vmin=0, vmax=255)
    plt.show()

关于行:

grayImage[i][j] = int((image[i][j][0] + image[i][j][1] + image[i][j][2]) / 3)

您缺少R、G和B通道的三个权重系数,如here on Wikipedia所述

Y ← 0.299⋅R+0.587⋅G+0.114⋅B

要将rgb转换为灰度,请使用 灰色=0.2126*红色+0.7152*绿色+0.0722*蓝色

你能发布输出吗

for i in range(imageHeight):
        for j in range(imageWidth):
            grayImage[i][j] = int(image[i][j][0]*0.2126 + image[i][j][1]*0.7152 + image[i][j][2] * 0.0722)
    return grayImage

相关问题 更多 >