Iluvatar546
Iluvatar546

Reputation: 3

Not able to use the readImage function in R

I have downloaded the latest R package and am using RStudio and am trying to convert a pgm image into a csv file and am using a readImage function. Although any time I do
img <- readImage(file) where file is the filepath

I get

Error in readImage(file) : could not find function "readImage"

Is there some other pack I need to download or am I using it wrong?

Upvotes: 0

Views: 1076

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You can use the magick package to read pgm files.

First, you need to do:

install.packages("magick")

Now you call

library(magick)

In my case, I have a pgm file in my R home directory, so I make the file path with:

file <- path.expand("~/cat.pgm")

Now I can read the image and convert it into a matrix of RGB strings by doing:

img <- image_read(file)
ras <- as.raster(img)
mat <- as.matrix(ras)

To write this to csv format, I can do:

write.csv(mat, "cat.csv", row.names = FALSE)

So now I have the image saved as a csv file. To read this back in, and prove it works, I can do:

cat_csv <- read.csv("cat.csv")
cat_ras <- as.raster(as.matrix(cat_csv))
plot(cat_ras)

Note though that the csv file is very large - 9MB, which is one of the reasons why it is rarely a good idea to store an image as csv.

Created on 2022-02-05 by the reprex package (v2.0.1)

Upvotes: 3

Related Questions