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

时间:2014-12-15 19:53:45

标签: 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)
}

我试过了:

  • grep,grepl,grepRaw:错误 - 模式有长度&gt; 1
  • package rimage:错误,包'rimage'不可用
  • 包光栅:不知道如何使用它来查找图像子集(我是否过度思考了这个?)
  • 包ripa:同样,不知道如何使用它(再次,我是否过度思考这个?)

我一直在this github收集结果,并会不断更新。

谢谢你

MNR

1 个答案:

答案 0 :(得分:5)

实际上,结果是 &#34; easy&#34;这样做的方式。我有幸与图像分析教授共度圣诞节。他花了一分钟来建议使用交叉协方差互相关。两者都作为统计数据包的一部分出现在R中。

>? ccf

以下是它的工作原理:

在上面的示例中,我使用...

导入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")

这会加载带有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 ..

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

> image.main <- sample(1:20,20)
> image.main.sub <- image.main[5:8]

想象一下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

现在,我们可以使用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 

ccf显示不同偏移量(滞后)的两个数据集之间的correlation。值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 

注意滞后的值为1.000匹配!

与此程序相关的是template matching

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

MNR