Images : le filtre médian


Description

Le filtre Médian est utilisé en traitement d'images pour palier aux anomalies lors d'une capture d'image.
Si vous avez un vieux scanner, sur vos images peuvent apparaître des pixels n'appartenant pas à celles-ci.

Source / Exemple :


using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace Traitimage.Bitmaps.Traitements
{
	
	public class FormatImage24 
	{
		
		public static void Median(Bitmap bitmap, int n)
		{
			//on crée un bord de n pixel sur l'image avec effet mirroir
			Bitmap imagecloned = CreateBitmapWithMirrorForN(bitmap,n);

			//on détermine la taille de la matrice
			int tailletab = (int)Math.Pow((2*n)+1,2);
			
			int tailletabdemi = tailletab/2;
			//tableaux contenant les pixels contenus dans la matrice
			byte [] tabred = new byte[tailletab];
			byte [] tabgreen = new byte[tailletab];
			byte [] tabblue = new byte[tailletab];

			//Taille de l'image avec le bord en mirroir
			int widthcloned = imagecloned.Width;
			int heightcloned = imagecloned.Height;

			//Taille de l'image à traiter
			int width = bitmap.Width;
			int height = bitmap.Height;

			unsafe
			{
				BitmapData bmpData=bitmap.LockBits(new Rectangle(0,0,width,height),ImageLockMode.ReadWrite,PixelFormat.Format24bppRgb);
				BitmapData bmpDatacloned=imagecloned.LockBits(new Rectangle(0,0,widthcloned,heightcloned),ImageLockMode.ReadWrite,PixelFormat.Format24bppRgb);
			
				byte * newPixel = (byte*)(void *)bmpData.Scan0;
				byte * mPixel = (byte *)(void *)bmpDatacloned.Scan0;

				int indice = 0;//indice pour tableaux
				int loc = 0;//localisation du pixel

				//largeur de numérisation
				int stridecloned = bmpDatacloned.Stride;
				int stride = bmpData.Stride;
			
				//offsets
				int offsetcloned = widthcloned % 4;
				int offset = width % 4;

				mPixel+=(stridecloned*n)+(3*n);//on positionne en n par n

				for (int y = n; y < (heightcloned -n); y++)
				{
					for (int x = n; x < (widthcloned - n); x++)
					{
						//récupération des pixels de la matrice
						for (int k=-n; k<n+1; k++)
							for (int l=-n; l<n+1; l++)
							{
								indice = (l+n)*(2*n+1)+(k+n);
								loc = (k*3)+(l*stridecloned);
								tabred[indice]= mPixel[loc];
								tabgreen[indice]= mPixel[loc+1];
								tabblue[indice]= mPixel[loc+2];
							}
						//tri (on prend le median)
						newPixel[0] = quick_select(tabred,tailletab);
						newPixel[1] = quick_select(tabgreen,tailletab);
						newPixel[2] = quick_select(tabblue,tailletab);
						newPixel+=3;
						mPixel+=3;
					}				
					newPixel+=offset;
					mPixel+=offsetcloned+(2*n*3);
				}
				bitmap.UnlockBits(bmpData);
				imagecloned.UnlockBits(bmpDatacloned);
			}
			imagecloned.Dispose();
		}

		private static byte quick_select(byte[] tab, int n)
		{
			int min, max ; //pointeur sur le min et le max en cours
			int median;
			int m, l, h; //milieu, petit, haut
			min = 0 ;
			max = n-1 ;
			median = (min + max) / 2;
			for (;;) 
			{
				if (max <= min) // 1 seul élément, plus besoin de trier, on renvoie le median
					return tab[median] ;
				if (max == min + 1) // plus que 2 éléments (on trie et on renvoie le median)
				{ 
					if (tab[min] > tab[max])
						inversion(ref tab[min], ref tab[max]) ; //on inverse
					return tab[median] ;
				}
				//on trie les élements min, milieu et max
				m = (min + max) / 2;
				if (tab[m] > tab[max]) inversion(ref tab[m], ref tab[max]) ;
				if (tab[min] > tab[max]) inversion(ref tab[min], ref tab[max]) ;
				if (tab[m] > tab[min]) inversion(ref tab[m], ref tab[min]) ;
				//on inverse le nouveau milieu avec le min+1
				inversion(ref tab[m], ref tab[min+1]) ;
				//on va inverser les elements dans la tranche en cours
				l = min + 1;
				h = max;
				for (;;) 
				{
					do l++; while (tab[min] > tab[l]) ;
					do h--; while (tab[h] > tab[min]) ;
					if (h < l)
						break;
					inversion(ref tab[l], ref tab[h]) ;
				}
				//on mets le milieu en position min à sa bonne place
				inversion(ref tab[min], ref tab[h]) ;
				//on réajuste les pointeurs min et max
				if (h <= median)
					min = l;
				if (h >= median)
					max = h - 1;
			}
		}

		private static void inversion(ref byte a,ref byte  b) 
		{
			byte t=a;
			a=b;
			b=t;
		}

		/// <summary>
		/// Permet de renvoyer une image avec un bord n 
		/// dont ce dernier est le miroir du bord de l'image initiale.
		/// Cette image sert dans le cas d'application de matrice 2*n +1
		/// </summary>
		/// <param name="n">correspond à la bordure supplémentaire en pixel.</param>
		/// <returns></returns>
		public static Bitmap CreateBitmapWithMirrorForN(Bitmap bitmap, int n)
		{
			Bitmap bitmapWithMirror = new Bitmap(bitmap.Width+(n*2),bitmap.Height+(n*2));
			
			//copie de l'image au centre de la nouvelle
			Graphics g = Graphics.FromImage(bitmapWithMirror);
			g.DrawImage(bitmap,n,n,bitmap.Width,bitmap.Height);
			g.Dispose();

			//on va copier les lignes manquantes (recopie des lignes Nord, Sud, Ouest, Est de l'image)
			int width = bitmap.Width;
			int height = bitmap.Height;
			int heightcloned = bitmapWithMirror.Height;
			int widthcloned = bitmapWithMirror.Width;

			unsafe
			{
				BitmapData bmpDatacloned=bitmapWithMirror.LockBits(new Rectangle(0,0,widthcloned,heightcloned),ImageLockMode.ReadWrite,PixelFormat.Format24bppRgb);
				
				byte * newPixel = (byte *)(void *)bmpDatacloned.Scan0;

				//largeur de numérisation
				int stridecloned = bmpDatacloned.Stride;
				int newloc = 0;//localisation des nouveaux pixels ajoutés
				int loc = 0;//localisation des pixels servant à créer le mirroir
				

				for (int i = 1; i<=n;++i)
					for(int x=0;x<width;++x)
					{
						//rangee Nord
						newloc = ((x+n)*3)+((i-1)*stridecloned);
						loc = ((x+n)*3)+((2*n-i+1)*stridecloned);
						newPixel[newloc]= newPixel[loc];
						newPixel[newloc+1]= newPixel[loc+1];
						newPixel[newloc+2]= newPixel[loc+2];
						
						//rangee Sud
						newloc = ((x+n)*3)+((heightcloned-i)*stridecloned);
						loc = ((x+n)*3)+((heightcloned -(2*n-i+1))*stridecloned);
						newPixel[newloc]= newPixel[loc];
						newPixel[newloc+1]= newPixel[loc+1];
						newPixel[newloc+2]= newPixel[loc+2];
					}	
				for (int i=1; i<=n ; ++i)
				{
					
					for(int y=0;y<heightcloned;++y)
					{
						//rangee Ouest
						newloc = ((n-i)*3)+(y*stridecloned);
						loc = ((n+i-1)*3)+ (y*stridecloned);
						newPixel[newloc]= newPixel[loc];
						newPixel[newloc+1]= newPixel[loc+1];
						newPixel[newloc+2]= newPixel[loc+2];

						//rangee Est
						newloc = ((widthcloned-(n-i+1))*3)+(y*stridecloned);
						loc = ((widthcloned-(n+i))*3)+ (y*stridecloned);
						newPixel[newloc]= newPixel[loc];
						newPixel[newloc+1]= newPixel[loc+1];
						newPixel[newloc+2]= newPixel[loc+2];
					}
				}
				bitmapWithMirror.UnlockBits(bmpDatacloned);
			}
			//l'image renvoyee peut être exploitee via des matrices (2*n)+1 X (2*n)+1
			//pas de réduction donc de la taille initiale pour l'image traitée.
			//Une copie en miroir évite les effets de bords
			return bitmapWithMirror;
		}
	}
}

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.