import cv2 import gdal import numpy as np #计算2% 98%处值作为最小 最大值 def minmaximg(width,heigh,img): img_fla = img.flatten() #展成一维数组 #img_fla = np.sort(img_fla) #排序 len=img.max() print('max=%d' % len) num=np.zeros(len+1,dtype=np.int32) print('size=%d'%np.size(img_fla)) for i in np.arange(np.size(img_fla)): num[img_fla[i]]=num[img_fla[i]]+1 #print('img_fla= %d,%d'%(i,img_fla[i])) #print('num %d,%d' % (i, num[img_fla[i]])) p=0 min=0 max=0 print(np.sum(num)) for j in np.arange(len+1): p = num[j] / (width*heigh) + p #print('/n',num[j]) if p>=0.02: min=j break p=0 for j in np.arange(len+1): p = num[j] / (width * heigh) + p # print('/n,%', num[j]) # print('/n,%', p) # print('/n,%', j) if p >= 0.98: max = j break return min,max def linearstretching(img,min,max): img=np.where(img > min, img, min) img=np.where(img < max, img, max) img = (img - min) / (max - min) * 255 return img def readTif(fileName): dataset = gdal.Open(fileName) if dataset == None: print(fileName+"掩膜失败,文件无法打开") return im_width = dataset.RasterXSize #栅格矩阵的列数 im_height = dataset.RasterYSize #栅格矩阵的行数 im_bands = dataset.RasterCount #波段数 im_data = dataset.ReadAsArray(0,0,im_width,im_height)#获取数据 im_geotrans = dataset.GetGeoTransform()#获取仿射矩阵信息 im_proj = dataset.GetProjection()#获取投影信息 im_blueBand = im_data[0,0:im_height,0:im_width]#获取蓝波段 im_greenBand = im_data[1,0:im_height,0:im_width]#获取绿波段 im_redBand = im_data[2,0:im_height,0:im_width]#获取红波段 im_nirBand = im_data[3,0:im_height,0:im_width]#获取近红外波段 return im_width,im_height,im_bands,im_blueBand,im_greenBand,im_redBand,im_nirBand fileName='E:\SHIP\GF1_PMS1_E107.5_N10.4_20150313_L1A0000693445-MSS1.tiff' im_width,im_height,im_bands,im_blueBand,im_greenBand,im_redBand,im_nirBand = \ readTif(fileName) bmin,bmax = minmaximg(im_width,im_height,im_blueBand) gmin,gmax = minmaximg(im_width,im_height,im_greenBand) rmin,rmax = minmaximg(im_width,im_height,im_redBand) im_blueBand=linearstretching(im_blueBand,bmin,bmax) im_greenBand=linearstretching(im_greenBand,gmin,gmax) im_redBand=linearstretching(im_redBand,rmin,rmax) img=cv2.merge([im_blueBand,im_greenBand,im_redBand]) cv2.imwrite('GF1_PMS1_E107.5_N10.4_20150313_L1A0000693445-MSS1.jpg',img)