图像灰度处理四种基本算法及优化

文章目录

  • 算法一
    • 1. imread
  • 算法二
    • 2. cvtColor
  • 算法三
    • 3. RGB R=G=B (R+G+B)/3
  • 算法四
    • 4. gray = r * 0.299+g * 0.587+b * 0.114
  • 性能优化
    • 5. 算法优化

算法一

1. imread

#imread 
#方法1 imread
import cv2
img0 = cv2.imread('image0.jpg',0)
img1 = cv2.imread('image0.jpg',1)
print(img0.shape)
print(img1.shape)
cv2.imshow('src',img0)
cv2.waitkey(0)

算法二

2. cvtColor

#方法2 cvtColor
import cv2
img  = cv2.imread('img0.jpg',1)
dat = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#颜色空间转换
cv2.imshow('src',img0)
cv2.waitkey(0)

算法三

3. RGB R=G=B (R+G+B)/3

#方法3 RGB R=G=B (R+G+B)/3
import cv2
import numpy as np
img  = cv2.imread('img0.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
#RGB R=G=B (R+G+B)/3
dat = 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
        dat[i,j] = np.uint8(gray)
cv2.imshow('dat',dat)
cv2.waitkey(0)

算法四

4. gray = r * 0.299+g * 0.587+b * 0.114

#方法4 gray = r*0.299+g*0.587+b*0.114
import cv2
import numpy as np
img  = cv2.imread('img0.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
#RGB R=G=B (R+G+B)/3
dat = 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
        dat[i,j] = np.uint8(gray)
cv2.imshow('dat',dat)
cv2.waitkey(0)

性能优化

5. 算法优化

#算法优化
#定点-》浮点-》+-*/》
#gray = r*0.299+g*0.587+b*0.114
#100 1000 10000
import cv2
import numpy as np
img  = cv2.imread('img0.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
#RGB R=G=B (R+G+B)/3
dat = 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*1+g*2+b*1)/4
        gray = (r+(g<<1)+b)>>2
        dat[i,j] = np.uint8(gray)
cv2.imshow('dat',dat)
cv2.waitkey(0)


向阳花开,无畏生长,顽强拼搏,加油!!!-2020-9.3日

你可能感兴趣的:(算法,opencv,计算机视觉)