如何手动将`BGR`图像转换为`灰度'(Python OpenCV)?

时间:2018-01-22 10:17:31

标签: python arrays image numpy opencv

我想手动将RGB图像转换为灰度图像。 我想知道的是如何获得RGB像素的红/蓝/绿值?

img = cv2.imread("images/penguins.jpg",0)
grey = img
for i in range(0,grey.shape[0]-1):
    for j in range(0,grey.shape[1]-1):
        img[i,j]=[ ]

我不知道下一步该怎么做

谢谢, 抱歉我的英文不好

1 个答案:

答案 0 :(得分:-1)

灰色公式:

  

灰色= 0.21 R + 0.72 G + 0.07 B

除了循环之外,更喜欢使用矩阵乘法。这是代码:

#!/usr/bin/python3
# 2018.01.22 18:55:20 CST
import cv2
import numpy as np
import time

## Read as BGR
img = cv2.imread("test.png")

## (1) Loop to calculate
ts = time.time()
H,W = img.shape[:2]
gray = np.zeros((H,W), np.uint8)
for i in range(H):
    for j in range(W):
        gray[i,j] = np.clip(0.07 * img[i,j,0]  + 0.72 * img[i,j,1] + 0.21 * img[i,j,2], 0, 255)

t = (time.time() -ts)
print("Loop: {:} ms".format(t*1000))

## (2) matrix multiply
ts = time.time()
w = np.array([[[ 0.07, 0.72,  0.21]]])
gray2 = cv2.convertScaleAbs(np.sum(img*w, axis=2))
t = (time.time() -ts)
print("Loop: {:} ms".format(t*1000))

## (3) display
cv2.imshow("img", img)
cv2.imshow("gray", gray)
cv2.imshow("gray2", gray2)
cv2.waitKey()

时间成本:

Loop: 6294.47340965271 ms
Loop: 14.13726806640625 ms

enter image description here