- 公式:gray = 0.299r + 0.587g + 0.114b
- 代码
import cv2
IMG_PATH = '.\img\\'
IMG_SAVE = '.\save\\'
# lena = cv2.imread('lena.png', -1)
lena = IMG_PATH + 'lena.png'
def channel_split_by_func(file=lena):
"""BGR转Gray,自己手写计算灰度图,需要注意数字格式转换"""
img = cv2.imread(file, -1)
b, g, r = cv2.split(img)
gray = (0.299*r + 0.587*g + 0.114*b).astype(np.uint8)
cv2.imshow('b', b)
cv2.imshow('g', g)
cv2.imshow('r', r)
cv2.imshow('ori', img)
cv2.imshow('gray', gray)
cv2.waitKey()
cv2.destroyAllWindows()
def bgr2gray():
"""BGR转Gray,直接调用cv2函数"""
color = cv2.imread(lena)
gray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)
cv2.imshow('color', color)
cv2.imshow('gray', gray)
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
channel_split_by_func()