text: """
   preprocess input image into a grayscale PNG ('input.png')
  """
  
  import logging
  import numpy as np
  import matplotlib.pyplot as plt
  from sys import exit
  
  from pydicom import dcmread
  from pydicom import errors as err
  from PIL import Image
  
  
  mlg = logging.getLogger(__name__)
  
  
  
  def isDICOM(file):
      """
      Check if the input file is DICOM
      """
  
      try:
          dcmread(file)
          return True
  
      except err.InvalidDicomError:
          msg = ' isDICOM: input is not a DICOM image'
          mlg.info(msg)
          return False
  
  
  
  def rgb2gray(rbgimg):
      """
      convert RGB to grayscale
      """
  
      # this is the usual grayscale conversion:
      #gray = lambda rgb : np.dot(rgb[... , :3] , [0.299 , 0.587, 0.114])
      # but we need a custom one b/c DICOM images are 'colorized' only to
      # add labels. Just turn off G and B channels:
      gray = lambda rgb : np.dot(rgb[... , :3] , [1, 0, 0])
      grayimg = gray(rbgimg)
  
      mlg.info(f' rbg2gray: signal (min, max) are ({np.amin(grayimg): .2f}, {np.amax(grayimg): .2f})')
  
      return grayimg
  
  
  
  def process(imgin):
      """
      convert input DICOM or JPG/JPEG or PNG into input.png
      """
  
      mlg.info(f' preproc: --- --- --- processing {imgin}')
  
      savename = 'input.png'
  
      # for DICOM file
      if (isDICOM(imgin)):
          rgb  = dcmread(imgin).pixel_array
          gray = rgb2gray(rgb)
          plt.imsave(savename, gray, cmap = plt.cm.gray)
          mlg.info(f' preproc: input is DICOM with size {gray.shape}')
  
      # all other formats
      else:
          try:
              img = Image.open(imgin)
              msg = f' preproc: input is {img.format} with size {img.size}'
  
              if img.format in ['PNG', 'JPG', 'JPEG']:
                  mlg.info(msg)
                  img = img.convert('L')
                  img.save(savename)
  
              else:
                  msg = ' preproc: unsupported input image format.'
                  mlg.error(msg), exit(msg)
  
          except Exception as e:
              msg = ' preproc: not able to open input file'
              mlg.error(msg), exit(msg)
  