Compare two images python

How to compare two images in OpenCV Python?

To compare two images, we use the Mean Square Error (MSE) of the pixel values of the two images. Similar images will have less mean square error value. Using this method, we can compare two images having the same height, width and number of channels.

Steps

You can use the following steps to compare two images using OpenCV −

Import the required library. In all the following Python examples, the required Python library is OpenCV. Make sure you have already installed it.

Read the input images using cv2.imread() and convert it to grayscale. The height, width and number of channels of the images must be the same.

img1 = cv2.imread('panda.png') img2 = cv2.imread('panda1.png') img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

Define a function to compute the Mean Squared Error between two images.

def mse(img1, img2): h, w = img1.shape diff = cv2.subtract(img1, img2) err = np.sum(diff**2) mse = err/(float(h*w)) return mse

Compute the Mean Squared Error (Matching error) between the images.

Print the image matching error (mse) and display the image difference.

print("Image matching Error between the two images:", mse) cv2.imshow("Contour", img) cv2.waitKey(0) cv2.destroyAllWindows()

Print the result value, the image shape matching metric. The lower the value, the better matching it is.

print("Matching Image 1 with Image 2:", ret12)

Let’s have a look at some examples for a better understanding.

We will use the following images as the Input File in the examples below.

Example 1

In this example, we create a simple Artificial Neural Network with four layers without forward function.

# import required libraries import cv2 import numpy as np # load the input images img1 = cv2.imread('panda.jpg') img2 = cv2.imread('panda1.jpg') # convert the images to grayscale img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # define the function to compute MSE between two images def mse(img1, img2): h, w = img1.shape diff = cv2.subtract(img1, img2) err = np.sum(diff**2) mse = err/(float(h*w)) return mse, diff error, diff = mse(img1, img2) print("Image matching Error between the two images:",error) cv2.imshow("difference", diff) cv2.waitKey(0) cv2.destroyAllWindows()

Output

On execution, it will produce the following output on the console −

Image matching Error between the two images: 3.0696934396076028

And we get the following window showing the difference between the two images −

Читайте также:  Node js создать html

Example 2

In this Python program, we compare three images.

import cv2 import numpy as np import matplotlib.pyplot as plt img1 = cv2.imread('panda.jpg') img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) h, w = img1.shape img2 = cv2.imread('panda1.jpg') img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) img3 = cv2.imread('bike.jpg') img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY) def error(img1, img2): diff = cv2.subtract(img1, img2) err = np.sum(diff**2) mse = err/(float(h*w)) msre = np.sqrt(mse) return mse, diff match_error12, diff12 = error(img1, img2) match_error13, diff13 = error(img1, img3) match_error23, diff23 = error(img2, img3) print("Image matching Error between image 1 and image 2:",match_error12) print("Image matching Error between image 1 and image 3:",match_error13) print("Image matching Error between image 2 and image 3:",match_error23) plt.subplot(221), plt.imshow(diff12,'gray'),plt.title("image1 - Image2"),plt.axis('off') plt.subplot(222), plt.imshow(diff13,'gray'),plt.title("image1 - Image3"),plt.axis('off') plt.subplot(223), plt.imshow(diff23,'gray'),plt.title("image2 - Image3"),plt.axis('off') plt.show()

Output

On execution, the above Python program will produce the following output on the console −

Image matching Error between image 1 and image 2: 3.0696934396076028 Image matching Error between image 1 and image 3: 23.37356529736358 Image matching Error between image 2 and image 3: 24.15752299202943

And we get the following window, showing the difference among the images −

Notice that the Matching error between the Image1 and Image2 is less in comparison to the matching error between Image 1 & 3 and between Image 2 & 3. So, Image 1 and Image 2 are more similar.

Читайте также:  Css background image cropping

Источник

Python. Как сравнить фотографии?

Наверняка у каждого из Вас есть большой домашний архив фотографий, а в нем лежат собственные снимки и фотографии, которыми с Вами поделились родственники. Просматривая свою фототеку, Вы наткнулись на дубли и тут же возник вопрос – сколько же еще таких? В этой статье я поделюсь тем, как я решал свою задачу по поиску одинаковых фотографий.

Совсем недавно у меня появилась интересная задача – необходимо было найти одинаковые фотографии на разных объектах недвижимости. Т.е. к объектам недвижимости расположенных с разным местоположением крепилась одна и та же фотография, может ошибочно, может специально, но такие объекты надо было найти. И я хотел бы поделиться тем, как я решал эту задачу. Для примера у Вас может быть домашняя фототека.

