我正在尝试使用python skimage
在以gdal
打开的图像上以float32
类型的数组执行简单的对比度拉伸。我首先用以下方法计算百分位数:
p2, p98 = np.percentile(arrayF, (P1, P2))
然后尝试执行拉伸:
img_rescale = exposure.rescale_intensity(arrayF, in_range=(p2, p98))
使用GDAL写入.tiff
的返回图像仅包含“ 1”,没有数据。
问题的原因可能在数据范围内。对于此arrayF,它在0,0352989和1,03559之间。当拉伸值为0-255的数组时,脚本可以正常工作。
这里是功能:
def contrastStrecher(Raster1, p1, p2, OutDir, OutName1):
fileNameR1 = Raster1
P1 = p1
P2 =p2
outputPath = OutDir
outputName = OutName1
extension = os.path.splitext(fileNameR1)[1]
raster1 = gdal.Open(fileNameR1, GA_ReadOnly)
colsR1 = raster1.RasterXSize
rowsR1 = raster1.RasterYSize
bandsR1 = raster1.RasterCount
driverR1 = raster1.GetDriver().ShortName
geotransformR1 = raster1.GetGeoTransform()
proj1 = raster1.GetProjection()
bandF = raster1.GetRasterBand(1)
nodataF = bandF.GetNoDataValue()
newnodata = -1.
arrayF = bandF.ReadAsArray().astype("float32")
nodatamaskF = arrayF == nodataF
arrayF[nodatamaskF] = newnodata
p2, p98 = np.percentile(arrayF, (P1, P2))
img_rescale = exposure.rescale_intensity(arrayF, in_range=(p2, p98))
del arrayF
img_rescale[nodatamaskF] = newnodata
driver = gdal.GetDriverByName(driverR1)
outraster = driver.Create(outputPath + outputName + extension, colsR1, rowsR1, 1, gdal.GDT_Float32)
outraster.SetGeoTransform(geotransformR1)
outraster.SetProjection(proj1)
outband = outraster.GetRasterBand(1)
outband.WriteArray(img_rescale)
del img_rescale
outband.FlushCache()
outband.SetNoDataValue(newnodata)
del outraster, outband
我发现newnodata
的值会干扰计算。以前我给它分配了-9999.9
的作用,结果如上所述。现在使用-1.
似乎函数可以输出正确的结果,但是我不确定,因为nodata
或newnodata
值不应包含在计算中。
存在一个称为百分位数拉伸的概念,其中所有通过指定的底部和顶部百分位数的东西都将分别映射到0和255,并且将两者之间的所有像素值都进行拉伸以改善对比度。我不确定您想要的是什么,但是我相信这是在此示例中使用可下载的代码完成的:https://scikit-image.org/docs/0.9.x/auto_examples/plot_equalize.html但是您可能不希望某些图像映射到0,255,所以也许可以使用argparse()
来输入这些参数作为参数,或者使用np.amax
和np.amin
指定截止点,尝试将图像写入文件并构建适合您需求的算法。