将彩色RGB图像转为灰度图像,其中像素值的转换为
灰度值=0.2989 * R + 0.5870 * G + 0.1140 * B
原彩色RGB图像是三通道的,转换成单通道的灰度图像
自己写了一个Python程序,实现该转换任务:
# -*- coding: utf-8 -*-# 将RGB彩色图像转为灰度图像import cv2import numpylena = cv2.imread('F:\CVImages\lena.jpg')img = lenaheight = img.shape[0]width = img.shape[1]channels = img.shape[2]value = [0] * 3gray_img = numpy.zeros([height, width], numpy.uint8)for row in range(height):for column in range(width):for chan in range(channels):value[chan] = img[row, column, chan]R = value[2]G = value[1]B = value[0]# new_value = 0.2989 * R + 0.5870 * G + 0.1140 * Bnew_value = 0.2989 * R + 0.5870 * G + 0.1140 * B # 转为灰度像素gray_img[row, column] = new_valuecv2.imshow('original image', img)cv2.waitKey(0)cv2.imshow('gray image', gray_img)cv2.waitKey(0)cv2.imwrite('gray_lena.jpg', gray_img)