Посмотрев просторы интернета, первым делом на глаза мне попалась библиотека OpenCV, эта библиотека имеет интерфейсы на различных языках, среди которых Python, Java, C++ и Matlab. Мне стало интересно, есть ли у Python стандартная библиотека для работы с изображениями и вот она – Pillow. Это форк PIL, которая успешно развивается и был принят в качестве замены оригинальной библиотеки. Свой выбор я остановил на ней.

Начнем работу с библиотекой, и попробуем открыть файл и показать его.

from PIL import Image #указываем необходимое имя файла im=Image.open(‘cbcf449ffc010b9f958d611e787fa48092ac31841.jpg’) # Покажет нам изображение. im.show()

Данный скрипт откроет нам изображение. Почитав документацию, я нашел функцию, которая по пикселям сравнивает два изображения и выдает разницу. Функция называется difference и находится в модуле ImageChops. Что бы показать принцип работы функции, для примера возьмем фотографию и добавим на нее какой-нибудь текст:

from PIL import Image, ImageChops image_1=Image.open(’06ebe74e5dfc3bd7f5e480cf611147bac45c33d2.jpg’) image_2=Image.open(’06ebe74e5dfc3bd7f5e480cf611147bac45c33d2_text.jpg’) result=ImageChops.difference(image_1, image_2) result.show() #Вычисляет ограничивающую рамку ненулевых областей на изображении. print(result.getbbox()) # result.getbbox() в данном случае вернет (0, 0, 888, 666) result.save(‘result.jpg’)

result.show() вернет разницу в пикселях. Так же прошу обратить внимание на result.getbbox(), функция либо вернет рамку где расходятся пиксели, либо вернет None если картинки идентичны. Если мы сравним первую картинку саму с собой, то получим полностью черное изображение.

Читайте также:  Lessonup ru login php

Напишем простенькую функцию по сравнению двух картинок:

def difference_images(img1, img2): image_1 = Image.open(img1) image_2 = Image.open(img2) result=ImageChops.difference(image_1, image_2).getbbox() if result==None: print(img1,img2,’matches’) return

Теперь необходимо подумать над алгоритмом перебора имеющихся изображений.

path=’images/’ #Путь к папке где лежат файлы для сравнения imgs=os.listdir(path) check_file=0 #Проверяемый файл current_file=0 #Текущий файл while check_file

Данный алгоритм перебирает все файлы в папке и сравнивает их между собой исключая проверку между собой и файлы, которые уже были проверены на совпадение.

А если файлов для сравнения очень много и их обработка очень долгая? Можно пойти двумя способами:

Первый способ простой, в нашу функцию difference_images добавляем несколько строк:

def difference_images(img1, img2): image_1 = Image.open(img1) image_2 = Image.open(img2) size = [400,300] #размер в пикселях image_1.thumbnail(size) #уменьшаем первое изображение image_2.thumbnail(size) #уменьшаем второе изображение #сравниваем уменьшенные изображения result=ImageChops.difference(image_1, image_2).getbbox() if result==None: print(img1,img2,’matches’) return

Второй способ уже сложнее и более интересный, потому что нужно будет управлять и потоками, и очередями, так же нужно будет переписать часть кода. Для этого нам понадобятся следующие библиотеки threading и Queue (подробней можно почитать в интернете), ниже приведен готовый код с внесенными изменениями, я постарался прокомментировать все действия что бы было понятно:

class diff_image(threading.Thread): #класс по сравнению картинок. «»»Потоковый обработчик»»» def __init__(self, queue): «»»Инициализация потока»»» threading.Thread.__init__(self) self.queue = queue def run(self): «»»Запуск потока»»» while True: # Получаем пару путей из очереди files = self.queue.get() # Делим и сравниваем self.difference_images(files.split(‘:’)[0],files.split(‘:’)[1]) # Отправляем сигнал о том, что задача завершена self.queue.task_done() def difference_images(self, img1, img2): image_1 = Image.open(img1) image_2 = Image.open(img2) size = [400,300] #размер в пикселях image_1.thumbnail(size) #уменьшаем первое изображение image_2.thumbnail(size) #уменьшаем второе изображение result=ImageChops.difference(image_1, image_2).getbbox() if result==None: print(img1,img2,’matches’) return def main(path): imgs=os.listdir(path) #Получаем список картинок queue = Queue() # Запускаем поток и очередь for i in range(4): # 4 — кол-во одновременных потоков t = diff_image(queue) t.setDaemon(True) t.start() # Даем очереди нужные пары файлов для проверки check_file=0 current_file=0 while check_file

В результате мы получили готовый алгоритм для поиска одинаковых картинок, а так же постарались ускорить обработку файлов двумя способами. Завершив свою задачу, я обнаружил 1227 совпадений в выборке из 6616 картинок.

Надеюсь, моя статья была полезна. Спасибо за внимание.

Источник

Оцените статью