灰度图像python实现

灰度图像python实现,python,image,opencv,image-processing,Python,Image,Opencv,Image Processing,我尝试使用python作为函数将RGB图像转换为灰度,但问题是我给了它一个有高度、宽度和通道的RGB图像,但在代码之后,我应该有一个只有高度和宽度的图像,但它给了我一个有高度、宽度和通道的图像为什么 def RGBtoGRAY(img): height, width, channels = img.shape grayimg = img for i in range(height): for j in range(width): g

我尝试使用python作为函数将RGB图像转换为灰度,但问题是我给了它一个有高度、宽度和通道的RGB图像,但在代码之后,我应该有一个只有高度和宽度的图像,但它给了我一个有高度、宽度和通道的图像为什么

def RGBtoGRAY(img):
    height, width, channels = img.shape
    grayimg = img
    for i in range(height):
        for j in range(width):
            grayimg[i,j] = 0.3 * image[i,j][0] + 0.59 * image[i,j][1] +  0.11 * image[i,j][2]
    return grayimg
输入图像的大小为

image.shape 
(533, 541, 3)
grayimage.shape 
(533, 541, 3)
输出图像的大小为

image.shape 
(533, 541, 3)
grayimage.shape 
(533, 541, 3)
通常我想找出输出图像的大小

(533, 541)

执行图像处理时,应避免使用
for
循环,因为它非常慢。相反,您可以使用Numpy,它针对向量操作进行了高度优化。使用:

方法#1:

->

方法#2:

您可以直接使用OpenCV并通过传入
cv2.IMREAD\u grayscale
0
标志以灰度形式加载图像,从而将图像作为灰度进行读取

image = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE) # OR
# image = cv2.imread('img.png', 0)
如果已加载图像,则可以使用将RGB或BGR图像转换为灰度


假设您使用的是for循环,因为您打算“手动”解决它(如C代码),那么您的实现中存在许多问题:

  • Python中的赋值
    grayimg=img
    不会创建
    img
    的副本(结果是
    grayimg
    引用
    img
    )。
    您打算使用:
    grayimg=img.copy()
  • img
    3个维度,因此当使用
    grayimg=img
    时,
    grayimg
    也有3个维度。
    您需要创建具有二维的
    grayimg

    创建
    grayimg
    并初始化为零的示例:

    grayimg = np.zeros((height, width), img.dtype)
    
  • 在for循环中,您使用的是
    image
    而不是
    img

以下是经更正的
RGBtoGRAY

def RGBtoGRAY(img):
    height, width, channels = img.shape
    #grayimg = img
    # Create height x width array with same type of img, and initialize with zeros.
    grayimg = np.zeros((height, width), img.dtype)
    for i in range(height):
        for j in range(width):
            grayimg[i,j] = 0.3 * img[i,j][0] + 0.59 * img[i,j][1] +  0.11 * img[i,j][2]
    return grayimg

grayimg=img
未创建新图像。它只是获取输入的引用。您希望创建具有相同尺寸的新图像。例如,是否有帮助?
def RGBtoGRAY(img):
    height, width, channels = img.shape
    #grayimg = img
    # Create height x width array with same type of img, and initialize with zeros.
    grayimg = np.zeros((height, width), img.dtype)
    for i in range(height):
        for j in range(width):
            grayimg[i,j] = 0.3 * img[i,j][0] + 0.59 * img[i,j][1] +  0.11 * img[i,j][2]
    return grayimg