开发者

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:

  1. A r A
  2. A r B => B r A
  3. 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