When using openCV to load an image, the color information is stored in the order of Blue-Green-Red instead of the currently more popular scheme RGB.
import cv2 image = cv2.imread(args["image"]) cv2.imshow("Image" , image) cv2.waitKey(0)
This reads in and displays the correct image file. An alternative way to do this using matplotlib is as follows.
import matplotlib.image as mpimg image = mpimg.imread(args["image"]) plt.axis("off") plt.imshow(image) # plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.show()
However, if we read in the image file through cv2 and display it with matplotlib or vice versa, the image will not be displayed correctly, since the R and B channels are flipped (see above link for an example image). Luckily, cv2 has a built-in way to correct this.
import cv2 import matplotlib.image as mpimg image = cv.imread(args["image"]) plt.axis("off") plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.show()
Alternatively, we can hack this by swapping the B and R channel since it is the third dimension of the image.
image = image[:, :, ::-1] # or image = image[:, :, (2, 1, 0)] plt.imshow(img)
According to the following post, BGR was introduced to the openCV in a time when BGR was the most popular format, and it got stuck. It is very similar to the funny story why US railway gauge is 4’8.5″.