Created
September 6, 2016 08:38
-
-
Save lgatto/104563cf38d1202c0764e3d39069cd83 to your computer and use it in GitHub Desktop.
Comparing images by subtracting pixels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library("EBImage") | |
resize_to_smallest <- function(x, y) { | |
dx <- dim(x) | |
dy <- dim(y) | |
w <- min(dx[1], dy[1]) | |
h <- min(dx[2], dy[2]) | |
list(x = EBImage::resize(x, w, h), | |
y = EBImage::resize(y, w, h)) | |
} | |
subtract_distance <- function(x, y) | |
UseMethod("subtract_distance") | |
subtract_distance.Image <- function(x, y) { | |
if (is.character(y) && file.exists(y)) | |
y <- readImage(y) | |
stopifnot(inherits(y, "Image")) | |
if (!identical(dim(x), dim(y))) | |
xy <- resize_to_smallest(x, y) | |
else xy <- list(x, y) | |
sum(EBImage::imageData(xy[[1]] - xy[[2]]) != 0) / prod(dim(xy[[1]])) | |
} | |
subtract_distance.character <- function(x, y) { | |
stopifnot(file.exists(x)) | |
if (!inherits(y, "Image")) { | |
stopifnot(inherits(y, "character")) | |
stopifnot(file.exists(y)) | |
} | |
x <- readImage(x) | |
y <- readImage(y) | |
subtract_distance.Image(x, y) | |
} | |
isSimilar2 <- function(x, y, threshold = 0.001, exact = FALSE) { | |
if (exact) threshold <- 0 | |
if (threshold > 1) threshold <- 1 | |
if (threshold < 0) threshold <- 0 | |
subtract_distance(x, y) <= threshold | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment