from __future__ import division
import os
import sys
import array
import struct
import io
import math
import numpy as np
import colorsys
import pydicom
from pydicom.dataset import Dataset, FileDataset
import pydicom.uid
import skimage as ski
import skimage.io
import skimage.transform
import skimage.draw
import skimage.morphology
import warnings

from Util import *
from File import *

NORMALIZE_NO = 0
NORMALIZE_SIMPLE = 1
NORMALIZE_CONTRAST_STRETCHING = 2
# NORMALIZE_ADAPTATIVE_EQUALIZATION = 3

# _image type should be np.float32
def NormalizeFrame(_image, _normalize = NORMALIZE_NO):
	if _normalize == NORMALIZE_SIMPLE:
		min = np.min(_image)
		max = np.max(_image)
		return (_image - min)/(max - min)
	elif _normalize == NORMALIZE_CONTRAST_STRETCHING:
		p2, p98 = np.percentile(_image, (2, 98))
		return ski.exposure.rescale_intensity(_image, in_range=(p2, p98), out_range=(0,1))
	# elif _normalize == NORMALIZE_ADAPTATIVE_EQUALIZATION
		# return ski.exposure.equalize_adapthist(_image, clip_limit=0.03):

	return _image

def GetMaxValue(_pixelSize):
	if _pixelSize == 8:
		return 255
	elif _pixelSize == 16:
		return 65535
	elif _pixelSize == 10:
		return 1023
	else:
		print("GetMaxValue():: WARNING NOT IMPLEMENTED _pixelSize = " + str(_pixelSize))
	return 65535

def GetFloat32NormalizedFrame(_image, _pixelSize, _normalize = NORMALIZE_NO):
	_image = _image.astype(np.float32)
	if _normalize != NORMALIZE_NO:
		return NormalizeFrame(_image, _normalize)
	return _image/GetMaxValue(_pixelSize)

def ReadOnlyDicomInfo(_filename):