 /*
  * Khoros: $Id: lvenhance.c,v 1.1 1991/05/10 15:41:54 khoros Exp $
  */

#if !defined(lint) && !defined(SABER)
static char rcsid[] = "Khoros: $Id: lvenhance.c,v 1.1 1991/05/10 15:41:54 khoros Exp $";
#endif

 /*
  * $Log: lvenhance.c,v $
 * Revision 1.1  1991/05/10  15:41:54  khoros
 * Initial revision
 *
  */ 

/*
 *----------------------------------------------------------------------
 *
 * Copyright 1991, University of New Mexico.  All rights reserved.
 * Permission to copy and modify this software and its documen-
 * tation only for internal use in your organization is hereby
 * granted, provided that this notice is retained thereon and
 * on all copies.  UNM makes no representations as too the sui-
 * tability and operability of this software for any purpose.
 * It is provided "as is" without express or implied warranty.
 * 
 * UNM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
 * NESS.  IN NO EVENT SHALL UNM BE LIABLE FOR ANY SPECIAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY OTHER DAMAGES WHAT-
 * SOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PER-
 * FORMANCE OF THIS SOFTWARE.
 * 
 * No other rights, including for example, the right to redis-
 * tribute this software and its documentation or the right to
 * prepare derivative works, are granted unless specifically
 * provided in a separate license agreement.
 *---------------------------------------------------------------------
 */

#include "unmcopyright.h"        /* Copyright 1991 by UNM */

/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 >>>>
 >>>>         File Name: lvenhance.c
 >>>>
 >>>>      Program Name: venhance
 >>>>
 >>>> Date Last Updated: Tue Mar  5 22:32:45 1991 
 >>>>
 >>>>          Routines: lvenhance - the library call for venhance
 >>>>
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/


#include "vinclude.h"


/* -library_includes */
/* -library_includes_end */


/****************************************************************
*
* Routine Name: lvenhance - library call for venhance
*
* Purpose:
*    
*    Enhances an image using the  local  standard  deviation  and
*    mean.
*    
*    
* Input:
*    
*         img -- pointer to the input image
*         xsize -- horizontal dimension of the window being used
*         ysize -- vertical dimension of the window being used
*         factor -- tuning factor (parameter k, see vman of venhance)
*         minstd -- minimum allowed standard deviation
*    
*    
* Output:
*    
*         img -- pointer to the output image
*    
*         img is used for both the input  xvimage  structure  and  the
*         output  result  xvimage  structure.   This  is  done to save
*         space, but you must be careful not  to  overwrite  important
*         data.
*    
*         lvenhance returns 1 upon success and 0 on failure.
*    
*    
*
* Written By: Marcelo Teran
*    
*    
****************************************************************/


/* -library_def */
int
lvenhance(img,xsize,ysize,factor,minstd)
struct xvimage *img;
int xsize, ysize;
float  factor,minstd;
/* -library_def_end */

/* -library_code */
{

    int row,                            /* points image row */ 
        col,                            /* points image col */ 
        xend,                           /* step in img up to here */
        yend,                           /* step in img up to here */
        nc,                             /* column size of image */
        nr,                             /* row size of image */
        xoff, yoff,
        z, h,
        points,
        ind, adex, bdex,
        i, j, k, m;                     /* general counters */

    float *hist;                        /* holds histogram of window */

    unsigned char *ptr;                 /* pointer to the image data char */
    float      *result;                 /* pointer to resulting image char */
    float       value, sum, avg, rms;
    float       MEAN, gain, var;
    float       std;

    char  *malloc(),                    /* function definition */
          *program;                     /* contains the library name */

    program = "lvenhance";

   /* check for odd windows */
    if((xsize & 1) == 0 || (ysize & 1) == 0){
        (void) fprintf(stderr,"lvenhance: Error window must be odd\n");
        return(0);
    }

    propertype(program,img,VFF_TYP_1_BYTE,1);      /* check img. type */        

    nr = img->col_size;
    nc = img->row_size;
    points = nc * nr;

    xend = nc - xsize;
    yend = nr - ysize + 1;
    m = 0; h = 0;

    xoff = xsize / 2;
    yoff = ysize / 2;

   /* Allocate space */ 
   hist = (float *) malloc((unsigned int) xsize * ysize* sizeof(float));
    if(hist == NULL) {
        (void) fprintf(stderr,"lvhmed: insufficient memory available\n");
        return(0);
    }

   /* Allocate space for resulting image */ 
    result = (float *)malloc((unsigned int)nc*nr*sizeof(float ));
    if(result == NULL) {
        (void) fprintf(stderr,"lvhmed: insufficient memory available\n");
        return(0);
    }
   /* Assign image data address to ptr */
    ptr = (unsigned char *)img->imagedata;

    sum = 0; 
   /* compute the overall mean */
    for(i = 0; i < points; i++){
        sum += ptr[i];
    }

    MEAN = sum / (float)points;

   /* perform enhancement to the image */
    for (row = 0 ; row < yend; row++){

       /* setup the first window for the current row */
        for(i = 0; i < ysize; i++){
            for(j = 0; j < xsize; j++){
                hist[i*xsize + j] = (float)ptr[nc*(row + i) + j];
            }
        }

        sum = 0; rms = 0;
       /* get the standard deviation value */
        for(ind = 0; ind < xsize * ysize; ind++){
            sum += hist[ind];
            rms += hist[ind] * hist[ind];
        }

        avg = sum /(xsize * ysize);
        var = rms /(xsize * ysize) - avg * avg;
        std = sqrt((double)var);
        if(std < minstd){
            gain = factor * MEAN;
        } else {
            gain = factor * MEAN / std;
        }
        value = gain *(ptr[nc*(row + yoff) + xoff + m++ ] - avg ) + avg;

        result[nc * (row + yoff) + xoff + h++] = value;

       /* step through the current row */
        for (col = 0 ; col < xend ; col++){

            for(k = 0; k < ysize; k++){
                for(z = 0; z < xsize; z++){
                   /* delete the lefmost column of the previous window*/
                    adex = z + k*xsize;
                    bdex = z + k*nc + col + row*nc;
                    hist[adex] = (float)ptr[bdex + 1];
                }
            }

            sum = 0; rms = 0;
            /* get the variance value */
            for(ind = 0; ind < xsize * ysize; ind++){
                sum += hist[ind];
                rms += hist[ind] * hist[ind];
            }
            avg = sum /(xsize * ysize);
            var = rms /(xsize * ysize) - avg * avg;
            std = sqrt((double)var);
            if(std < minstd){
                gain = factor * MEAN;
            } else {
                gain = factor * MEAN / std;
            }
            value = gain *(ptr[nc*(row + yoff) + xoff + m++ ] - avg ) + avg;

            result[nc * (row + yoff) + xoff + h++] = value;

        } m = 0; h = 0;


    }

    (void)free(img->imagedata);

    img->data_storage_type = VFF_TYP_FLOAT;
    img->imagedata = (char *) result;

    if( !lvconvert(img,1,0,1,255.0,1.0,0)){
        (void) fprintf(stderr,"lvconvert Failed\n");
        return(0);
    }

    return(1);
}
/* -library_code_end */
