Brandon J - 6 months ago 10

Python Question

Okay guys, I am stuck trying to create a histogram matching for two images; a template image and a destination image(destination meaning the image where i want to match the template image). Rather than displaying the matched image, i get a blank image. I feel like i am exhausted at this hence why i came to SO. Can someone guide me in the right direction?

Here is my traceback

`/Users/Brandon/project/zam.py:21: RuntimeWarning: divide by zero encountered in divide`

cdfTemplate = (255 * cdfTemplate / cdfTemplate[-1]) #normalize

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/ma/core.py:4089: UserWarning: Warning: converting a masked element to nan.

warnings.warn("Warning: converting a masked element to nan.")

And here is the contents of template.

`[ 0.77050539 0.78084622 0.79283112 ..., 0 0`

nan]

[ 0.75330601 0.76671072 0.78165129 ..., 0 0 0]

[ 0.72842868 0.74465601 0.76483058 ..., 0 0]

Any Help in the right direction would be appreciated.

`def matching(template, target, numberOfBins=256):`

templateHist, bins1 = np.histogram(template.flatten(), numberOfBins, density = False)

targetHist, bins2 = np.histogram(target.flatten(), numberOfBins, density = False)

cdfTemplate = templateHist.cumsum() #Cumulative distributed function

cdfTemplate = (255 * cdfTemplate / cdfTemplate[-1]) #normalize

cdfTarget = targetHist.cumsum()

cdfTarget = (255 * cdfTarget / cdfTarget[-1]).astype(np.float64)

im2 = np.interp(template.flatten(), cdfTemplate, bins1[:-1])

im3 = np.interp(im2, cdfTarget, bins2[:-1])

result = im3.reshape((template.shape))

return result

Answer

- The error message is telling you that
`cdfTemplate[-1]`

is equal to zero, which results in all of the elements in`cdfTemplate`

becoming NaNs. - Working backwards, this implies that the sum of
`templateHist`

must also be zero. `templateHist`

contains bin counts computed from`template.flatten()`

. Since you haven't specified a set of weights for`np.histogram`

, there's no way that any of the elements in`templateHist`

could be negative. Therefore`templateHist`

must be all zeros.- You are also passing a positive integer as the
`bins`

parameter to`np.histogram`

, and you haven't specified the`range`

parameter. Therefore if`template`

contains*any*values then`np.histogram`

should automatically select a set of bin edges such that at least one of the counts would be positive. - If
`template`

contained NaNs or infinite values you should get a`ValueError`

rather than a vector of all-zero bin counts. - Therefore the logical conclusion is that
`template`

must be an empty array.

Source (Stackoverflow)

Comments