Search code examples
pythonhistogram

Plot 16-bit 65536 image histogram and display certain range of histogram


I would like to plot a 16-bit image with a histogram and select and display certain range of the histogram in grayscale.

I have tried the code below and it produces a histogram for the 16-bit grayscale image.

from skimage import io
import matplotlib.pyplot as plt
image = io.imread('1.tiff')
plt.hist(image.ravel(), bins = 65536)
plt.xlabel('Intensity Value')
plt.ylabel('Count')
plt.show()

Histogram

I would want to select, say, 34000 to 36000 intensity to produce a grayscale image. But looking through the web, I found the following code that produced only black and white not grayscale output image.

gray = cv.imread('1.tiff', cv.IMREAD_ANYDEPTH)
gray_filtered = cv.inRange (gray, 34000, 36000)
cv.imshow('gray_filtered', gray_filtered)
if cv.waitKey(0) & 0xff == 27:
    cv.destroyAllWindows()

I need a code that can produce grayscale image, say, from 34000 to 36000 intensity. Help very appreciated.

Many thanks.


Solution

  • You should be able to use rescale_intensity() after importing exposure:

    from skimage import io, exposure
    image = io.imread('1.tif')
    image = exposure.rescale_intensity(image, in_range=(34000, 36000))
    io.imsave('new_image.tif', image)
    

    For the histogram, you should just be able to pass a range argument:

    plt.hist(image.ravel(), bins=65536, range=(34000, 36000))
    

    Before (I tried an example):

    enter image description here

    After:

    enter image description here