Distinct subsets from a set
I wrote an extension method which returns me 2-dimensional array of YUV values from a bitmap i.e.:
public static YUV[,] ToYuvLattice(this System.Drawing.Bitmap bm)
{
var lattice = new YUV[bm.Width, bm.Height];
for(var ix = 0; ix < bm.Width; ix++)
{
for(var iy = 0; iy < bm.Height; iy++)
{
lattice[ix, iy] = bm.GetPixel(ix, iy).ToYUV();
}
}
return lattice;
}
Then I need to extract sets with the same U and V components. I.e. Set1 contains all [item1;item2] pairs, Set2 conatains [_item1;_item2] pairs. So I want to get List of Lists.
public IEnumerable<List<Cell<YUV>>> ExtractClusters()
{
foreach(var cell in this.lattice)
{
if(cell.Feature.U != 0 || cell.Feature.V != 0)
{
// other condition to be defined
}
// null yet
yield return null;
}
}
I started with above code but I stuck开发者_如何学C with condition to distinct values.
It sounds like you have an equivalence relation and you want to partition the data. By equivalence relation, I mean:
- A r A
- A r B => B r A
- A r B and B r C => A r C
If that is what you have then this should work.
public static class PartitionExtension
{
static IEnumerable<List<T>> Partition<T>(this IEnumerable<T> source, Func<T, T, bool> equivalenceRelation)
{
var result = new List<List<T>>();
foreach (var x in source)
{
List<T> partition = result.FirstOrDefault(p => equivalenceRelation(p[0], x));
if (partition == null)
{
partition = new List<T>();
result.Add(partition);
}
partition.Add(x);
}
return result;
}
}
Usage:
return this.lattice
.Where( c=> c.Feature.U != 0 && c.Feature.V != 0 )
.Partition((x,y)=>
x.Feature.U == y.Feature.U &&
x.Feature.V == y.Feature.V);
精彩评论