from osgeo import gdal_array
import operator
from functools import reduce
import matplotlib.pyplot as plt
import cv2
src = 'phase2/20170218_UH_CASI_S4_NAD83.pix'
pix_arr = gdal_array.LoadFile(src)
print(pix_arr.shape)
NUMS = 65536
R = 21
G = 12
B = 7
(50, 1202, 4172)
img_arr = cv2.merge((pix_arr[R]/float(NUMS), pix_arr[G]/float(NUMS), pix_arr[B]/float(NUMS)))
print(img_arr.shape)
plt.figure(figsize=(18.03, 62.58))
plt.imshow(img_arr)
plt.show()
(1202, 4172, 3)
![效果不好,看不清](https://img-blog.csdnimg.cn/20200915214147789.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5Nzk4NDIz,size_16,color_FFFFFF,t_70#pic_center)
def histogram(ima, bins=list(range(0, NUMS))):
flat = ima.flat
n = gdal_array.numpy.searchsorted(gdal_array.numpy.sort(flat), bins)
n = gdal_array.numpy.concatenate([n, [len(flat)]])
hist = n[1:]-n[:-1]
return hist
def stretch(ima):
hist = histogram(ima)
lut = []
for bt in range(0, len(hist), NUMS):
step = reduce(operator.add, hist[bt:bt+NUMS]) / (NUMS-1)
n = 0
for i in range(NUMS):
lut.append(n / step)
n += hist[i+bt]
gdal_array.numpy.take(lut, ima, out=ima)
return ima
x = [i for i in range(NUMS)]
hist_r = histogram(pix_arr[R])
hist_g = histogram(pix_arr[G])
hist_b = histogram(pix_arr[B])
plt.figure(figsize=(5, 5))
plt.plot(x, hist_b, color='b')
plt.plot(x, hist_g, color='g')
plt.plot(x, hist_r, color='r')
plt.show()
![直方图中小值出现频率很高](https://img-blog.csdnimg.cn/20200915214200928.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5Nzk4NDIz,size_16,color_FFFFFF,t_70#pic_center)
stretched_r = stretch(pix_arr[R])
stretched_g = stretch(pix_arr[G])
stretched_b = stretch(pix_arr[B])
stretched_img = cv2.merge((stretched_r/float(NUMS), stretched_g/float(NUMS), stretched_b/float(NUMS)))
plt.figure(figsize=(18.03, 62.58))
plt.imshow(stretched_img)
plt.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200915214215599.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5Nzk4NDIz,size_16,color_FFFFFF,t_70#pic_center)
x = [i for i in range(NUMS)]
s_hist_r = histogram(stretched_r)
s_hist_g = histogram(stretched_g)
s_hist_b = histogram(stretched_b)
plt.figure(figsize=(5, 5))
plt.plot(x, s_hist_b, color='b')
plt.plot(x, s_hist_g, color='g')
plt.plot(x, s_hist_r, color='r')
plt.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200915214228593.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5Nzk4NDIz,size_16,color_FFFFFF,t_70#pic_center)