title: How to convert 12 bit DICOM image to 8 bit jpeg?
body: <p>I am trying to load DICOM files into python using the DICOM library. I have done the following</p>
  <pre><code>ds=dicom.read_file(r&quot;C:\Users\Z003SPFR.AD005\ML\GLCM AND SVM\data\NECT\1.IMA&quot;)
  #    # store the raw image data
  DicomImage = ds.pixel_array
  </code></pre>
  <p>This gives me values that appear to be 12 bit, since the highest value obtained was around 3047 and lowest value was 0. Then I made my own mapping function to bring it to the range 0-255. I used the following code:</p>
  <pre><code>leftMin = 0
  leftMax = np.amax(DicomImage)
  
  rightMin = 0
  rightMax = 255
  
  
  
  def translate(value, leftMin, leftMax, rightMin, rightMax):
      # Figure out how 'wide' each range is
      leftSpan = leftMax - leftMin
      rightSpan = rightMax - rightMin
  
      # Convert the left range into a 0-1 range (float)
      valueScaled = float(value - leftMin) / float(leftSpan)
  
      # Convert the 0-1 range into a value in the right range.
      return rightMin + (valueScaled * rightSpan)
  
  #print(translate(value, leftMin, leftMax, rightMin, rightMax))
  
         
  
  def int12_to_int8(img):
      img_array = []
  
      for eachRow in img:
          for eachPix in eachRow:
              img_array.append(translate(eachPix,leftMin, leftMax, rightMin, rightMax))
      img_array = np.array(img_array)
      img_array = img_array.reshape(512,512)  
      return img_array
  
  correct_range_image = int12_to_int8(DicomImage)
  </code></pre>
  <p>After doing this, I realized that the array <code>img_array</code> was of type <code>uint16</code>. I wanted it as <code>uint8</code>. So I used the following line to convert to <code>uint8</code>:</p>
  <pre><code>cvuint8 = cv2.convertScaleAbs(correct_range_image)
  </code></pre>
  <p>Then I displayed the resulting image. But I received an image that didn't represent the original image very well. I have posted pictures of the original image and the converted image. How can I make the conversion better so that I get a better representation of the original image? Code I used to display is here :</p>
  <pre><code>cv2.imwrite('1.jpeg', cvuint8 )
  cv2.imshow('image',cvuint8 )[enter image description here][1]
  cv2.waitKey(0)
  </code></pre>
  <p>IMAGES</p>
  <p>Converted Image<br />
  <a href="https://i.stack.imgur.com/ZLgUQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZLgUQ.png" alt="Converted Image" /></a></p>
  <p>Original Image<br />
  <a href="https://i.stack.imgur.com/L7X13.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L7X13.png" alt="Original Image" /></a></p>