Home > database >  Why does Matplotlib's `imshow` result is not matching with cv2's `imshow`?
Why does Matplotlib's `imshow` result is not matching with cv2's `imshow`?

Time:08-24

I am trying to convert an Image to black and white using opencv-python. I have tried the following program.

import cv2
import matplotlib.pyplot as plt
img = cv2.imread("path/to/image.jpg", cv2.IMREAD_GRAYSCALE)

(thresh, img) = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

cv2.imshow("Image",img)
cv2.waitKey(0) & 0xFF 
cv2.destroyAllwindows()

Input Image is :

Input Image

This program results in an expected output as shown below.

cv2.imshow output

However, if I use the matplotlib's imshow to plot the black and white image, the result is different.

Program:

import cv2
import matplotlib.pyplot as plt
img = cv2.imread("path/to/image.jpg", cv2.IMREAD_GRAYSCALE)

(thresh, img) = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
plt.imshow(img)
plt.show()

Output:

plt.imshow output

Is there a reason why there is a difference between these two outputs ?

Python & Modules' version I am using :

python 3.8.2

matplotlib==3.5.1

opencv-python==4.6.0.66

OS : macOS Monterey version 12.4

CodePudding user response:

try it

plt.imshow(img,cmap='gray')

CodePudding user response:

When you display a simple 2D array with matplotlib, it uses the values as indexes into a color map. You can provide your own color map, if you want.

  • Related