使用R将图像子集与较大的图像匹配

mnr*_*mnr 0 r image-processing

我正在使用R进行一些非常简单的图像分析.具体来说,我正在尝试确定一个图像是否是另一个图像的裁剪版本.

在R中必须有一种"简单"的方法来做到这一点 - 但我找不到它.我怀疑我过度思考这个问题 - 所以寻找关于我缺少的指导.

具体来说,请考虑以下事项

install.packages("jpeg")
library(jpeg)

image.main <- readJPEG("path to a jpeg image")
image.main.sub <- readJPEG("path to another jpeg image, cropped version of the first")

if (someMagicFunctionThatFindsSubImage(image.main,image.main.sub)) {
    # TRUE - image.main.sub is a subset of image.main 
} else {
    # FALSE - image.main.sub is NOT a subset of image.main
}

someMagicFunctionThatFindsSubImage <- function (bigImage,smallImage) {
  # the matrix of values that represent smallImage is also present
  # in the matrix of values that represent bigImage
  # bigImage and smallImage can be megabytes in size
  # bigImage and smallImage can be limited to RGB Jpeg data (array of X,Y and 3 layers)
}
Run Code Online (Sandbox Code Playgroud)

我试过了:

  • grep,grepl,grepRaw:error - pattern的长度> 1
  • package rimage:错误,包'rimage'不可用
  • 包栅格:不知道如何使用它来查找图像子集(我是否过度思考?)
  • 包ripa:同样,不知道如何使用它(再次,我是否过度思考?)

我一直在这个github收集结果,并会保持更新.

谢谢

MNR

mnr*_*mnr 5

事实上,它原来有一个"容易"的方式来做到这一点.我有幸与图像分析教授共度圣诞节.他花了一分钟时间建议使用交叉协方差互相关.两者都作为统计数据包的一部分出现在R中.

>? ccf
Run Code Online (Sandbox Code Playgroud)

以下是它的工作原理:

在上面的示例中,我使用...导入JPEG图像

> install.packages("jpeg")
> library(jpeg)

> image.main <- readJPEG("path to a jpeg image")
> image.main.sub <- readJPEG("path to another jpeg image, cropped version of the first")
Run Code Online (Sandbox Code Playgroud)

这会加载带有jpeg图像内容的image.main和image.main.sub - 就像这样......

> str(image.main)
num [1:3456, 1:5184, 1:3] 0.839 0.839 0.827 0.831 0.835 ..
Run Code Online (Sandbox Code Playgroud)

为了便于讨论,我将创建此数据的高度简化版本.忍受我一秒钟......

> image.main <- sample(1:20,20)
> image.main.sub <- image.main[5:8]
Run Code Online (Sandbox Code Playgroud)

想象一下image.main包含一个非常小的jpeg图像.

image.main.sub包含image.main的子集.

他们看起来像这样......

> image.main
[1]  2 10  8  9 19  5 11  3  7 16 20 15  6 14 17  1 13 18 12  4
> image.main.sub
[1] 19  5 11  3
Run Code Online (Sandbox Code Playgroud)

现在,我们可以使用ccf函数确定image.main.sub位于image.main中的位置

> ccf(image.main,image.main.sub,plot=FALSE)

Autocorrelations of series ‘X’, by lag

   -3     -2     -1      0      1      2      3 
0.440 -0.332  0.295 -0.935  0.327 -0.010  0.215 
Run Code Online (Sandbox Code Playgroud)

ccf显示了不同偏移量(滞后)下两个数据集之间的相关性.值1表示100%相关.如果我们将image.main配置为匹配image.main.sub,请观察结果...

> ccf(image.main[5:8],image.main.sub,plot=FALSE)

Autocorrelations of series ‘X’, by lag

    -3     -2     -1      0      1      2      3 
-0.398  0.281 -0.382  1.000 -0.382  0.281 -0.398 
Run Code Online (Sandbox Code Playgroud)

注意滞后0的值为1.000匹配!

与此过程相关的是模板匹配.

我已经在我的github页面上构建了整个解决方案.

MNR