Example #1
0
def select_method(Method):
    '''
    Selects a method that returns the column averages for an array A.
    '''

    if Method.lower() == "mean":
        func = lambda A: np.average(A, axis=0)

    elif Method.lower() == "median":
        func = lambda A: np.median(A, axis=0)

    elif Method.lower() == "mode":
        func = lambda A: mode(A, axis=0)[0]

    elif Method.lower() == "frobustmean":
        func = lambda A: centroid.frobomad(A, axis=0)[0]

    elif Method.lower() == "robustmean":
        func = lambda A: chzphot.robomad(A)[0]

    elif Method.lower() == "g******g":
        func = lambda A: np.average(np.vstack(
            (np.median(A, axis=0), centroid.frobomad(A, axis=0)[0],
             mode(A, axis=0)[0], np.average(A, axis=0))),
                                    axis=0)

    else:  # Use Kevin's Frobomad
        print "ERROR!!! Invalid normalization method input. Please try using"
        print "mean, median, mode, robustmean, or g******g."
        print "Just using the Robust Mean By Default"
        print ""

        func = lambda A: centroid.frobomad(A, axis=0)[0]

    return func
def FindNormFactor(target,imgArray,Method="Mean",Scalar=False):
    """
        Purpose: Find the normilization vector to apply to the image
    """
    rows,cols = imgArray.shape
    norm_factor = []
    for col in range(0,cols):
        if Method.lower() == "mean":
            norm_factor.append(target/np.mean(imgArray[:,col]))
        elif Method.lower() == "median":
            norm_factor.append(target/np.median(imgArray[:,col]))
        elif Method.lower() == "mode":
            norm_factor.append(target/mode(imgArray[:,col])[0])
        elif Method.lower() == "robustmean":
            norm_factor.append(target/centroid.frobomad(imgArray[:,col])[0])
        elif Method.lower() == "g******g":
            norm_factor.append(target/np.mean([np.median(imgArray[:,col]),centroid.frobomad(imgArray[:,col])[0],np.mean(imgArray[:,col]),mode(imgArray[:,col])[0]]))
        else: # Use Kevin's Frobomad
            print "ERROR!!! Invalid normalization method input. Please try using"
            print "mean"
            print "median"
            print "mode"
            print "robustmean"
            print "g******g"
            print "Just using the Robust Mean By Default"
            print ""
            norm_factor.append(target/centroid.frobomad(imgArray[:,col])[0])
    return norm_factor
Example #3
0
def FindNormFactor(target, imgArray, Method="Mean", Scalar=False):
    """
        Purpose: Find the normilization vector to apply to the image
    """
    rows, cols = imgArray.shape
    norm_factor = []
    for col in range(0, cols):
        if Method.lower() == "mean":
            norm_factor.append(target / np.mean(imgArray[:, col]))
        elif Method.lower() == "median":
            norm_factor.append(target / np.median(imgArray[:, col]))
        elif Method.lower() == "mode":
            norm_factor.append(target / mode(imgArray[:, col])[0])
        elif Method.lower() == "robustmean":
            norm_factor.append(target / centroid.frobomad(imgArray[:, col])[0])
        elif Method.lower() == "g******g":
            norm_factor.append(target / np.mean([
                np.median(imgArray[:, col]),
                centroid.frobomad(imgArray[:, col])[0],
                np.mean(imgArray[:, col]),
                mode(imgArray[:, col])[0]
            ]))
        else:  # Use Kevin's Frobomad
            print "ERROR!!! Invalid normalization method input. Please try using"
            print "mean"
            print "median"
            print "mode"
            print "robustmean"
            print "g******g"
            print "Just using the Robust Mean By Default"
            print ""
            norm_factor.append(target / centroid.frobomad(imgArray[:, col])[0])
    return norm_factor
