简体   繁体   English

使用 numpy 将 BGR 图像转换为灰度图像

[英]Converting BGR image to grayscale using numpy

I have a small question hope you guys can help me.我有一个小问题希望你们能帮助我。 I know that to convert a RGB image to grayscale without using numpy, we can use:我知道要在不使用 numpy 的情况下将 RGB 图像转换为灰度图像,我们可以使用:

img = cv2.imread(input_file, cv2.IMREAD_COLOR)
r, g, b = img[:, :, 0], img[:, :, 1], img[:, :, 2]
img_gray = 0.2989 * r + 0.5870 * g + 0.1140 * b

Now I want to read the image by BGR scale then convert that BGR image to grayscale not using cv2.COLOR_BGR2GRAY , how can I do it with the similar code above?现在我想通过 BGR 比例读取图像,然后不使用cv2.COLOR_BGR2GRAY将该 BGR 图像转换为灰度,我该如何使用上面的类似代码来完成?

OpenCV will read the file into memory in BGR order, even though it is RGB on disk. OpenCV 将按 BGR 顺序将文件读入 memory,即使它是磁盘上的 RGB。 That's just the way it works.这就是它的工作方式。 So you need to change your second line to:因此,您需要将第二行更改为:

b, g, r = img[:, :, 0], img[:, :, 1], img[:, :, 2]

Then your third line will work correctly, although you may want to make unsigned 8-bit integers with:然后您的第三行将正常工作,尽管您可能希望使用以下方法生成无符号的 8 位整数:

img_gray = (0.2989 * r + 0.5870 * g + 0.1140 * b).astype(np.uint8)

By the way, you could actually do it faster with numpy like this:顺便说一句,你实际上可以像这样使用numpy更快地完成它:

import numpy as np

grey = np.dot(img[...,::-1], [0.299, 0.587, 0.114]).astype(np.uint8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM