本篇本章介绍4种方法来进行图片的灰度处理。
方法一,利用OpenCV种的imread
import cv2
img0 = cv2.imread('2.jpg',0)
img1 = cv2.imread('2.jpg',1)
print(img0.shape) #没有维度
print(img1.shape)
cv2.imshow('src',img0)
cv2.waitKey(0)
打印结果
(448, 400)
(448, 400, 3)
这里可以发现,灰度处理的图片没有维度
方法二,利用OpenCV种的cvtColor 颜色空间转换
import cv2
img = cv2.imread('2.jpg',1)
#颜色空间转换 1 数据 2 BGR
dst = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('dst',dst)
cv2.waitKey(0)
方法3 用RGB 均值来做灰度
import cv2
import numpy as np
img = cv2.imread('2.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
# RGB R=G=B = gray (R+G+B)/3 求RGB的平均值
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,height):
for j in range(0,width):
(b,g,r) = img[i,j]
gray = (int(b)+int(g)+int(r))/3
dst[i,j] = np.uint8(gray)
cv2.imshow('dst',dst)
cv2.waitKey(0)
方法4 gray = r0.299+g0.587+b*0.114 利用这个公式来做
import cv2
import numpy as np
img = cv2.imread('2.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
# RGB R=G=B = gray (R+G+B)/3
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,height):
for j in range(0,width):
(b,g,r) = img[i,j]
b = int(b)
g = int(g)
r = int(r)
gray = r*0.299+g*0.587+b*0.114
dst[i,j] = np.uint8(gray)
cv2.imshow('dst',dst)
cv2.waitKey(0)