Example #4
0
def PlotComparison(old_img, new_img, title="Title"):
    """
        Purpose: Generate a 2x2 plot showing image statistics to compare before/after 
        gain normalization.

        Inputs: -old_img {numpy array}- Original pre-normalized image
                -old_img {numpy array}- Original pre-normalized image
    """
    rows, cols = new_img.shape
    oldstd = []
    newstd = []
    oldmed = []
    newmed = []
    for col in range(0, cols):
        oldstd.append(np.std(old_img[:, col]))
        newstd.append(np.std(new_img[:, col]))
        oldmed.append(centroid.frobomad(old_img[:, col])[0])
        newmed.append(centroid.frobomad(new_img[:, col])[0])

    randcol = pylab.randint(0, cols, 500)
    randrow = pylab.randint(0, rows, 500)

    pylab.figure(num=None,
                 figsize=(13, 7),
                 dpi=80,
                 facecolor='w',
                 edgecolor='k')
    pylab.title(title)

    #Standard Deviation Comparison
    pylab.subplot(2, 2, 1)
    pylab.plot(oldstd)
    pylab.plot(newstd)
    pylab.legend(['Before Normalization \sigma', 'After Normalization \sigma'])
    pylab.xlabel('Column')
    pylab.ylabel('USELESS Standard Deviation')

    pylab.subplot(2, 2, 3)
    pylab.plot(oldmed)
    pylab.plot(newmed)
    pylab.legend(['Before Normalization Rmean', 'After Normalization Rmean'])
    pylab.xlabel('Column')
    pylab.ylabel('Robust Mean')

    #fourrier signal
    pylab.subplot(2, 2, 2)
    pylab.hist(old_img[randrow, randcol], bins=75)
    pylab.xlabel('Hist')
    pylab.ylabel('Old Rand Selection Intensity')

    pylab.subplot(2, 2, 4)
    pylab.hist(new_img[randrow, randcol], bins=75)
    pylab.xlabel('Hist')
    pylab.ylabel('New Rand Selection Intensity')
def PlotComparison(old_img,new_img,title="Title"):
    """
        Purpose: Generate a 2x2 plot showing image statistics to compare before/after 
        gain normalization.

        Inputs: -old_img {numpy array}- Original pre-normalized image
                -old_img {numpy array}- Original pre-normalized image
    """
    rows,cols=new_img.shape
    oldstd=[]
    newstd=[]
    oldmed=[]
    newmed=[]
    for col in range(0,cols):
        oldstd.append(np.std(old_img[:,col]))
        newstd.append(np.std(new_img[:,col]))
        oldmed.append(centroid.frobomad(old_img[:,col])[0])
        newmed.append(centroid.frobomad(new_img[:,col])[0])

    randcol=pylab.randint(0,cols,500)
    randrow=pylab.randint(0,rows,500)

    pylab.figure(num=None, figsize=(13, 7), dpi=80, facecolor='w', edgecolor='k')
    pylab.title(title)

    #Standard Deviation Comparison
    pylab.subplot(2,2,1)
    pylab.plot(oldstd)
    pylab.plot(newstd)
    pylab.legend(['Before Normalization \sigma','After Normalization \sigma'])
    pylab.xlabel('Column')
    pylab.ylabel('USELESS Standard Deviation')

    pylab.subplot(2,2,3)
    pylab.plot(oldmed)
    pylab.plot(newmed)
    pylab.legend(['Before Normalization Rmean','After Normalization Rmean'])
    pylab.xlabel('Column')
    pylab.ylabel('Robust Mean')

    #fourrier signal
    pylab.subplot(2,2,2)
    pylab.hist(old_img[randrow,randcol],bins=75)
    pylab.xlabel('Hist')
    pylab.ylabel('Old Rand Selection Intensity')

    pylab.subplot(2,2,4)
    pylab.hist(new_img[randrow,randcol],bins=75)
    pylab.xlabel('Hist')
    pylab.ylabel('New Rand Selection Intensity')
def select_method(Method):
    '''
    Selects a method that returns the column averages for an array A.
    '''

    if Method.lower() == "mean":
        func = lambda A: np.average(A, axis=0)
        
    elif Method.lower() == "median":
        func = lambda A: np.median(A, axis=0)
        
    elif Method.lower() == "mode":
        func = lambda A: mode(A, axis=0)[0]
        
    elif Method.lower() == "frobustmean":  
        func = lambda A: centroid.frobomad(A, axis=0)[0]
    
    elif Method.lower() == "robustmean":
        func = lambda A: chzphot.robomad(A)[0]
        
    elif Method.lower() == "g******g":
        func = lambda A: np.average(np.vstack(( np.median(A, axis=0), 
                                       centroid.frobomad(A, axis=0)[0],
                                       mode(A, axis=0)[0],
                                       np.average(A, axis=0) )),
                                    axis=0)  
       
    else: # Use Kevin's Frobomad
        print "ERROR!!! Invalid normalization method input. Please try using"
        print "mean, median, mode, robustmean, or g******g."
        print "Just using the Robust Mean By Default"
        print ""
        
        func = lambda A: centroid.frobomad(A, axis=0)[0]

    return func
