Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

opencv

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

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):

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 ordering within the function automatically (from BGR to RGB) or the ordering has been BGR all along?

like image 612
Cypher Avatar asked Jun 21 '18 07:06

Cypher


People also ask

Does OpenCV use BGR or RGB?

OpenCV seems to have been built with the principle of maximum surprise in mind! And it all begins with the default BGR pixel format. It does not play well with libraries that use the standard RGB pixel format.

Why do we convert BGR to RGB in OpenCV?

OpenCV uses BGR image format. So, when we read an image using cv2. imread() it interprets in BGR format by default. We can use cvtColor() method to convert a BGR image to RGB and vice-versa.

Why does OpenCV use BGR?

OpenCV reads in images in BGR format (instead of RGB) because when OpenCV was first being developed, BGR color format was popular among camera manufacturers and image software providers.


1 Answers

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.

OpenCV imread, imwrite and imshow indeed all work with the BGR order, so there is no need to change the order when you read an image with cv2.imread and then want to show it with 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 imshow but read the image with OpenCV, you would need to convert from BGR to RGB.

like image 135
w-m Avatar answered Sep 30 '22 00:09

w-m