我正在编写一个小程序来根据手动选择的点对齐图像,并将两个图像彼此相邻显示。为了使相似的栅格值具有相似的颜色,我想将颜色条拉伸(stretch)到两个图像的相同值。在 QGIS 中,可以使用累积计数削减,您可以在其中输入百分比以增强栅格的对比度。
我想使用 matplotlib 在我的单波段光栅图像中找到相应的(2% 和 98%)光栅值。然后我会使用最小的 2% 值和最大的 98% 值作为我的图像的 vmin 和 vmax。
我似乎无法在 matplotlib 中找到该函数,所以有人有建议吗?
最佳答案
你要找的是percentile功能。
而不是使用 matplotlib
,您可以使用一些数学来获得所需的结果。
您可以使用 percentile
找到上下百分位数。函数,并在下百分位数和上百分位数之间线性“拉伸(stretch)”像素范围。
这是一个代码示例:
import cv2
import numpy as np
img = cv2.imread('chelsea.png', cv2.IMREAD_GRAYSCALE) # Read input image for testing
min_percent = 2 # Low percentile
max_percent = 98 # High percentile
lo, hi = np.percentile(img, (min_percent, max_percent))
# Apply linear "stretch" - lo goes to 0, and hi goes to 1
res_img = (img.astype(float) - lo) / (hi-lo)
#Multiply by 255, clamp range to [0, 255] and convert to uint8
res_img = np.maximum(np.minimum(res_img*255, 255), 0).astype(np.uint8)
#Display images before and after linear "stretch":
cv2.imshow('img', img)
cv2.imshow('res_img', res_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:
输入图像:
输出图像:
关于python-3.x - 在 Matplotlib 中使用百分比累积计数增强对比度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60449340/