GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 16-Jan-2006, 11:40
june_C21 june_C21 is offline
New Member
 
Join Date: Jan 2006
Posts: 3
june_C21 is on a distinguished road

Median Filter Coding


Does anyone know how to write median filter in C programming? thanks
  #2  
Old 16-Jan-2006, 21:19
kobi_hikri's Avatar
kobi_hikri kobi_hikri is offline
Regular Member
 
Join Date: Apr 2005
Location: Israel
Posts: 431
kobi_hikri has a spectacular aura aboutkobi_hikri has a spectacular aura about

Re: Median Filter Coding


Quote:
Originally Posted by june_C21
Does anyone know how to write median filter in C programming? thanks

Can you please explain ? What do you mean by "median"
filter " ?
Please specify an example of input and output to help us understand the task.

Kobi.
__________________
It's actually a one time thing (it just happens alot).
  #3  
Old 18-Jan-2006, 08:40
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,153
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Median Filter Coding


Quote:
Originally Posted by june_C21
Does anyone know how to write median filter in C programming? thanks
One way to find the median of a list of numbers
1. sort the list.
2. select the middle point of the sorted list


For a filter, where new values replace old values, it's kind of interesting:

First you can have the data points in some kind of FIFO (usually a circular buffer) so that as each datum comes in, it overwrites the oldest value. But wait; there's more.

You probably want to have the sorted values represented in a linked list so that you can find the median without having to sort the entire list of values each time (but, maybe not, if the number of points is small). That means that, associated with each point in the circular buffer, there is a pointer to an element of the linked list. Before entering the new data point into the circular buffer, the item in the linked list of sorted values is removed, and the new item is inserted in the appropriate place.

You may find some points worth pursuing here: Embedded Systems Design article

(And lots of other places too, if you look for them.)



Regards,

Dave
  #4  
Old 23-Feb-2006, 08:31
june_C21 june_C21 is offline
New Member
 
Join Date: Jan 2006
Posts: 3
june_C21 is on a distinguished road

Re: Median Filter Coding


thanks a lot.. how about maximun filter, minimum filter and midpoint filter. do you have any idea how to write those in C ?
  #5  
Old 27-Feb-2006, 08:57
davis
 
Posts: n/a

Re: Median Filter Coding


Quote:
Originally Posted by june_C21
thanks a lot.. how about maximun filter, minimum filter and midpoint filter. do you have any idea how to write those in C ?

One of the problems in writing a "filter" in C is that without knowing the data type of the elements that the filter will be performing is operations (min/max/med) on, it is relatively a lot more difficult to write it.

For example, how would you write a filter for the following "list" of numbers?


4, 18.21098, 1.314e-8, 97220998756, 1234567890.0987654321 etc.

If you want to "filter" integers, life is a lot easier, huh? It is rather difficult to design a filter that will work with heterogenous types in C (same mechanism supports different types at compile type and homogenous types at runtime for a given instance) and "nearly impossible" (very difficult) to do it using heterogenous types in the same "array" of data points.

Furthermore, in C, even though possible, it is very much "unsafe" compared to a C++ implementation. Building the "safety" needed for any kind of real-world app makes the code very challenging to write and debug...and, if necessary for a threaded world, even more difficult to make thread safe. It is all possible, but (at least) impractical especially for aspiring programmers. Even an accomplished programmer will have substantive difficulty in writing such a beast.

Therefore, if we assume the "easiest thing possible" --that you want to filter some ints--we can suggest some basic, simple code to get you started.

(Note this is a quick hack meant only to demonstrate the concepts, it may not do exactly what you want and is not "production-ready" by any measure.)

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef min
#define min( a, b ) (a<b?a:b)
#endif
#ifndef max
#define max( a, b ) (a>b?a:b)
#endif

void print_int_array_values( int array_of_ints[], const int array_size )
{
    int i = 0;
    for( i = 0; i < array_size; i++ )
    {
        printf( "%3d ", array_of_ints[i] );
    }
    printf( "\n" );
}

void sort( int array_of_ints[], const int array_size )
{
  int i = 0;
  int j = 0;
  int increment = 3;
  int temp = 0;

  while( increment > 0 )
  {
    for( i = 0; i < array_size; i++ )
    {
      j = i;
      temp = array_of_ints[i];
      while( (j >= increment) && (array_of_ints[j - increment] > temp) )
      {
        array_of_ints[j] = array_of_ints[j - increment];
        j = j - increment;
      }
      array_of_ints[j] = temp;
    }
    if( increment/2 != 0 )
    {
      increment = (increment/2);
    }
    else if( increment == 1 )
    {
      increment = 0;
    }
    else
    {
      increment = 1;
    }
  }
}

