12

I want to use OpenCV's perceptual hashing functions from Python.

This isn't working.

import cv2
a_1 = cv2.imread('a.jpg')
cv2.img_hash_BlockMeanHash.compute(a_1)

I get:

TypeError: descriptor 'compute' requires a 'cv2.img_hash_ImgHashBase' object but received a 'numpy.ndarray'

And this is failing too

a_1_base = cv2.img_hash_ImgHashBase(a_1) 
cv2.img_hash_BlockMeanHash.compute(a_1_base)

I get:

TypeError: Incorrect type of self (must be 'img_hash_ImgHashBase' or its derivative)

Colab notebook showing this:

https://colab.research.google.com/drive/1x5ZxMBD3wFts2WKS4ip3rp4afDx0lGhi

1

3 Answers 3

14
+50

It's a common compatibility gap that the OpenCV python interface has with the C++ interface (i.e. the classes don't inherit from each other the same way). There are the *_create() static functions for that.

So you should use:

hsh = cv2.img_hash.BlockMeanHash_create()
hsh.compute(a_1)

In a copy of your collab notebook: https://colab.research.google.com/drive/1CLJNPPbeO3CiQ2d8JgPxEINpr2oNMWPh#scrollTo=OdTtUegmPnf2

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

4 Comments

it returns an array, how to get one number?
hash_xor = reduce(lambda x, y: x ^ y, hash[0]) ?
It gives me following error: AttributeError: module 'cv2.cv2' has no attribute 'img_hash'. My opencv-python and opencv-contrib-python version is 4.3.0
Removing opencv-python and reinstalling it, solved the isuue!
11
pip install opencv-python
pip install opencv-contrib-python    #img_hash in this one 

(https://pypi.org/project/opencv-python/)

1 Comment

pip uninstall opencv-python, never both together!
7

Here I show you how to compute 64-bit pHash with OpenCV. I defined a function which returns unsigned, 64-bit integer pHash from a color BGR cv2 image passed-in:

import cv2
    
def pHash(cv_image):
        imgg = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY);
        h=cv2.img_hash.pHash(imgg) # 8-byte hash
        pH=int.from_bytes(h.tobytes(), byteorder='big', signed=False)
        return pH

You need to have installed and import cv2 for this to work.

1 Comment

Is there a way to generate larger than 8-byte hash? for example 16-byte.

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.