首页 > 解决方案 > 灰度图像python实现

问题描述

我尝试使用 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)

通常我想在输出图像的大小中找到

(533, 541)

标签: pythonimageopencvimage-processing

解决方案


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

gray = R * .299 + G * .587 + B * .114

方法 #1: apply_along_axis :

import cv2
import numpy as np

def grayscale(colors):
    r, g, b = colors
    return 0.299 * r + 0.587 * g + 0.114 * b

# Create image of size 100x100 of random pixels
# Convert to grayscale
image = np.random.randint(255, size=(100,100,3),dtype=np.uint8)
gray = np.apply_along_axis(grayscale, 2, image)

# Display
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.waitKey()

之前->之后

enter image description here enter image description here

方法#2: cv2.cvtColor

You could use OpenCV directly and read in the image as grayscale with cv2.imread by passing in the cv2.IMREAD_GRAYSCALE or 0 flag to load the image as grayscale.

image = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE) # OR
# image = cv2.imread('img.png', 0)

If you already have the image loaded, you can convert the RGB or BGR image to grayscale using cv2.cvtColor

image = cv2.imread('img.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

推荐阅读