int minimum( const int array_of_ints[], const int array_size )
{
    int i = array_size;
    int temp = array_of_ints[0];
    if( i > 0 )
    {
        do
        {
            temp = min( temp, array_of_ints[-1 + i] );
        } while( (--i) > 0 );
    }
    else
    {
        printf( "usage error: parameter array_size must be greater than zero!\n" );
    }
    return temp;
}

int maximum( const int array_of_ints[], const int array_size )
{
    int i = array_size;
    int temp = array_of_ints[0];
    if( i > 0 )
    {
        do
        {
            temp = max( temp, array_of_ints[-1 + i] );
        } while( (--i) > 0 );
    }
    else
    {
        printf( "usage error: parameter array_size must be greater than zero!\n" );
    }
    return temp;
}

int median( const int array_of_ints[], const int array_size, int print_arrays )
{
    int i = array_size;
    int* pInts = 0;
    int temp = 0;

    if( i > 0 )
    {
        pInts = malloc( i * sizeof( int ) );
        if( pInts )
        {
            memcpy( pInts, &array_of_ints[0], (i * sizeof( int )) );
            if( print_arrays != 0 )
            {
                printf( "unsorted: " );
                print_int_array_values( pInts, i );
            }
            sort( pInts, i );
            if( print_arrays != 0 )
            {
                printf( "sorted:   " );
                print_int_array_values( pInts, i );
            }
            temp = pInts[((int)i/2)];
        }
    }
    else
    {
        printf( "usage error: parameter array_size must be greater than zero!\n" );
    }

    return temp;
}

int main()
{
    int array_of_ints[] = { 7, 4, 19, -3, 24, 17, 35, 56, 908, -17, 31, 0, 11, 91 };

    int minInt = minimum( array_of_ints, (sizeof( array_of_ints )/sizeof( int )) );
    int maxInt = maximum( array_of_ints, (sizeof( array_of_ints )/sizeof( int )) );
    int medInt = median( array_of_ints, (sizeof( array_of_ints )/sizeof( int )), 1 );
    printf( "minimum = %d\n", minInt );
    printf( "maximum = %d\n", maxInt );
    printf( "median  = %d\n", medInt );

    return 0;
}

// output:

unsorted:   7   4  19  -3  24  17  35  56 908 -17  31   0  11  91
sorted:   -17  -3   0   4   7  11  17  19  24  31  35  56  91 908
minimum = -17
maximum = 908
median  = 19

Note that quicksort would have been much faster than the shell sort used, but for this particular data set, it is a non-issue and shell sort is much easier to implement.

www.cs.bell-labs.com

...is an interesting animation of the various common sorting algorithms in action.


:davis:
  #6  
Old 22-Feb-2012, 01:54
JAZZ_ROCKS JAZZ_ROCKS is offline
New Member
 
Join Date: Feb 2012
Posts: 1
JAZZ_ROCKS is on a distinguished road

Re: Median Filter Coding


CPP / C++ / C Code:
#include<stdio.h>
#include<stdlib.h>
//#include"medianfilter.h"
#include<memory.h>
#include<math.h>

#define OUTPUT_FILE "out.bmp"

long getImageInfo(FILE*,long,int);

