# 一、图片灰度算法

### 灰度算法简介

#### 一.opencv灰度实现

• 读取时实现:
import cv2
# picture type 0:gray   1 color
cv2.imshow("image", img)
cv2.waitKey(0)


• 实时转为灰度
import cv2
# 颜色空间转换的,将bgr转换为灰度图片
dst = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
cv2.imshow("dst", dst)
cv2.waitKey(0)


#### 二.灰度算法手动实现

• 灰度算法著名的心理学公式:

Gray = R0.299 + G0.587 + B*0.114

import cv2
import numpy as np
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
mode = imgInfo[2]
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*0.114 + g*0.587 + r*0.299
dst[i, j] = np.uint8(gray)
cv2.imshow("dst", dst)
cv2.waitKey(0)


• 非心理学公式:
import cv2
import numpy as np
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
mode = imgInfo[2]
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 #(r+g+b)/3得到
dst[i, j] = np.uint8(gray)
cv2.imshow("dst", dst)
cv2.waitKey(0)


03-30
07-12 710

08-26 1万+
06-18 2万+
07-25 500
04-04 337
05-31 461