How to get Hounsfield units from raw pixel data for CT?

Hello! When I read the value of individual pixels of CT or MRI, I get values ​​in the range from 0 to 65535. How can I get values ​​in Hounsfield units, that is, in the range from -1024 to ~2000?
For example:

  • contrasted vessels: 300-500 HU
  • the lungs: about -750 HU
  • etc.

Get the slope and intercept from the header of the file then you could write a function or create a look up table to generate values based on: HU = Gray_Value * slope + intercept.

I found the solution. The conversion formula is:

HU = (raw_pixel - PixelRepresentation * 2^BitsAllocated / 2)
    >> (BitsAllocated - BitsStored) * RescaleSlope + RescaleIntercept

Firstly, is need to make bit shifting to right.

  • (0028,0100) BitsAllocated - the count of bits for one pixel storing
  • (0028,0101) BitsStored - the count of bits that really used from allocated

Example:
BitsAllocated - BitsStored = 16 - 12 = 4, so we need to shift raw pixel data to 4 to rigth (this is equal to dividing by 16).

Also the important tag is:
(0028,0103) PixelRepresentation
if is equal to 0: unsigned pixel data
if is equal to 1: signed data

If PixelRepresentation equals to 1 (signed pixel data), then we need subtract the half from max value that can be stored in the pixel. For example, if BitsAllocated = 16, then 65536 - is the maximum number of values ​​that can be stored in 16 bits. Then the half would be 32768.

Example 1:

  • min raw pixels: 0
  • max raw pixels: 49936
  • min HU: -1024
  • max HU: 2097
  • (0028,0100) BitsAllocated: 16
  • (0028,0103) PixelRepresentation: 0
  • (0028,0101) BitsStored: 12
  • (0028,1053) RescaleSlope: 1
  • (0028,1052) RescaleIntercept: -1024

The answer is:

  • min HU = (0 - 0 * 2^16 / 2) >> (16 - 12) * 1 - 1024 = -1024
  • max HU = (49936 - 0 * 2^16 / 2) >> (16 - 12) * 1 - 1024 = 2097

Example 2:

  • min raw pixels: 30768
  • max raw pixels: 35679
  • min HU: -3024
  • max HU: 1887
  • (0028,0100) BitsAllocated: 16
  • (0028,0103) PixelRepresentation: 1
  • (0028,0101) BitsStored: 16
  • (0028,1053) RescaleSlope: 1
  • (0028,1052) RescaleIntercept: -1024

The answer is:

  • min HU = (30768 - 1 * 2^16 / 2) >> (16 - 16) * 1 - 1024 = -3024
  • max HU = (35679 - 1 * 2^16 / 2) >> (16 - 16) * 1 - 1024 = 1887

Example 3:

  • min raw pixels: 31744
  • max raw pixels: 34311
  • min HU: -1024
  • max HU: 1543
  • (0028,0100) BitsAllocated: 16
  • (0028,0103) PixelRepresentation: 1
  • (0028,0101) BitsStored: 16
  • (0028,1053) RescaleSlope: 1
  • (0028,1052) RescaleIntercept: 0

The answer is:

  • min HU = (31744 - 1 * 2^16 / 2 >> (16 - 16) * 1 + 0 = -1024
  • max HU = (34311 - 1 * 2^16 / 2) >> (16 - 16) * 1 + 0 = 1543