2011-10-19 33 views
3

IList在xy平面上包含一組z樣本(全部爲雙精度)。 GetColor()將任意z轉換爲像素顏色。 我打算縮放IList x和y限制以對應位圖寬度和高度,因爲樣本數量通常不等於像素數量。 樣本作爲光柵掃描收集,因此順序不同。我不知道掃描完成之前有多少個樣本。 有沒有一種巧妙的方法來使用LINQ和/或Lambda表達式爲每個位圖像素找到最接近的IList x和y?如何將IList <T>映射到位圖?

PictureBox pb; 
Bitmap bmp = new Bitmap(pb.Width, pb.Height); 
IList<Sample> samples = new List<Sample>(); 
// ... collect samples ... 
// Find closest sample 
Sample GetSample(int w, int h) 
{ 
    // how to find closest x and y for each w and h? 
} 
// Map samples to bitmap 
for (var w = 0; w < pb.Width; w++) 
{ 
    for (var h = 0; h < pb.Height; h++) 
    { 
     var sample = GetSample(w, h); 
     var color = GetColor(sample.z, samples.Min().z, samples.Max().z); 
     bmp.SetPixel(w, h, color); 
    } 
} 
pb.Image = bmp; 
Color GetColor(double z, double minZ, double maxZ) 
{ 
    var red = (int) (255*(z - minZ)/(maxZ - minZ)); 
    var blue = 255 - red; 
    var green = red*blue/65; 
    return Color.FromArgb(red, green, blue); 
} 
// class Sample 
public class Sample : IComparable<Sample> 
{ 
    public double z { get; set; } 
    public double x { get; set; } 
    public double y { get; set; } 
    int IComparable<Sample>.CompareTo(Sample s) 
    { 
     return z < s.z ? -1 : 1; 
    } 
} 

回答

2

也許我提供的方法會幫助你,它允許找到最接近的數字。

問題找到最接近樣品是處理的情況下,當你有:

w == 1 
h == 1 

Sample(x = 1, y = 8) 
Sample(x = 8, x = 1) 

Which one should be considered as closest? 

用法:

int closestX = this.FindClosest(samples.Select(p => p.x).ToList(), w); 
int closestY = this.FindClosest(samples.Select(p => p.y).ToList(), h); 

方法:

public int FindClosest(IList<int> points, int desiredNumber) 
{ 
    int nearest = -1; 
    int latestDistance = int.MaxValue; 

    foreach (int t in points) 
    { 
     if (t == desiredNumber) 
     { 
      return t; 
     } 

     int currentDistance = Math.Abs(desiredNumber - t); 
     if (currentDistance < latestDistance) 
     {      
      nearest = t; 
      latestDistance = currentDistance; 
     } 
    } 

    return nearest; 
} 
1

請記住,lambda只是一個函數,而Linq大多隻是遍歷將內容應用到函數的集合。將不會有魔術優化發生。

它看起來像你問如何填補這個函數體:

Sample GetSample(int w, int h) 
{ 
    // how to find closest x and y for each w and h? 
} 

和實現應該檢查IList<Sample> samples的內容。你會如何將它寫成簡單的循環代碼?

也許可以通過使用比普通的IList更好的數據結構來優化它。取決於你在搜索samples時需要做什麼。

相關問題