How to convert image to point data for ggplot2 scatterplot

I recently found a package on Github where the developer analyzed data on 248 parts of the Spy vs Spy comic by Antonio Prohias appearing in Mad Magazine.

He analyzes some basic intelligence, calculates a running net score of Black Spy wins, and then conducts a non-parametric test (Wald Wolfowitz test) to look at the clusters of consecutive wins of one of the spies to find out if Prochias kept the balance of points, changing the previous result, or, possibly he chose the favorites.

While I found this fun exercise, I was most interested in the spy plot.

Spy vs. Spy

The exact data for the Spy plot is actually taken from the MATLAB spy() Easter egg , and the developer places these data points in R as a tibble :: tribble .

My question is: how to create point data from an image? Is it possible to perform edge detection in R using imager() to get the circuit

enter image description here

And then somehow convert the data of this image to tbl_df ? I am not familiar with raster arrays, but perhaps the answer lies in something similar?

+5
source share
1 answer

We can use imager::cannyEdges to get the edges, and then put the coordinates in the data frame.

 library('ggplot2') library('imager') plot(boats) 

boats

 img <- cannyEdges(boats) plot(img) 

edge

It looks like img is a logical array with 4 dimensions.

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

I just want two dimensions, so I will drop the two dimensions.

 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 can convert this matrix to a coordinate list.

 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 

Now it can be built.

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

enter image description here

+4
source

Source: https://habr.com/ru/post/1274950/


All Articles