opencv学习11——灰度图像读取

一、灰度图像读取,4中实现方式

1.cv2.imread(image,0),在图像读取方法中使用0或者cv2.IMREAD_GRAYSCALE读取灰度图

2. cv2.cvtColor(image,cv2.COLOR_BGR2GRAY),在图像以BGR形式读取完毕后,使用图像色彩转换的方法cvt将图像有BGR转换为灰度图

3.使用代码将BGR格式图像转换为灰度图,转换公式:gray = (b + r + g)/3

4.代码转换,转换公式:gray = r*1 + g*2 + b*1

二、代码实现

1.

import cv2

img2 = cv2.imread('image01.jpg',cv2.IMREAD_GRAYSCALE)
cv2.imshow('',img2)
cv2.waitKey(0)

2.

import cv2

img = cv2.imread('image01.jpg',1)
dst = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

3.

# gray = (b + r + g)/3
import cv2
import numpy as np

img = cv2.imread('image01.jpg',1)
imgHeight,imgWidth,imgDeep = img.shape

dst = np.zeros((imgHeight,imgWidth,3),np.uint8)

for i in range(imgHeight):
    for j in range(imgWidth):
        (b,g,r) = img[i,j]
        gray = (int(b)+int(g)+int(r))/3
        dst[i,j] = np.uint8(gray)

cv2.imshow('',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

4.

#定点运算,gray = r*1 + g*2 + b*1
import cv2
import numpy as np

img = cv2.imread('image01.jpg',1)
imgHeight,imgWidth,imgDeep = img.shape

dst = np.zeros((imgHeight,imgWidth,3),np.uint8)

for i in range(imgHeight):
    for j in range(imgWidth):
        (b,g,r) = img[i,j]
        gray = (int(b)*1+int(g)*1+int(r)*1)/3
        dst[i,j] = np.uint8(gray)

# # 位移计算
# for i in range(imgHeight):
#     for j in range(imgWidth):
#         (b,g,r) = img[i,j]
#         gray = (int(b)*1+(int(g)<<1)+int(r)*1)>>2
#         dst[i,j] = np.uint8(gray)

cv2.imshow('',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/nominior/article/details/82832314