0

OpenCV and matplotlib sometimes give the same output, sometimes they give different output, when displaying an image with their respective imshow functions. What is the difference between them?

For example it gives the same output for this code:

img = cv2.imread("sudoku.jpg")
plt.figure()
plt.imshow(img, cmap="gray")
plt.axis("off")
plt.title("orjinal")
plt.show()

cv2.imshow("orjinal",img)

matplotlib: enter image description here OpenCV: enter image description here

It gives different output for this code:

laplacian = cv2.Laplacian(img,ddepth=cv2.CV_16S)
plt.figure()
plt.imshow(laplacian, cmap="gray")
plt.axis("off")
plt.title("laplacian")
plt.show()

cv2.imshow("laplacian",laplacian)

matplotlib: enter image description here OpenCV: enter image description here

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • 2
    You haven't shown the 2 images, but one common issue is that matplotlib uses RGB while opencv uses BGR: [Difference between plt.show and cv2.imshow?](https://stackoverflow.com/a/38907583/13138364) – tdy Mar 17 '22 at 19:42
  • then if we use cv2.COLOR_BGR2RGB will it work the same – Muhammed Atmaca Mar 17 '22 at 20:04

1 Answers1

1

The main difference, and the one that causes the difference you showed, is that matplotlib will, by default, scale the image so that its minimum value is black and its maximum value is white. OpenCV always shows images according to their data type, for example for a uint8 image, 0 is black and 255 is white. In your case, you have a signed 16-bit image, which has -32768 as black and 32767 as white. Your pixel values occupy a way smaller range, and so all appear as the same middle-gray color.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120