Import the libraries and load Sift and Flann objects
From Line 1 to Line 3 we import the libraries.
We added a new library glob, which we need to read all the files from a specific folder. It’s by default installed in python, so you don’t need to do anything, just import it.
From Line 7 to Line 13 we load the objects Sift and Flann and we detect the Keypoints and descriptors of the original image.
import cv2
import numpy as np
import glob
original = cv2.imread("original_golden_bridge.jpg")
# Sift and Flann
sift = cv2.xfeatures2d.SIFT_create()
kp_1, desc_1 = sift.detectAndCompute(original, None)
index_params = dict(algorithm=0, trees=5)
search_params = dict()
flann = cv2.FlannBasedMatcher(index_params, search_params)
Load Images and Titles
On Line 16 we create an empty array where we’re going to load later all the images.
On Line 17 we create an empty array where we’re going to load the titles of the images.
On Line 18 we loop trough all the images inside the folder “images”.
On Line 19 we load each image and then we add title and image to the arrays we created before.
# Load all the images
all_images_to_compare = []
titles = []
for f in glob.iglob("images\*"):
image = cv2.imread(f)
titles.append(f)
all_images_to_compare.append(image)
Find similarities and print the result
On Line 23 We loop trough all the images loaded and the titles.
From Line 24 to Line 31 we check if the images are completely equal. If they are, we break the loop, as it’s pointless to check for similarity if we already know that they are equal, and we go to next image.
From Line 35 to Line 53 we check the similarity between the images and we print the result.
for image_to_compare, title in zip(all_images_to_compare, titles):
# 1) Check if 2 images are equals
if original.shape == image_to_compare.shape:
print("The images have same size and channels")
difference = cv2.subtract(original, image_to_compare)
b, g, r = cv2.split(difference)
if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
print("Similarity: 100% (equal size and channels)")
break
# 2) Check for similarities between the 2 images
kp_2, desc_2 = sift.detectAndCompute(image_to_compare, None)
matches = flann.knnMatch(desc_1, desc_2, k=2)
good_points = []
for m, n in matches:
if m.distance > 0.6*n.distance:
good_points.append(m)
number_keypoints = 0
if len(kp_1) >= len(kp_2):
number_keypoints = len(kp_1)
else:
number_keypoints = len(kp_2)
print("Title: " + title)
percentage_similarity = len(good_points) / number_keypoints * 100
print("Similarity: " + str(int(percentage_similarity)) + "\n")

Hi there, I’m the founder of Pysource.
I’m a Computer Vision Consultant, developer and Course instructor.
I help Companies and Developers to build efficient computer vision software.
Hi Theraider747,
I find your job very very good and I trying to follow your tutorial for compare images.
I completed each step in : https://pysource.com/2019/03/15/how-to-install-python-3-and-opencv-4-on-windows/
and installed PyCharm 2019.1
I solved this first error :
sift = cv2.xfeatures2d.SIFT_create()
AttributeError: module ‘cv2.cv2’ has no attribute ‘xfeatures2d’
Installed opencv-contrib-python-headless module, but now I find other issue :
sift = cv2.xfeatures2d.SIFT_create()
cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function ‘cv::xfeatures2d::SIFT::create’
Can you hep me to solve this second error ?
Thanks a lot
Alessandro
Hi Alessandro,
It turned out that in the latest version of Opencv by default The SIFT algorythm doesn’t work.
The easiest solution is to install an older version of opencv.
You can isntall Opencv 3.4.1 + Contrib for example and it will work.
Thanks a lots!
OpenCV 3.4.1 and Py 2.7 >> RUN !! 🙂
Thanks for tutotarial:
I face this error,
if m.distance < 0.6*n.distance:
^
SyntaxError: invalid syntax
That was just an error on the source code here on the website. I’ve just fixed it.
I was trying to execute the above program,it worked perfectly with your given images,but when i captured images from pi camera and try to compare,it was not able to compare and it is showing the error called “killed”
any solution for this??
I had tried your code out works only get this error cant seem to find solution:
matches = flann.knnMatch(des1,des2, k=2)
cv2.error: OpenCV(3.4.2) /home/pi/opencv-python/opencv/modules/flann/src/miniflann.cpp:487: error: (-215:Assertion failed) (size_t)knn size() in function ‘runKnnSearch_’
if you have any help
Hello Sir will it work for faces!?
I think the greater-than sign is pointing the wrong way in this tutorial – I was getting results that showed that duplicate.jpg had 0% similarity to original_golden_bridge.jpg (which can’t be right). I changed this line `if m.distance > 0.6*n.distance:` to this: `if m.distance < 0.6*n.distance:`, and it all worked out. Thanks for the great tutorials.
can you provide me the source for above video
Suppose we are working with the frames of two videos, is it possible to compare them simultaneously? You have shown to compare a single photo with multiple other photos which are different versions of that photo. Can we compare them frame by frame proceeding forward? Please help me.
Same question
Hi – i used Shi-Tomasi detector and FlannMatcher for Features matching of two images.but Pycharm Give this error:
matches = flann.knnMatch(corners1, corners2, k=1)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-cff9bdsm\opencv\modules\flann\src\miniflann.cpp:315: error: (-210:Unsupported format or combination of formats) in function ‘cv::flann::buildIndex_’
> type=13
Please help me