def DarkColNormalize(imgArray,top=0,target=None,Plot=0,Method="Mean"):
    """
        Purpose: Normalize image array based on dark columns.

        Inputs: imgArray -numpy array- image array
                top      -bool {optional}- Indicates if this is a "top" oriented image array. For top sensor half,
                          dark rows come after the information image array. Otherwise, this assumes the dark rows
                          come first.
    """
    rows,cols = imgArray.shape
#    print "rows",rows,"cols",cols
    
    if top == 0:
        darkrows = imgArray[0:16,:]
    else:
        darkrows = imgArray[rows-16:rows,:]

    # Get target normalization (which is median of the top or bottom half including dark rows))
    if target is None:
        target = centroid.frobomad(imgArray)[0]

    # Get normalization factor
    norm_factor=FindNormFactor(target,darkrows,Method=Method)
    # Apply Normalization Factor
    new_imgArray = imgArray*norm_factor

    # IF assuming BIAS, not GAIN
#    new_imgArray = imgArray.copy()
#    for col in range(0,cols):
#        new_imgArray[:,col] = np.subtract(imgArray[:,col],np.mean(darkrows[:,col]))


    if Plot:
        if top:
            PlotComparison(imgArray,new_imgArray,title="Top Sensor Half")
        else:
            PlotComparison(imgArray,new_imgArray,title="Bottom Sensor Half")


    # Cut off dark rows and columns and return
    if top:
        final_image = new_imgArray[0:1080][:,16:2560+16]
    else:
        final_image = new_imgArray[16:1080+16][:,16:2560+16]
        
    return final_image
Example #8
0
def DarkColNormalize(imgArray, top=0, target=None, Plot=0, Method="Mean"):
    """
        Purpose: Normalize image array based on dark columns.

        Inputs: imgArray -numpy array- image array
                top      -bool {optional}- Indicates if this is a "top" oriented image array. For top sensor half,
                          dark rows come after the information image array. Otherwise, this assumes the dark rows
                          come first.
    """
    rows, cols = imgArray.shape
    #    print "rows",rows,"cols",cols

    if top == 0:
        darkrows = imgArray[0:16, :]
    else:
        darkrows = imgArray[rows - 16:rows, :]

    # Get target normalization (which is median of the top or bottom half including dark rows))
    if target is None:
        target = centroid.frobomad(imgArray)[0]

    # Get normalization factor
    norm_factor = FindNormFactor(target, darkrows, Method=Method)
    # Apply Normalization Factor
    new_imgArray = imgArray * norm_factor

    # IF assuming BIAS, not GAIN
    #    new_imgArray = imgArray.copy()
    #    for col in range(0,cols):
    #        new_imgArray[:,col] = np.subtract(imgArray[:,col],np.mean(darkrows[:,col]))

    if Plot:
        if top:
            PlotComparison(imgArray, new_imgArray, title="Top Sensor Half")
        else:
            PlotComparison(imgArray, new_imgArray, title="Bottom Sensor Half")

    # Cut off dark rows and columns and return
    if top:
        final_image = new_imgArray[0:1080][:, 16:2560 + 16]
    else:
        final_image = new_imgArray[16:1080 + 16][:, 16:2560 + 16]

    return final_image
def ImgColNormalize(imgArray,target=None, Rows=0,Method="mean"):
    "THIS WONT WORK UNLESS LOOKING AT SOMETHING FLAT"
    """
    Purpose: Normalize image array based on dark columns.

    Inputs: imgArray -numpy array- image array
            target   -desired norm level {optional}- Set this to the gain you wished the image normalized to. Otherwise
                      the overall image median is used by default.
    """
    rows,cols = imgArray.shape

    # Get target normalization
    if target is None:
        target = centroid.frobomad(imgArray[800:1200,700:1300])[0]

    # Get normalization factor
    norm_factor=FindNormFactor(target,imgArray,Method=Method)

    # Apply Normalization Factor
    new_imgArray = imgArray*norm_factor

    return new_imgArray
Example #10
0
def ImgColNormalize(imgArray, target=None, Rows=0, Method="mean"):
    "THIS WONT WORK UNLESS LOOKING AT SOMETHING FLAT"
    """
    Purpose: Normalize image array based on dark columns.

    Inputs: imgArray -numpy array- image array
            target   -desired norm level {optional}- Set this to the gain you wished the image normalized to. Otherwise
                      the overall image median is used by default.
    """
    rows, cols = imgArray.shape

    # Get target normalization
    if target is None:
        target = centroid.frobomad(imgArray[800:1200, 700:1300])[0]

    # Get normalization factor
    norm_factor = FindNormFactor(target, imgArray, Method=Method)

    # Apply Normalization Factor
    new_imgArray = imgArray * norm_factor

    return new_imgArray