int main(int argc,char *argv[])
{

	FILE *bmpInput, *bmpOutput;
	unsigned char *pixel; 
	char signature[2];
	long nRows,nCols,nbits;
	long xpixpeRm,ypixpeRm;
	long nColors;
	long fileSize;
	long vectorSize;
	long nBits;
	long rasterOffset;
	int i, j,k,l,m;
	unsigned char databuff[512][512][3];
	
	if(argc<2)
	{
		printf("Usage: %s <lena512.bmp>\n",argv[0]);
		exit(0);
	}
	
	//Open the specified input file for reading.
	printf("Reading %s ...\n",argv[1]);
	if((bmpInput = fopen(argv[1],"rb"))==NULL)
	{
		printf("Cannot read %s \n", argv[1]);
		exit(0);
	}
	
	//open output file.
	if((bmpOutput = fopen(argv[2],"w+"))==NULL)
	{
		if((bmpOutput = fopen(OUTPUT_FILE,"w+"))==NULL)	//if user hasn't specified the output file use default output filename.
		{
			printf("Cannot read %s \n", argv[1]);
			exit(0);
		}
	}
	
	//position the pointer to the beginning of the file.	
	fseek(bmpInput, 0L, SEEK_SET);

	//read First two characters of the input file.
	for(i=0; i<2; i++)
	{
		signature[i] = (char)getImageInfo(bmpInput,i,1);
	}

	//verify First two character of a BMP image file are BM
	if((signature[0]=='B') && (signature[1]=='M'))
	{
		printf("It is verified that the image is in Bitmap format\n");
	}
	else
	{
		printf("The image is not a BMP format,quitting....\n");
		exit(0);
	}

	//specifies number of bits per pixel in the image.
	nBits = getImageInfo(bmpInput, 28, 2);
	printf("The Image is \t%ld-bits per pixel. \n", nBits);

	//offset from the begining of the file where the pixel data starts.
	rasterOffset = getImageInfo(bmpInput,10,4);
	printf("The pixel Data is at \t%ld byte.\n",rasterOffset);

	//size of the file in bytes.
	fileSize=getImageInfo(bmpInput,2,4);
	printf("File size is \t%ld byte\n",fileSize);

	//number of columns in image.
	nCols = getImageInfo(bmpInput,18,4);
	printf("Width:\t\t%ld\n",nCols);

	//number of rows in image.
	nRows = getImageInfo(bmpInput,22,4);
	printf("Height:\t%ld\n",nRows);

	
	xpixpeRm = getImageInfo(bmpInput,38,4);
	printf("Image has \t%ld pixels per m in x-dir.\n",xpixpeRm);

	ypixpeRm = getImageInfo(bmpInput,42,4);
	printf("Image has \t%ld pixel per m in y-dir.\n",ypixpeRm);

	nColors = 1L<<nBits;
	printf("There are \t%ld number of colors \n",nColors);

	//it is the size of the array required to store the image pixel data.
	vectorSize = nCols*nRows;
	printf("vector Size is \t%ld\n",vectorSize);

	//write the bmp header to the output file.
	i = 0;
	while(i < rasterOffset)
	{
		fputc((char)getImageInfo(bmpInput, i, 1), bmpOutput);
		i++;
	}


	//now declare an 2D array to store & manipulate the image pixel data.
	pixel = (char *) malloc(sizeof(char)*nRows*nCols); 

	//Set all the array value to zero.
	printf("\n\nResetting the pixel array: ");
	i = 0;
	while(i < vectorSize)
	{
		pixel[i] = 0x00;
		i++;
//			printf("%d ", i);
	}
	
	//Read the bitmap data into array:
	printf("\n\nReading the pixel array: ");
	i = 0;
	while(i < vectorSize)
	{
		pixel[i] = (char)getImageInfo(bmpInput, i, 1);
		i++;
//		printf("%d ", i);
	}		
	
	//Display or modify pixel values:
	printf("\n\n Diplaying pixel values: \n\n");
	i = 0;
	j = 0;
	while(i < nRows)
	{
		j = 0;
	while(j < nCols)
		{
			printf("(%d,%d)-%02x\n ",i,j, pixel[i*nRows+j]); //Printing the pixel values.
			j++;
	}
	i++;
}			
	if((nRows!=512)||(nCols!=512)||(nBits!=8)){
printf(" this works only for 512x512 8-color bitmaps\n");
return 0;
}

//int main(void)
//{
//	enum {nCols=512,nRows=512};
//	const float in[nCols*nRows];
//	float out[nCols*nRows];
//	median(out,in,nCols,nRows);
//	printf("the filterd image is:\n");
//	for (int i=0;i<nRows;i++)
//{
//	for (int j=0;j<nCols;j++)
//{
//	printf("%0.f",out[i*nCols+j]);
//	printf("\n");
//}
//
//return 0;
void _medianfilter( element* image,element* result,int nCols,int nRows)
{
for(int m=1;m<nRows-1;++m)
for(int n=1;n<nCols-1;++n)
{
int k=0;
element window[9];
for(int j=m-1;j<m+2;++j)
for(int i=n-1;i<n+2;++i)
	window[k++]=image[j*N+i];
for(int j=0;j<5;++j)
{
int min =j;
for(int l=j+1;l<9;++l)
if(window[l]<window[min])
min=l;
const element temp=window[j];
window[j]=window[min];
window[min]=temp;
result[(m-1)*(nCols-2)+n-1]=window[4];
}
}
}






	//write the modified pixel array to the output file.
	i = 0;
	while(i < vectorSize)
	{
		fputc(pixel[i], bmpOutput);
		i++;
	}
	
	//write the End-Of-File character the output file.
	fputc(EOF, bmpOutput);
	
	printf("\n");
	fclose(bmpInput);
	fclose(bmpOutput);
}

