2011-03-23 64 views
1

我正在處理包含圖像處理的任務。我發現,我一遍又一遍地重複一個代碼(干預警報),我只是好奇,是否有辦法避免它。在使用圖像(委託應用程序)時減少冗餘代碼?

的代碼是:

for (int x = 0; x < image.Width; x++) 
{ 
    for (int y = 0; y < image.Height; y++) 
    { 
     byte pixelValue = Convert.ToByte(Byte.MaxValue * image.GetPixel(x, y).GetBrightness()); 
     //Do something with pixelValue 
    } 
} 

的各種各樣的任務是廣泛,一旦我創建直方圖,然後我在閾值處理圖像等....我覺得有可能是使用委託一些解決方案,但我對他們的經驗有限,顯然這不是最重要的想法。

你能否在.NET Framework 2.0中提出解決方案?

感謝

回答

0

你可以做這樣的:

public static void ProcessPixelValues(Image image, Action<int, int, byte> processPixelValue) 
{ 
    for (int x = 0; x < image.Width; x++) 
    { 
     for (int y = 0; y < image.Height; y++) 
     { 
      byte pixelValue = Convert.ToByte(Byte.MaxValue * image.GetPixel(x,   y).GetBrightness()); 

      processPixelValue(x, y, pixelValue); 
     } 
    } 
} 

public static void PrintPixelValuesOfImage(Image image) 
{ 
    Action<int, int, byte> processPixelValue = 
     (x, y, pixelValue) => Console.WriteLine("The pixel value of [{0},{1}] is {2}", x, y, pixelValue); 

    ProcessPixelValues(image, processPixelValue); 
} 

C#2.0代碼

public delegate void ProcessPixelValueCallback(int x, int y, byte pixelValue); 

public static void ProcessPixelValues(Image image, ProcessPixelValueCallback processPixelValue) 
{ 
    for (int x = 0; x < image.Width; x++) 
    { 
     for (int y = 0; y < image.Height; y++) 
     { 
      byte pixelValue = Convert.ToByte(Byte.MaxValue * image.GetPixel(x,   y).GetBrightness()); 

      processPixelValue(x, y, pixelValue); 
     } 
    } 
} 

public static void PrintPixelValuesOfImage(Image image) 
{ 
    ProcessPixelValueCallback processPixelValue = delegate(int x, int y, byte pixelValue) 
    { 
     Console.WriteLine("The pixel value of [{0},{1}] is {2}", x, y, pixelValue); 
    }; 

    ProcessPixelValues(image, processPixelValue); 
} 
1

我不知道2.0,但4.0,很可能會沿着

public void VisitPixels(Image image, Action<int,int,Pixel> func){ 
    for (int x = 0; x < image.Width; x++) 
    { 
    for (int y = 0; y < image.Height; y++) 
    { 
     func(x,y,image.GetPixel(x,y)); 
    } 
    } 
} 

線的東西。如果你想有一個返回值,它可以得到比較麻煩一些,但你可以或許認爲它喜歡或者是MapFold

地圖

僞:

public T[][] MapPixels<T>(Image image, Func<int,int,Pixel,T> func){ 
    var ret = new T[image.Width][image.Height]; 
    for (int x = 0; x < image.Width; x++) 
    { 
    for (int y = 0; y < image.Height; y++) 
    { 
      ret[x][y] = func(x,y,image.GetPixel(x,y))); 
    } 
    } 
    return ret; 
} 

public T FoldLPixels<T>(Image image, Func<T,Pixel,T> func, T acc){ 
    var ret = acc; 
    for (int x = 0; x < image.Width; x++) 
    { 
    for (int y = 0; y < image.Height; y++) 
    { 
      ret = func(ret,image.GetPixel(x,y)); 
    } 
    } 
    return ret; 
} 

然後,您可以例如獲得的平均亮度,如:

var avgBright = FoldLPixels(image, 
          (a,b)=>a+b.GetBrightness(), 
          0)/(image.Width+image.Height);