user20003920
user20003920

Reputation: 33

How to save a collection of images in grayscale

library(OpenImageR)

I am trying to convert an rgb images into grayscale then save them

path = list.files("/dat",".jpg", 

               full.names = T, all.files = TRUE)

imgr=lapply(path, readImage)

imgs<-lapply(imgr, rgb_2gray)

Below the function that I used but I don't know how to modify it

writeImage(img.fi))

Upvotes: 0

Views: 37

Answers (1)

jay.sf
jay.sf

Reputation: 73437

You may want to use lapply on writeImage() as well.

> library(OpenImageR)
>
> path <- '~/sandbox/animals'
> setwd(path)
>
> fnms <- list.files(path, ".jpg", full.names=TRUE, all.files=TRUE)
> imgr <- lapply(fnms, readImage) |> lapply(rgb_2gray)
> new_fnms <- sub('.jpg', '_gry.jpg', fnms)
> lapply(seq_along(new_fnms), \(i) writeImage(imgs[[i]], new_fnms[i]))
[[1]]
NULL

[[2]]
NULL
> dir()
[1] "pic1_gry.jpg" "pic1.jpg"     "pic2_gry.jpg" "pic2.jpg"

Data:

> urls <- 
  c('https://www.publicdomainpictures.net/pictures/50000/velka/lion-and-lioness-animals.jpg',
    'https://c.pxhere.com/photos/21/01/elephant_animals_water_sri_lanka_proboscis-930457.jpg!d')
> download.file(urls, paste0('~/sandbox/animals/', sprintf('pic%s.jpg', 1:2)))

Upvotes: 1

Related Questions