Using OpenCV's Image Hashing Module from Python
Asked Answered
T

3

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

Turley answered 15/4, 2019 at 9:5 Comment(1)
Take a look at this: pyimagesearch.com/2017/11/27/image-hashing-opencv-pythonLactam
B
12

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

Broad answered 21/4, 2019 at 20:29 Comment(4)
it returns an array, how to get one number?Fauman
hash_xor = reduce(lambda x, y: x ^ y, hash[0]) ?Fauman
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.0Chronometer
Removing opencv-python and reinstalling it, solved the isuue!Chronometer
G
10
pip install opencv-python
pip install opencv-contrib-python    #img_hash in this one 

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

Gourde answered 16/7, 2019 at 9:55 Comment(0)
L
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.

Lester answered 24/1, 2021 at 1:28 Comment(1)
Is there a way to generate larger than 8-byte hash? for example 16-byte.Remembrancer

© 2022 - 2024 — McMap. All rights reserved.