Pregunta

I have the collection that contains images and DCT hash for their. How I can select only similar images using Similarity(long hash, long hashOther) method in LINQ where clause.
This query is not work:

var results = imageCollection
.AsQueryable()
.Where(x=>ImageHash.Similarity(x.Hash, hash) >= 50)
.ToList();

Serialization error occurs.

Thanks!

¿Fue útil?

Solución

Keep in mind that any LINQ query you write against MongoDB must ultimately be translated into an equivalent query in the MongoDB query language. The LINQ query you wrote can't be translated to a raw MongoDB query because this part:

.Where(x=>ImageHash.Similarity(x.Hash, hash) >= 50)

has no equivalent in the MongoDB query language.

What you will have to do is fetch all the Image _id and Hash values client side and run your Similarity criteria client side. Once you have the _id values of all the images that are similar enough you can fetch the images themselves.

Hopefully your query will also include other criteria so that only a subset of the images need to be run through the Similarity criteria client side.

It would look more or less like this:

var matchingIds = collection.FindAllAs<BsonDocument>
    .SetFields("_id", "Hash")
    .AsEnumerable() // force client side evaluation of the rest of the query
    .Where(x => ImageHash.Similarity(x["Hash"].AsByteArray, hash) > 50))
    .Select(x => x["_id"]);
var query = Query.In("_id", matchingIds);
var matchingImages = collection.Find(query);
foreach (var image in matchingImages)
{
    // process matching image
}

Otros consejos

As you say in your comment, have you tried a POCO class?

public class MyImage
{
 [BsonId]
 public ObjectId id {get;set;}    
 public string Hash {get;set;}

}

var results = imageCollection
 .AsQueryable(MyImage)
.Where(x=>ImageHash.Similarity(x.Hash, hash) >= 50)
.ToList();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top