简体   繁体   English

在Python中将RGB像素转换为灰度。 没有matplot或PIL

[英]Converting RGB pixels to Grayscale in Python. No matplot or PIL

I have a homework assignment I'm desperate to figure out. 我迫切需要解决一项家庭作业。 We've only spent two lecture days on opencv so I'm going in blind with this. 我们在opencv上只花了两天的演讲时间,所以我对此一无所知。

The assignment is to convert an RGB img to grayscale using the luminance formula 0.02126*R+0.7152*G+0.0722*B 该任务是使用亮度公式0.02126 * R + 0.7152 * G + 0.0722 * B将RGB img转换为灰度

So the type of each pixel should be the same as the original image. 因此,每个像素的类型应与原始图像相同。 We're not allowed to use matplot or PIL which is what I've seen a lot of trying to figure this thing out. 我们不允许使用matplot或PIL,这是我看到的很多尝试弄清楚的事情。

The code I have now outputs just a gray image. 我现在的代码仅输出灰色图像。 So instead of graySCALE, it's only gray. 因此,它不是灰色SCALE,而是灰色。 I'm so lost, please help. 我很迷路,请帮助。

import cv2
import numpy as np
def togray():
    img = cv2.imread("fruits.jpg")
    cv2.imshow('Original',img)
    height, width, channels = img.shape
    img2 = np.ndarray (shape=(height,width,))
    for i in range(height):
        for j in range(width):
            img2[i,j]=(0*0.2126 + 0.7152*1 + 0.0722*2)

    cv2.imshow('Grayscale',img2)
    cv2.waitKey(0)

togray()

Try doing img2 = 0.02126*img[:,:,2] + 0.7152*img[:, :,1] + 0.0722*img[:,:,0] 尝试做img2 = 0.02126*img[:,:,2] + 0.7152*img[:, :,1] + 0.0722*img[:,:,0]

The comment by Julien was wrong for two reasons: (i) The shape of an image is (m, n, 3) in opencv. 朱利安的评论是错误的,原因有两个:(i (m, n, 3)在opencv中(m, n, 3)图像的形状为(m, n, 3) This explains why that indexing gives you a smaller box. 这就解释了为什么索引为您提供了一个较小的框。 (ii) opencv channels are BGR, not RGB, so you need to swap the 2 and the 0 indices as I did here. (ii)opencv通道是BGR,而不是RGB,因此您需要像在这里那样交换2和0索引。 (The actual result should not change too much just considering how small the R and B terms contribute). (仅考虑R和B项的贡献,实际结果不应有太大变化)。

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

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