I want to load and display a.tif image in OpenCV Python. I load the image using cv2.imread('1_00001.tif') and then I display it using plt.imshow(img), but the image displayed is all black instead of what it was originally.
I can load and display the image correctly using PIL's Image.open() and matplotlib's mpimg.imread() so I think it is a cv2 specific problem. However, I have also successfully displayed.jpg and.tiff images using the same cv2.imread() function so it may also be a problem with specifically that.tif image.
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('1_00001.tif')
plt.imshow(img)
I expect an image of a circle with a few blurry lines inside, but the actual output is just a black image.
Check your image pixel values. plt.imshow
clips pixel values from 0-255, so I would guess that you're feeding in a PNG image with values greater than 255, and they're all getting clipped to 255 (black). Usually you'll want to normalize a TIFF or PNG image before feeding them to plt.imshow
, so it's interesting that you're not seeing this problem on some tiff images.
Im think, Some tiff tags not work properly with openCV try
img=cv2.imread("YOURPATH/opencv/samples/data/lena.jpg",cv2.IMREAD_COLOR)
cv2.imwrite("1_00001.tif",img)
img1=cv2.imread("1_00001.tif")
cv2
is a computer vision library designed to work with 8-bit rgb images. I suspect your .tif
is monochrome, possibly uint16
(common for microscopes) You will therefore need the cv2.IMREAD_UNCHANGED
flag if you wish to read the image with full fidelity.
import cv2
import numpy as np
img = cv2.imread('1_00001.tif', cv2.IMREAD_UNCHANGED)
print(f'dtype: {img.dtype}, shape: {img.shape}, min: {np.min(img)}, max: {np.max(img)}')
dtype: uint16, shape: (128, 128), min: 275, max: 5425
Without the cv2.IMREAD_UNCHANGED
flag cv2
will instead convert the image to 8-bit rgb:
dtype: uint8, shape: (128, 128, 3), min: 1, max: 21
matplotlib.imshow has different behavior depending on input. An array of size [M,N] will be rendered with a colormap scaled to the data. An array of size [M,N,3] will be rendered as RGB in range 0-255 for int or 0-1 for floats (no autoscaling,) Most likely your image contained low integer values. and therefore appeared black when plotted in maplotlib without autoscaling. This should not be a problem if you use the cv2.IMREAD_UNCHANGED
flag or plot one channel at a time.
You may also wish to look into other libraries designed spesifically for working with tiff files ie tifffile . However, I will note that cv2
is in my experience much faster than tifffile
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.