def ImgNormalize(imgArray, bg=None, Method="mean", source="image"):
    """
        Purpose: Normalize an image based on column averages. "bg" is the image
        background value, and is computed by frobomad if left unspecified. The 
        default method is "mean." Image values are used by default, unless "source"
        is set to "dark."
        
        Timing: For one image, **just** finding the column values takes:
          mean     = 0.05 sec
          median   = 0.25 sec
          frobomad = 1.6 sec
          mode     = 15 sec
          g******g = 15 sec 
    """
    
    # Deepcopy
    img = np.int16( cp.deepcopy(imgArray) )

    # Get size of the image
    [ysize, xsize] = img.shape
    middle = int(ysize/2)
    
    # Get column value method
    func = select_method(Method)
    
    # Separate dark rows and image
    dark = None
    if (ysize, xsize) == (2192,2592):
        # Delete dark columns on the left/right sides of the image (16 cols)
        img = img[:, 16:xsize-16]
    
        # Separate the dark rows from the image and update middle
        dark = img[middle-16:middle+16]
        img = img[np.r_[0:middle-16, middle+16:ysize] ]
        middle -= 16;
    
    # Use dark rows for column data
    if source == "dark":
        if dark is None:
            raise RuntimeError('Image must be uncropped to use source="dark"')
        else: 
            topCol = func(dark[:16])
            botCol = func(dark[16:])
            
    elif source == "image":
        topCol = func(img[:middle])
        botCol = func(img[middle:])     
          
    else:
        raise RuntimeError('Source must be image or dark')
    
    # Find top and bottom bg
    if bg is None:
        bg = centroid.frobomad(img[:middle])[0]
    

    # Apply column averages to image

#    top= img[:middle]*bg[0]/np.tile(topCol, (middle,1))
#    bottom=img[middle:]* bg[1]/np.tile(botCol, (middle,1))
#    img=np.append(top,bottom,0)


    img[:middle] = img[:middle]*bg/np.tile(topCol, (middle,1))
    img[middle:] = img[middle:]*bg/np.tile(botCol, (middle,1))


    
    # return subtracted image
    return img  
Example #12
0
def ImgNormalize(imgArray, bg=None, Method="mean", source="image"):
    """
        Purpose: Normalize an image based on column averages. "bg" is the image
        background value, and is computed by frobomad if left unspecified. The 
        default method is "mean." Image values are used by default, unless "source"
        is set to "dark."
        
        Timing: For one image, **just** finding the column values takes:
          mean     = 0.05 sec
          median   = 0.25 sec
          frobomad = 1.6 sec
          mode     = 15 sec
          g******g = 15 sec 
    """

    # Deepcopy
    img = np.int16(cp.deepcopy(imgArray))

    # Get size of the image
    [ysize, xsize] = img.shape
    middle = int(ysize / 2)

    # Get column value method
    func = select_method(Method)

    # Separate dark rows and image
    dark = None
    if (ysize, xsize) == (2192, 2592):
        # Delete dark columns on the left/right sides of the image (16 cols)
        img = img[:, 16:xsize - 16]

        # Separate the dark rows from the image and update middle
        dark = img[middle - 16:middle + 16]
        img = img[np.r_[0:middle - 16, middle + 16:ysize]]
        middle -= 16

    # Use dark rows for column data
    if source == "dark":
        if dark is None:
            raise RuntimeError('Image must be uncropped to use source="dark"')
        else:
            topCol = func(dark[:16])
            botCol = func(dark[16:])

    elif source == "image":
        topCol = func(img[:middle])
        botCol = func(img[middle:])

    else:
        raise RuntimeError('Source must be image or dark')

    # Find top and bottom bg
    if bg is None:
        bg = centroid.frobomad(img[:middle])[0]

    # Apply column averages to image

#    top= img[:middle]*bg[0]/np.tile(topCol, (middle,1))
#    bottom=img[middle:]* bg[1]/np.tile(botCol, (middle,1))
#    img=np.append(top,bottom,0)

    img[:middle] = img[:middle] * bg / np.tile(topCol, (middle, 1))
    img[middle:] = img[middle:] * bg / np.tile(botCol, (middle, 1))

    # return subtracted image
    return img