title: Saving DICOM image as lossless JPEG
body: <p>My original image is in DICOM format and I want to save it in lossless jpg format (or at least keep as much information as I can!!!). How can I do that in python? Currently, I am using the following code which produces lossy png image. I call it lossy png because the png image looks different from dicom image when I see dicom image by dicom browser. Also, how can I modify this image to get jpg image rather than png image. </p>
  
  <pre><code>import numpy as np
  import png
  import pydicom
  ds = pydicom.dcmread("./MyImage.dcm")
  shape = ds.pixel_array.shape
  # Convert to float to avoid overflow or underflow losses.
  image_2d = ds.pixel_array.astype(float)
  # Rescaling grey scale between 0-255
  image_2d_scaled = (np.maximum(image_2d,0) / image_2d.max()) * 256
  # Convert to uint
  image_2d_scaled = np.uint8(image_2d_scaled)
  # Write the PNG file
  with open("out.png", 'wb') as png_file:
      w = png.Writer(shape[1], shape[0], greyscale=True)
      w.write(png_file, image_2d_scaled)
  </code></pre>