Reputation: 673
I am trying to find an image with the closest colour in the database given an image using the euclidean algorithm (since I do not really care about the distance, I omit the sqrt). Each item in the database contains the fields r
, g
, b
.
Heres my code to retrieve the result:
r, g, b = utilities.get_avg_rgb(match_image.convert('RGB'))
res = self.database_collection.aggregate([
{'$set': {
'diff': {
'$sum': [{'$pow': [{'$sub': ['$r', r]}, 2]},
{'$pow': [{'$sub': ['$g', g]}, 2]},
{'$pow': [{'$sub': ['$b', b]}, 2]}]
}
}},
{'$sort': {'diff', 1}},
{'$limit': 1}
])
However, I get the following error:
<class 'tuple'>: (<class 'bson.errors.InvalidDocument'>, InvalidDocument("cannot encode object: {1, 'diff'}, of type: <class 'set'>"), <traceback object at 0x0F5483C8>)
I think it says I am trying to encode an object with class set
which it cannot do so (?) but I could not find the reason.
May I know why this happens and how to fix it? Thanks
Upvotes: 0
Views: 983
Reputation: 1260
I believe the $sort
operator takes <field1>: <sort order>
, where you have <field1>, <sort order>
. Try {'$sort': {'diff': 1}}
.
Also, $set
is an update operator and does not appear to be supported in the aggregation pipeline.
Upvotes: 1