Python OpenCV - imshow 不需要从 BGR 转换为 RGB

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50963283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:39:46  来源:igfitidea点击:

Python OpenCV - imshow doesn't need convert from BGR to RGB

pythonopencv

提问by Cypher

As I'm lead to believe, OpenCV reads images in the BGR colorspace and we usually have to convert it back to RGB like this:

正如我所相信的,OpenCV 读取 BGR 色彩空间中的图像,我们通常必须像这样将其转换回 RGB:

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

But when I try to simply read an image and show it, the coloring seems fine (without the need to convert BGR to RGB):

但是当我尝试简单地读取图像并显示它时,着色似乎很好(无需将 BGR 转换为 RGB):

img_bgr = cv2.imread(image_path)
cv2.imshow('BGR Image',img_bgr)
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
cv2.imshow('RGB Image',img_rgb )
cv2.waitkey(0)

So is imshow()changing the colorspace within the function automatically (from BGR to RGB) or the colorspace has been BGR all along?

那么是imshow()自动更改函数内的色彩空间(从 BGR 到 RGB)还是色彩空间一直是 BGR?

回答by w-m

BGR and RGB are not color spaces, they are just conventions for the order of the different color channels. cv2.cvtColor(img, cv2.COLOR_BGR2RGB)doesn't do any computations (like a conversion to say HSV would), it just switches around the order. Any ordering would be valid - in reality, the three values (red, green and blue) are stacked to form one pixel. You can arrange them any way you like, as long as you tell the display what order you gave it.

BGR 和 RGB 不是颜色空间,它们只是不同颜色通道顺序的约定。cv2.cvtColor(img, cv2.COLOR_BGR2RGB)不做任何计算(就像 HSV 会做的转换一样),它只是切换顺序。任何排序都是有效的——实际上,三个值(红色、绿色和蓝色)堆叠在一起形成一个像素。您可以按您喜欢的任何方式排列它们,只要您告诉显示屏您给它的顺序即可。

OpenCV imread, imwriteand imshowindeed all work with the BGR order, so there is no need to change the order when you read an image with cv2.imreadand then want to show it with cv2.imshow.

OpenCV imreadimwrite并且imshow确实都与 BGR 顺序一起工作,因此当您使用 读取图像cv2.imread然后想用 显示它时,无需更改顺序cv2.imshow

While BGR is used consistently throughout OpenCV, most other image processing libraries use the RGB ordering. If you want to use matplotlib's imshowbut read the image with OpenCV, you would need to convert from BGR to RGB.

虽然 BGR 在整个 OpenCV 中一致使用,但大多数其他图像处理库使用 RGB 排序。如果您想使用matplotlib'simshow但使用 OpenCV 读取图像,则需要从 BGR 转换为 RGB。

回答by Satyam Singh

screen = cv2.cvtColor(screen, cv2.COLOR_RGB2BGR)

this one line code changes rgb to bgr

这一行代码将 rgb 更改为 bgr