简体   繁体   中英

Subtract two histograms

I am trying to find the residual left behind when you subtract pixel distribution of two different images(the images are in a 2D array format).

I am trying to do something like the below

import numpy as np
hist1, bins1 = np.histogram(img1, bins=100)
hist2, bins2 = np.histogram(img2, bins=100)
residual = hist1 - hist2

However, in my above method the problem is that both the images have different maximum and minimum and when you do hist1-hist2 the individual bin value of each element in hist1-hist2 is not the same.

I was wondering if there is an alternative elegant way of doing this.

Thanks.

You can explicitly define bins in np.histogram() call. If you set them to the same value for both calls, then your code would work.

If your values are say between 0 and 255, you could do following:

import numpy as np
hist1, bins1 = np.histogram(img1, bins=np.linspace(0, 255, 100))
hist2, bins2 = np.histogram(img2, bins=np.linspace(0, 255, 100))
residual = hist1 - hist2

This way you have 100 bins with the same boundaries and the simple difference now makes sense (the code is not tested but you get the idea).

import numpy as np
nbins = 100
#minimum value element wise from both arrays
min = np.minimum(img1, img2)
#maximum value element wise from both arrays
max = np.maximum(img1, img2)
#histogram is build with fixed min and max values
hist1, _ = numpy.histogram(img1,range=(min,max), bins=nbins)
hist2, _ = numpy.histogram(img2,range=(min,max), bins=nbins)

#makes sense to have only positive values 
diff = np.absolute(hist1 - hist2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM