简体   繁体   English

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

[英]Converting RGB Image to Grayscale by Manually in Python (without using external libraries)

I sum each pixel's Red, Green and Blue values and divide the sum by 3:我将每个像素的红色、绿色和蓝色值相加,然后将总和除以 3:

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

This is what I got:这就是我得到的:

My code is:我的代码是:

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

And this is the original image:这是原始图像:

Where am I doing wrong?我在哪里做错了?

Here is the documentation of the imshow method 这是 imshow 方法的文档

The input may either be actual RGB(A) data, or 2D scalar data, which will be rendered as a pseudocolor image.输入可以是实际的 RGB(A) 数据,也可以是 2D 标量数据,它们将被渲染为伪彩色图像。 Note: For actually displaying a grayscale image set up the color mapping using the parameters cmap='gray', vmin=0, vmax=255注意:为了实际显示灰度图像,使用参数 cmap='gray', vmin=0, vmax=255 设置颜色映射

To visualize the image in grayscale:要以灰度显示图像:

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

Concerning line:关于线路:

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

You are missing the three weighting coefficients for the R, G and B channels, as explained here on Wikipedia .您缺少 R、G 和 B 通道的三个加权系数,如Wikipedia 上所述。

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

to convert from rgb to grayscale use gray = 0.2126 * red + 0.7152 * green + 0.0722 * blue从 rgb 转换为灰度使用 gray = 0.2126 * red + 0.7152 * green + 0.0722 * blue

can you post the output你能发布 output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM