0

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

3
  • I believe the $sort operator takes <field1>: <sort order>, where you have <field1>, <sort order>. Try {'$sort': {'diff': 1}} Commented Jul 30, 2019 at 15:44
  • @It'sNotMe Yup that solved the problem, but now I am getting a new exception <class 'tuple'>: (<class 'pymongo.errors.OperationFailure'>, OperationFailure("Unrecognized pipeline stage name: '$set'"), <traceback object at 0x0EBFFC60>) Commented Jul 30, 2019 at 15:47
  • 1
    @It'sNotMe Thanks alot for seeing that for me! I will try to work on from here, do you mind making it as an answer so I can accept it? Commented Jul 30, 2019 at 15:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.