如何将图像转换为 ggplot2 散点图的点数据

How to convert an image into point data for ggplot2 scatterplot

我最近发现了一个 package on Github,其中开发人员分析了 Antonio Prohias 在 Mad Magazine 中出现的 248 期间谍与间谍漫画的粉丝精选数据。

他进行了一些基本的探索性数据分析,计算了 运行 Black Spy 胜利的净得分,然后运行非参数测试(Wald Wolfowitz 测试)来查看连续胜利的集群间谍,以确定 Prohias 是否通过扭转先前的结果来保持比分平衡,或者他是否可能选择了最爱。

虽然我觉得这是一个有趣的练习,但我对间谍阴谋最感兴趣。

间谍图的点数据实际上来自MATLAB easter egg spy() package and the dev put this point data into R as a tibble::tribble

我的问题是如何从图像创建点数据?是否可以做edge detection in R with imager()得到大纲

然后以某种方式将此图像数据转换成tbl_df?我不熟悉位图数组,但也许答案是这样的?

我们可以使用imager::cannyEdges获取边缘,然后将坐标放入数据框中绘制。

library('ggplot2')
library('imager')

plot(boats)

img <- cannyEdges(boats)
plot(img)

看起来img是一个4维的逻辑数组。

dim(img)
# [1] 256 384   1   3

我只想要两个维度,所以我将放弃其中两个维度。

img <- img[, , 1, 1]
img[1:8, 1:8]
#       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]
# [1,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [2,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [3,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [4,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [5,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [6,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [7,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [8,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

which可以把这个矩阵转换成坐标列表

coords <- which(img, arr.ind = T)
head(coords)
#      row col
# [1,] 255   1
# [2,] 255   2
# [3,] 255   3
# [4,] 255   4
# [5,] 255   5
# [6,] 255   6

现在可以绘制了。

df <- data.frame(x = coords[,1], y = coords[,2])

ggplot(df, aes(x, -y)) +
  geom_point()