图像读取方式(PIL,CV2,tiff,gdal)

dir1 = './coco/train/0003130704_L2_4300_4911_L1_6420_15895.tif'
dir2 = './coco/com/0003130704_L2_4300_4911_L1_6420_15895.tif'

tiff读取

img1 = tifffile.imread(dir1)  #  (1024,1024)
# print(img1)    # 0-32598
img1 = Image.fromarray(img1)   # 可正常显示
img2 = tifffile.imread(dir2)  #   (1024,1024,2)
# print(img2,np.uint8(img2))  # -548-60,0-253
img2 = Image.fromarray(np.uint8(img2))  # 显示与原图不同。然而,不转为np.uint8又转换失败。

PIL读取

img1=Image.open(dir1)     # 显示正常
img2=Image.open(dir2)   # 读取错误:PIL.UnidentifiedImageError: cannot identify image file

参考多个大佬博客发现,PIL只支持以下两种图像格式:
① 多通道8bit图像,如RGB
② 单通道高bit图像,如I16,I32,Float32图像
多通道多bit的tif图像不支持。

cv2读取

img1=cv2.imread(dir1,-1)   # -1:8bit原通道;2 原深度单通道;3:原深度三通道
# print(img1,img1.shape)          # (1024,1024)
img2=cv2.imread(dir2,-1)
# print(img2,img2.shape)          # (1024,1024)
img1=Image.fromarray(img1)  # 显示正常   2:0-32598,0-255  -1:
img2=Image.fromarray(img2)  # 显示正常

gdal读取

from osgeo import gdal  # 使用gdal包
data = gdal.Open(imgdir)
# 数据集的基本信息
print('影像的波段数: ', data.RasterCount)
w, h = data.RasterXSize, data.RasterYSize
print('影像的列,行数: {r}rows * {c}colums'.format(r=w, c=h))

# 读取第一个波段并将其转为array
band_1 = data.GetRasterBand(1)
x1=band_1 = band_1.ReadAsArray(0, 0, w, h)  # 行,列
print("1",band_1)
img1=Image.fromarray(band_1)

band_2 = data.GetRasterBand(2)
x2=band_2 = band_2.ReadAsArray(0, 0, w, h)  # 行,列
print("2",band_2)
img2=Image.fromarray(band_2)
img1.show()
img2.show()

你可能感兴趣的:(python,开发语言)