module demonstrating kernel density estimation in case of a 2d image
More...
module demonstrating kernel density estimation in case of a 2d image
Overview
This application computes histogram of an input 2d image using a classical histogram algorithm. A second computation is then proceeded using a kernel density estimation method. Input image is loaded from a given input TIFF file. Histogram results are saved in a given csv file.
- See also
- histogram 2d algorithm
-
kernel density estimator 2d algorithm
Usage
This is a standalone script file which takes no input argument.
Here is a snapshot of input image used by the application and of corresponding results :
Source code documentation
We start by importing all necessary libraries:
import os
import sys, getopt
import PyIPSDK
import PyIPSDK.IPSDKIPLGlobalMeasure as glbmsr
Then we define the input parameters.
imagesSamplePath = PyIPSDK.getIPSDKDirectory(PyIPSDK.eInternalDirectory.eID_Images)
inputImgPath = os.path.join(imagesSamplePath, "Lena_510x509_UInt8.tif")
outputDataPath = PyIPSDK.getIPSDKDefaultDirectory(PyIPSDK.eDefaultExternalDirectory.eDED_Tmp)
refCsvPath = os.path.join(outputDataPath, "ref_histogram.csv")
estimCsvPath = os.path.join(outputDataPath, "estim_histogram.csv")
We load our input image from the associated Tiff file, by calling the function ipsdk::image::file::loadTiffImageFile.
inImg = PyIPSDK.loadTiffImageFile(inputImgPath)
nbTotPixels = inImg.getGeometry().getNbPixels()
We then apply the histogram computation on the input image using a classical histogram algorithm and a faster one based on a kernel density estimation algorithm.
binMin = 0
binMax = 255
binWidth = 2
histogramMsrParams = PyIPSDK.createHistoMsrParamsWithBinWidth(binMin, binMax, binWidth)
refHisto = glbmsr.histogramMsr2d(inImg, histogramMsrParams)
kdeDataSet = glbmsr.kernelDensityEstimator2d(inImg)
estimHisto = PyIPSDK.generateHistogram(kdeDataSet,
binMin, binMax, binWidth,
nbTotPixels)
We then save the results into output csv files.
print("Saving histograms data to directory " + outputDataPath)
PyIPSDK.exportToCsv(refCsvPath, refHisto)
PyIPSDK.exportToCsv(estimCsvPath, estimHisto)
Lastly, if matplotlib python library is available, we plot results into a graph.
import matplotlib.pyplot as plt
refPlot, = plt.plot(refHisto.getBinMeanColl(), refHisto.frequencies, 'g+-', label="Reference")
estimPlot, = plt.plot(estimHisto.getBinMeanColl(), estimHisto.frequencies, 'ro-', label="Estimation")
plt.title("Image histograms")
plt.xlabel('Bin mean')
plt.ylabel('Population')
plt.legend(handles=[refPlot, estimPlot])
plt.grid(True)
plt.show()
See the full source listing