Сравнение двух изображений в Python - PullRequest
1 голос
/ 30 октября 2019

Я хочу сравнить два изображения с помощью Python, но я не знаком с этим языком.

У меня есть два изображения одинакового размера. Я должен создать массив, содержащий попиксельное различие двух изображений. Наконец, мне нужно вычислить среднее значение суммы всех значений массива как число с плавающей запятой.

Я могу сделать это с помощью Processing, но я не могу сделать это с помощью Python.

Если два изображения одинаковы, результат, очевидно, будет 0.

Я хотел бы перевести этот код на Python (самое важное - это значение окончательного среднего).

PImage img,img2;
int threshold = 64;

void setup(){
    //size(600,400);
    img = loadImage(args[0]);
    img2 = loadImage(args[1]);
    println(comparison(img,img2));
    exit();
}

PImage binarization(PImage img,int threshold){
    for(int i = 0; i < img.pixels.length; i++){
        if(green(img1.pixels[i]) > threshold) img.pixels[i] = color(255);
        else img.pixels[i] = color(0);
    }
    return img;
}

float comparison(PImage img, PImage img2){

    img.filter(GRAY);
    img2.filter(GRAY);

    img = binarazation(img,threshold);
    img2 = binarization(img2,threshold); 

    int array[] = new int[img.pixels.length];

    for(int i = 0; i < img.pixels.length; i++){
        array[i] = int( abs(green(img.pixels[i]) - green(img2.pixels[i])));
    }

    float average = 0;

        for(int i = 0; i < img.pixels.length; i++){
            average+= array[i];
    }
    average = average/img.pixels.length;

    return average;
}

РЕДАКТИРОВАТЬ ::::

Большое спасибо!

Функция сравнения, которую я разместил ранее, не совсем верна

на самом деле должно появиться изображение (после того, как оно было преобразовано в оттенки серого) с другим изображением (какой алгоритм был применен)

как я могу изменить функцию сравнения, опубликованную elgordorafiki?

Алгоритм Канни для использования в следующем:

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread ('img', 0)
edges = cv2.Canny (img, 100,110)

plt.subplot (2,1,1), plt.imshow (img, cmap = 'gray')
plt.title ('Original Image'), plt.xticks ([]), plt.yticks ([])
plt.subplot (2,1,2), plt.imshow (edges, cmap = 'gray')
plt.title ('Canny Edge Detection'), plt.xticks ([]), plt.yticks ([])

plt.show ()

1 Ответ

0 голосов
/ 30 октября 2019

Как подсказывает @martineau, библиотека визуализации Python - хороший путь. Я лично также думаю, что вы можете использовать numpy и matplotlib в качестве альтернативы. Хорошая вещь о Python заключается в том, что вы можете использовать массив и выполнять операции над всем изображением вместо использования циклов for, которые будут выглядеть лучше и быстрее.

В качестве примера я быстро перенес ваш код на python(не уверен в том, что фильтр там делает и какое значение имеет ваш порог, но остальные должны быть почти такими же)среднее значение будет как-то высоким, возможно, использование значений от 1 до 0 будет легче интерпретировать после, но это зависит от вас).

import numpy as np
import matplotlib.pyplot as plt
import sys

def binarize(img, threshold):

    # create an image with True or False (that can be seen as 1 or 0) and multiply by 255
    binaryimg = (img > threshold).astype(int) * 255
    return binaryimg

def comparison(img1, img2):

    # convert to gray. What's the filter doing?
    gray1 = rgb2gray(img1)
    gray2 = rgb2gray(img2)

    # select a threhsold value and binarize the image
    threshold = 0.5
    gray1_bin = binarize(gray1, threshold)
    gray2_bin = binarize(gray2, threshold)

    # in python you can compute a difference image.
    # so diff will contain in each pixel the difference between the two images
    diff = gray1_bin - gray2_bin

    # the np.mean gives you already sum / number of pixels
    average = np.mean(diff)

    return average

def rgb2gray(col_img):

    # converts images to gray
    weights = np.array([0.3, 0.59, 0.11])
    gray = np.sum([col_img[:, :, i].astype(np.float64) * weights[i] for i in range(3)], axis=0)

    return gray

# the "main" method
if __name__ == "__main__":

    # read the images
    img = plt.imread(sys.argv[1])
    img2 = plt.imread(sys.argv[2])

    result = comparison(img, img2)

    print("The difference between the images is {}".format(result))

Надеюсь, это поможет!

...