34. 灰度处理

2019-11-12  本文已影响0人  十里江城

本文解释灰度处理的方法实现与算法的优化

1) 灰度处理的三种方法:

法1 灰度读取

import cv2 

img1 = cv2.imread('face.jpg', 1) 
img0 = cv2.imread('face.jpg', 0) 
print(img0.shape)
print(img1.shape)
cv2.imshow('src', img1)
cv2.imshow('dst1', img0)
cv2.waitKey(0)

维度变化与灰度图像显示如下:


image.png image.png

法2 颜色转换

import cv2

img = cv2.imread('face.jpg', 1)
dst = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('src', img)
cv2.imshow('dst2', dst)
cv2.waitKey(0)


结果如下:


image.png

法3 (B+G+R) / 3

import cv2
import numpy as np

img = cv2.imread('face.jpg', 1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
# R = G = B: gray
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('src', img)
cv2.imshow('dst3', dst)
cv2.waitKey(0)
        
        

结果如下:

image.png

法4 心理学公式 gray = r * 0.299 + g * 0.587 + b * 0.114

import cv2
import numpy as np
img = cv2.imread('face.jpg', 1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
# R = G = B: gray
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('src', img)
cv2.imshow('dst4', dst)
cv2.waitKey(0)

结果如下:


image.png

2) 灰度算法优化

# 灰度重要- 基础- 实时性要求
# 灰度图像的优化: 
# - 定点优于浮点
# - ”+-“优于于乘除
# - 移位优于乘除
# 对r*0.299 + g*0.578 + b*0.114

import cv2
import numpy as np 

img = cv2.imread('face.jpg', 1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]

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 = (b * 1 + g * 2 + r * 1) / 4
        # 定点-> 移位  "(g<<1)"
        gray = (r + (g << 1) + b ) >> 2
        dst[i, j] = np.uint8(gray)        
cv2.imshow('img', img)
cv2.imshow('dst', dst)
cv2.waitKey(0)

结果如下:


image.png
上一篇下一篇

猜你喜欢

热点阅读