在 OPENCV PYTHON 中将 RGB 图像转换为灰度的简单算法!
我使用了注释,所以代码是不言自明的。但它运行迅速。
import cv2
import numpy as np
img1 = cv2.imread('opencvlogo.png')
row,col,ch = img1.shape
g = [ ] #the list in which we will stuff single grayscale pixel value inplace of 3 RBG values
#this function converts each RGB pixel value into single Grayscale pixel value and appends that value to list 'g'
def rgb2gray(Img):
global g
row,col,CHANNEL = Img.shape
for i in range(row) :
for j in range(col):
a = ( Img[i,j,0]*0.07 + Img[i,j,1]*0.72 + Img[i,j,2] *0.21 ) #the algorithm i used id , G = B*0.07 + G*0.72 + R* 0.21
#I found it online
g.append(a)
rgb2gray(img1) #convert the img1 into grayscale
gr = np.array(g) #convert the list 'g' containing grayscale pixel values into numpy array
cv2.imwrite("test1.png" , gr.reshape(row,col)) #save the image file as test1.jpg
所以我使用了这个图像文件......
我的程序生成以下灰度文件..