long getImageInfo(FILE* inputFile, long offset, int numberOfChars)
{
	unsigned char *ptrC;
	long value = 0L, temp;
	unsigned char dummy;
	int i;
	
	dummy = '0';
	ptrC = &dummy;

	//position the file pointer to the desired offset.	
	fseek(inputFile, offset, SEEK_SET);

	//read the bytes into values (one byte at a time).
	for(i=1; i<=numberOfChars; i++)
	{
		fread(ptrC,sizeof(char),1,inputFile);
		temp = *ptrC;
		value = (long) (value + (temp<<(8*(i-1))));
			
	}
	
	return(value);
}


hello every i m using this code...this code read the pixel value of the picture and then write it along with the image... bt wen i am applying median filter it showing error... i am new with c programming... can ne 1 plz help me with the programing.. nd tel me what is wrong???
regards..
Last edited by admin : 22-Feb-2012 at 13:31. Reason: Please insert your example C/C++ codes between [CPP] and [/CPP] tags
  #7  
Old 22-Feb-2012, 07:37
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,153
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Median Filter Coding


Quote:
Originally Posted by JAZZ_ROCKS
CPP / C++ / C Code:
#include<stdio.h>
.
.
.
	return(value);
}



... am new with c programming...

I wouldn't want to hurt anyone's feelings, but...

The median filter part of the code that you posted appears to be a hideously butchered, woefully incomplete, and just plain butt-ugly attempt at converting some C++ code that originated at http://www.librow.com/articles/article-1/. The complete code, and a link to download it, is in Appendix A.2.

I don't think it would be impossible to extract the 2-D version of the medianfilter function and convert it to a C program, but the code you posted does not look to me to be a good starting point for learning. It's just too painful to spend more than ten seconds looking at. (But maybe that's just me. Others may be willing and able to help to build on what you have shown. I, personally, don't see the educational value of trying to see and show some way of straightening out that mess.)

My suggestion: Write a main() function and implement enough I/O functionality to actually read the pixels of a bitmap file into a memory array and write it back out. Make sure that the output file is an exact copy of the input file. If you have questions, post again, and show the complete code. Show the exact compiler messages that you don't understand. If the code runs but doesn't give the output you expect (or if it crashes), then explain exactly what happens when you execute the code.

I mean, if you are going to apply some kind of filter to a 512x512 8-bit color bitmap file (as I think is your intent), first of all you have to read the pixel values into an array, right? I don't see any evidence that there is any chance of doing that in the code that you posted. (There have been a few posts, over the years, on gidforums that address this. Maybe you can use the forum's search feature...)

Then look at the code in the C++ filter function in the link that I gave above, and see if any part of it makes sense to you as a beginning C programmer. Most of the specific 2-D code can be converted to C without a huge effort, but I have to ask:

Is this an assignment for some kind of class?

What is the class? C programming? Image processing? Digital Signal Processing? Or what?

Are there any program language prerequisites for the class?

Does the assignment specifically say that the implementation must be in C?


Regards,

Dave

Footnote:
The Original Post in this five-year-old thread gave no context, and my response (and the other response, from The One Whose Name Must Not Be Spoken) might have been appropriate for implementing some kind of function to find the median of a sequence of numbers.

Anyhow...

My response to the original five-year-old question has (practically) nothing to do with the 2-D "median filter" applied to bitmap files as described in the article for which I give a link in this post. Well, actually, the concept of finding the median value by selecting the center member of a sorted set is applicable, but...
__________________
Sometimes I just can't help myself...
Last edited by davekw7x : 22-Feb-2012 at 08:36.
 


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
i really need help in coding this applet.. i gave up !! plz help 123awd Java Forum 7 02-Nov-2005 03:33
PHP/MySQL coding issue cmarti MySQL / PHP Forum 3 26-Jul-2004 08:01
Pls help in this coding. harsha C++ Forum 5 08-Apr-2004 20:48
coding a word with a givin factor funnyf C++ Forum 2 13-Jan-2004 08:32

Network Sites: GIDNetwork · GIDApp · GIDBlog · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 19:56.


vBulletin, Copyright © 2000 - 2014, Jelsoft Enterprises Ltd.