Issue
In continue to my previous question (that still not answered here)
Here is a simple code with some unsuccessful attempts and exported image.npy file that illustrates the problem:
'''
conda install -c conda-forge opencv
pip install numpy
pip install matplotlib
'''
import cv2
import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
image = np.load('image.npy') # Link to the file under this code block
print(image.shape) # output: (256, 256, 1)
print(image.dtype) # output: float64
# Unsuccessful attempts:
# image[np.where(image.max() != 255)] = 0
# max_img = image.max(axis=0)
# int_image = image.astype(int)
Link to download the image.npy file
And when I display it with opencv using the following code:
cv2.imshow('image', image)
cv2.waitKey()
I get an image like the following result:
In contrast, when I display it with matplotlib using the following code:
plt.imshow(image, cmap="gray")
(The 'cmap' parameter is not the issue here, It's only plot the image in Black & White)
I get an image the following result:
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!
Solution
You can use the following steps:
- load the data from the file
- truncate the data into 0-255 values, same type as original (float64)
- filtering using the
==
operator, which gives True/False values, then multiplying by 255 to get 0/255 integer values - use
cv2.imshow
combined withastype
to get the required type
import numpy as np
import cv2
if __name__ == '__main__':
data = np.load(r'image.npy')
data2 = np.trunc(data)
data3 = (data2 == 255) * 255
cv2.imshow('title', data3.astype('float32'))
cv2.waitKey(0)
Answered By - ishahak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.