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

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

 /*
  * $Log: lvhmed.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: lvhmed.c
 >>>>
 >>>>      Program Name: vhmed
 >>>>
 >>>> Date Last Updated: Tue Mar  5 22:29:34 1991 
 >>>>
 >>>>          Routines: lvhmed - the library call for vhmed
 >>>>
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/


#include "vinclude.h"


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


/****************************************************************
*
* Routine Name: lvhmed - library call for vhmed
*
* Purpose:
*    
*    Perform median filtering on an image using  a  histogram  to
*    find the median.
*    
*    
* Input:
*    
*         img -- xvimage structure
*         wsize -- window width argument
*         hsize -- window height argument
*    
*         For odd windows (masks) the median value is replaced in  the
*         center pixel location of the window.
*    
*    
* Output:
*    
*         img -- holds the result of the median filtered
*                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.
*    
*         lvhmed returns 1 on success and 0 on failure.
*    
*    
*
* Written By: Marcelo Teran, Ramiro Jordan
*    
*    
****************************************************************/


/* -library_def */
int
lvhmed(img,xsize,ysize)
struct xvimage *img;
int xsize, ysize;
/* -library_def_end */

/* -library_code */
{

    int row,                            /* points image row */ 
        col,                            /* points image col */ 
        th,                             /* gives the mediun of the wind. */
        tmdn,                           /* numb of pixels <= median */ 
        g1,                             /* auxiliar variable */
        xoff,                           /* horiz. offset in the img */
        yoff,                           /* vertic. offset in the img */
        xend,                           /* step in img up to here */
        yend,                           /* step in img up to here */
        mdn,                            /* this is the median value */
        nc,                             /* column size of image */
        nr,                             /* row size of image */
        i, j, k, m;                     /* general counters */

    unsigned int hist[256];             /* holds histogram of window */

    unsigned char *ptr,                 /* pointer to the image data char */
                  *result;              /* pointer to resulting image char */

    char  *program;                     /* contains the library name */

    program = "lvhmed";

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

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

    th = xsize * ysize / 2;

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

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

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

   /* Zero histogram */
    bzero((char *) hist, 256 * sizeof(unsigned int));

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

   /* perform median filtering of an image */
    for (row = 0 ; row < yend; row++){

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

       /* get the median value */
        if(tmdn > th){
            do {
                mdn = mdn - 1;
                tmdn = tmdn - hist[mdn];
            } while(tmdn > th);

        } else {
            while(tmdn + hist[mdn] <= th){
                tmdn = tmdn + hist[mdn];
                mdn = mdn + 1;
            }
        }
        result[nc *(row + yoff) + xoff + m++] = mdn;

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

            for(k = 0; k < ysize; k++){

               /* delete the lefmost column of the previous window*/
                g1 =  ptr[col + nc*(row + k)];
                hist[g1] = hist[g1] -1;

                if(g1 < mdn) tmdn = tmdn -1;

               /* add the rightmost column of the current window*/
                g1 = ptr[xsize+ nc*(row + k) +col];
                hist[g1] = hist[g1] + 1;

                if(g1 < mdn) tmdn = tmdn + 1;

            }

       /* get the median value */
            if(tmdn > th){
                do {
                    mdn = mdn - 1;
                    tmdn = tmdn - hist[mdn];
                } while(tmdn > th);
            } else {
                while(tmdn + hist[mdn] <= th){
                    tmdn = tmdn + hist[mdn];
                    mdn = mdn + 1;
                }
            }
            result[nc *(row + yoff) + xoff + m++] = mdn;
        }
       /* Reset histogram and variables */
        bzero((char *) hist, 256 * sizeof(unsigned int));
        m = 0; tmdn = 0; mdn = 0;
    }

    free (img->imagedata);
    img->imagedata = (char *) result;

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