2

I wonder how I can create a matrix with pixel colors information from a figure on R. As in the example, the idea is process an grayscale image to a matrix like this:

3x3 pixel image

     [,1]    [,2]    [,3]   
[1,] "Black" "White" "Black"
[2,] "White" "Black" "White"
[3,] "Black" "White" "White"
David Arenburg
  • 91,361
  • 17
  • 137
  • 196

2 Answers2

1

You can use the image function:

## Generating the pixel matrix (1 is black, 0 is white)
my_image <- matrix(c(1,0,1,0,1,0,1,0,0), 3, 3)
## Remove the plot margin
par(mar = c(0,0,0,0))
## Plot the picture
image(my_image, col = c("white", "black"), xaxt = "n", yaxt = "n")
Thomas Guillerme
  • 1,747
  • 4
  • 16
  • 23
0

As I did not find a way to deal with this issue, I created an R package and make it available on CRAN. An example of how to get this information:

# Install package
install.packages("bwimage")

# Load package
library("bwimage")

# Path to an example provided by bwimage package
bush<-system.file("extdata/bush.JPG",package ="bwimage") 

# Convert the image to a binary matrix. For each pixel, the intensity of red, green and blue is averaged and compared to a threshold. If the average intensity is less than the threshold (default is 50%) the pixel will be set as black (1 in the matrix), otherwise it will be white (0).

threshold_color(bush,"jpeg", "frame_fixed",target_width = 15,target_height=15)