-1

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

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
McLovin
  • 555
  • 8
  • 20
  • 3
    Those appear to be the same blobs. Are you referring to the plot colors? OpenCV displays images. What you process is what you see. Matplot lib plots graphs, and uses [color maps](https://matplotlib.org/stable/tutorials/colors/colormaps.html) to change the color of the information you see. – stateMachine Aug 24 '22 at 03:01

2 Answers2

2

try it

plt.imshow(img,cmap='gray')
Verizz
  • 108
  • 1
  • 7
1

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30