1

During my work on image processing I encounter a strange phenomenon that is not clear to me.

I have an image with dimensions of: (256, 256, 1) And when I display it with opencv using the following code:

cv2.imshow('image', image)
cv2.waitKey()

I get the following result:

image from opencv

In contrast, when I display it with matplotlib using the following code:

plt.imshow(image, cmap="gray")

I get the following result:

image output from matplotlib

The second result is the desired one as far as I'm concerned - my question is how to make the image like this (by code only and without the need to save to a file and load the image) and make it so that I get the same image in opencv as well.

I researched the issue but did not find a solution.

This reference helps me understand the reason in general but I'm still don't know how to show the image in opencv like matplotlib view in this case.

Thank you!

Daniel Agam
  • 209
  • 1
  • 9
  • 1
    matplotlib uses a color mapping. lookup the LUT for `cmap="gray"` and use that with `cv.applyColorMap` to achieve the same result – berak Aug 11 '22 at 12:49
  • I've also tried that: ```cv2.applyColorMap(image, cv2.COLORMAP_JET)``` and get this error: ```cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\colormap.cpp:736: error: (-5:Bad argument) cv::ColorMap only supports source images of type CV_8UC1 or CV_8UC3 in function 'cv::colormap::ColorMap::operator ()' ``` – Daniel Agam Aug 11 '22 at 12:51
  • has nothing to do with colormaps. has everything to do with value ranges and data types. explore the `image.max()` and `image.dtype` – Christoph Rackwitz Aug 11 '22 at 18:02
  • Thank you! If there is an example a little more specific to my case it could help me better understand how to use them – Daniel Agam Aug 11 '22 at 18:06
  • 1
    Does this answer your question? [Unclear difference in displaying the same image by opencv and matplotlib \[with example code & exported .npy file\]](https://stackoverflow.com/questions/73350318/unclear-difference-in-displaying-the-same-image-by-opencv-and-matplotlib-with-e) – Christoph Rackwitz Aug 14 '22 at 14:22
  • it's essentially the same question so there's no good reason to ask it twice. – Christoph Rackwitz Aug 14 '22 at 14:23

1 Answers1

1

I post the answer in this link, Also copy to here:

   int_image = image.astype(np.uint8)

    cv2.imshow('image', int_image)
    cv2.waitKey()
    plt.imshow(image, cmap="gray")
    plt.title("image")
    plt.show()

Now - The 2 plots are same.

Hope this helps more people in the future

Daniel Agam
  • 209
  • 1
  • 9