Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using OpenCV's Image Hashing Module from Python

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

like image 631
andandandand Avatar asked Apr 15 '19 09:04

andandandand


3 Answers

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

like image 75
stav Avatar answered Oct 19 '22 17:10

stav


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.

like image 35
A. Genchev Avatar answered Oct 19 '22 17:10

A. Genchev


pip install opencv-python
pip install opencv-contrib-python    #img_hash in this one 

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

like image 8
whomm Avatar answered Oct 19 '22 18:10

whomm