I have looked at previous posts. Especially this one. I see the code is this
library(animation)
## make sure ImageMagick has been installed in your system
saveGIF({
for (i in 1:10) plot(runif(10), ylim = 0:1)
})
I installed ImageMagick (after much confusion).
I ran the above code, and do not see anything happening? I have two images on my computer saved in a file. I want to combine them to create a short gif. How do I go about doing this? What portion of the above code combines multiple images that are saved on my computer? How do I go about doing this using the animation library and imagemagick?
I am running into a wall here. Any help will be greatly appreciated.
You can do it using ImageMagick, as follows:
install.packages("magick")
library(magick)
list.files(path = "<<path to your images>>", pattern = "*.png", full.names = T) %>%
image_read %>% # reads each image file
image_join() %>% # joins image
image_animate(fps=2) %>% # animates, can opt for number of loops
image_write("merged_pngs.gif")
Hope it helps.
Related
I am new to this platform and I hope someone can help me.
I have imported some pdf files into Rstudio using the pdftools library. Now I want to make structured columns of this text. I just can't seem to get the structure right.
This is an example of one file added that I imported. I want to make the yellow shaded lines in a data table.
This is the outcome I would ultimately like to have.
Now I have entered the code below, but I can't get it into a data table.
library(pdftools)
library(stringr)
library(dplyr)
# load the PDF-files into Rstudio
files <- list.files(pattern = "pdf$", full.names = TRUE)
# make a list of the PDF-files
filestext <- lapply(files, pdf_text)
# remove "\n"
filestext <- str_split(filestext, pattern = "\n")
This is the result I get:
Does anyone know the easiest way to solve this?
I would also give https://sensible.so a shot. We have some great documentation and a free plan just for projects like this. Plus, when you sign up there are some tutorials to help you understand how to extract different types of data. I bet you can have this extracted into a clean JSON object in no time.
I want to read 12 images at a time in R.
I don't know how to do it. I am complete new to working on images in R.
How can I read couple of images from a folder in my system?
I am using windows10 operating system. RAM 8 gb. CORE i5 processor.
GPU is Intel(R) HD Graphics 620.
I am able to read only single image in R and that image is displaying as numeric values. I tried to convert it into raster format and then tried to print image to view the image. But I am still finding the color codes in values but not the image in print.
Can anyone help me on this?
Thanks a lot.
install.packages("magick")
library(magick)
install.packages("rsvg")
install.packages("jpeg")
library(jpeg)
img <- readJPEG("C:/Users/folder/Abc.jpg", native = FALSE)
img1 <- as.raster(img, interpolate = F)
print(img1)
I want to read couple of images at a time into R console and want to view or print images.
The suggested duplicate gives you the basics for how to read in a number of files at once, but there are a few potential gotchas, and it won't help you with displaying the images.
This first bit is purely to set up the example
library(jpeg)
library(grid)
# Create a new directory and move to it
tdir <- "jpgtest"
dir.create(tdir)
setwd(tdir)
# Copy the package:jpeg test image twice, once as .jpg and once as .jpeg
# to the present working directory
file.copy(system.file("img", "Rlogo.jpg", package="jpeg"),
to=c(file.path(getwd(), "test.jpg"), file.path(getwd(), "test.jpeg")))
Then we can list the files, either using a regex match, or choose them interactively, then read and store the images in a list.
# Matches any file ending in .jpg or .jpeg
(flist <- list.files(pattern="*\\.jp[e]?g$"))
# Interactive selection
flist <- file.choose()
jpglist <- lapply(flist, readJPEG)
To display the images I tend to use grid, but there are a number of alternatives.
grid.raster(jpglist[[1]], interpolate=FALSE)
Remove temporary directory
setwd("..")
unlink(tdir)
I wanted to do something I thought simple, but... well, I failed repetitively.
I want to create a gif or a video (.avi) from pictures in a folder with R.
I can list the path and the names of the pictures (e.g. "./folder/1.jpg" "./folder/2.jpg" "./folder/3.jpg" "./folder/4.jpg" )
I just wanted to put them the one after the other and create a video or gif file (I will treat them frame by frame later, so the speed is not important)
I found a solution with SaveGIF, it works with plots in R but I didn't find the way to use it with external jpg.
Otherwise, there was this solution with image_animate "Animated graphics", but again, I didn't manage.
Do somebody already have a solution to do that?
Thank you very much for your help!
You can do it with the magick package, which gives you access to ImageMagick functions. For example, if the frames of your movie are in files named
frames <- paste0("folder/", 1:100, ".jpg")
then you would create a movie using
library(magick)
m <- image_read(frames)
m <- image_animate(m)
image_write(m, "movie.gif")
You could choose to write to other formats as well, just by changing the filename, or using other arguments to image_write().
A better solution in my oppinion is using the av package.
example:
list_of_frames <- list.files("your/path/to/directory", full.names=T)
av::av_encode_video(list_of_frames, framerate = 30,
output = "output_animation.mp4")
I have a bunch of .avi files I would like to load into R, breakdown each frame as an individual image, arrange the images, and save as a separate image. In spite of a sincere effort to try to find a package to load .avi files, I can't find anything.
1) is it possible to load and work with avi files in r?
2) how is this done?
3) is there a specific library for this?
Ive seen several examples using linux, such as this post, but I'm hoping for an R solution.
Converting AVI Frames to JPGs on Linux
I figured this out. As indicated in the comments section, ffmpeg is the package called by various packages in R to load videos into the R environment. The Imager package has a function called "load.video.internal" that works well and uses ffmpeg. I had to down load the package from github because this function was not available in the version I installed using "install.packages". I ended up copy/pasting the function from the source package and commenting out the reference to the "has.ffmpeg" function because it kept hanging at this step. Using paste, I was able to indicate the file path and load an avi file successfully.
Modified load.video.internal function:
load.video.internal <- function(fname,maxSize=1,skip.to=0,frames=NULL,fps=NULL,extra.args="",verbose=FALSE)
{
# if (!has.ffmpeg()) stop("Can't find ffmpeg. Please install.")
dd <- paste0(tempdir(),"/vid")
if (!is.null(frames)) extra.args <- sprintf("%s -vframes %i ",extra.args,frames)
if (!is.null(fps)) extra.args <- sprintf("%s -vf fps=%.4d ",extra.args,fps)
arg <- sprintf("-i %s %s -ss %s ",fname,extra.args,as.character(skip.to)) %>% paste0(dd,"/image-%d.bmp")
tryCatch({
dir.create(dd)
system2("ffmpeg",arg,stdout=verbose,stderr=verbose)
fls <- dir(dd,full.names=TRUE)
if (length(fls)==0) stop("No output was generated")
ordr <- stringr::str_extract(fls,"(\\d)+\\.bmp") %>% stringr::str_split(stringr::fixed(".")) %>% purrr::map_int(~ as.integer(.[[1]])) %>% order
fls <- fls[ordr]
#Check total size
imsz <- load.image(fls[[1]]) %>% dim %>% prod
tsz <- ((imsz*8)*length(fls))/(1024^3)
if (tsz > maxSize)
{
msg <- sprintf("Video exceeds maximum allowed size in memory (%.2d Gb out of %.2d Gb)",tsz,maxSize)
unlink(dd,recursive=TRUE)
stop(msg)
}
else
{
out <- map_il(fls,load.image) %>% imappend("z")
out
} },
finally=unlink(dd,recursive=TRUE))
}
Example of its use:
vid_in <- load.video.internal(paste("/home/phil/Documents/avi_files/Untitled.avi"))
UPDATED SIMPLER VERSION:
the magick package will read avi files using the image_read function.
I am looking for an automated method to convert leaflet R Studio plots into image files.
Seems like exporting a leaflet widget to HTML is straightforward (Saving leaflet output as html). However I cannot find any answers or docs about how to save the image produced by a leaflet widget as an image. It seems strange that I can do this manually in R Studio but that there isn't some function within R Studio that can be called to do the same thing.
I've tried the usual suspects, variations on the following:
png("test_png.png")
map
dev.off()
But these all just print white or print a file that can't even be opened. IF I understand this Git discussion correctly, seems like something in leaflet is not available but is desired by users.
In the meantime, R Studio clearly has a way to render this image into an image file, making me press a button to do it. Is there a way to automate this? How can I export the images plotted in R Studio to image files? I need image files and I need this to be programmatic because I want to make a gif out of a few hundred maps.
Alternately, I'd welcome suggestions for a workaround. I might try this: Python - render HTML content to GIF image but if someone has alternatibve suggestions, please share.
I've been trying to do this with a combination of the webshot package and saveWidget from htmltools, although it's pretty slow. For a few hundred maps, it's probably not too bad if you're only doing it here and there. But, for real-time application it is too slow.
There are two external applications you need for this workflow. webshot takes screenshots of webpages and requires you to install PhantomJS first (it's tiny and easy). I also use ImageMagick (and needs to be accessible from the command line) to create the .gif files, but I'm sure there many other programs you could use to make gifs.
The idea is just to create the maps in a loop, save them to a temporary html file with saveWidget and use webshot to turn it into a png (slow). Then, once you have all the pngs, use ImageMagick to convert them to a gif (fast).
Here is an example, I also load ggmap, but only to get a location to zoom in on.
library(webshot)
library(leaflet)
library(htmlwidgets)
library(ggmap)
loc <- geocode('mt everest') # zoom in everest
zooms <- seq(2,14,3) # some zoom levels to animate
## Make the maps, this will make some pngs called 'Rplot%02d.png'
## in your current directory
for (i in seq_along(zooms)) {
m <- leaflet(data=loc) %>%
addProviderTiles('Esri.WorldImagery') %>%
setView(lng=loc$lon, lat=loc$lat, zoom=zooms[i])
if (i==1)
m <- m %>% addPopups(popup="Going to see Mt Everest")
if (i==length(zooms))
m <- m %>%
addCircleMarkers(radius=90, opacity = 0.5) %>%
addPopups(popup = 'Mt Everest')
## This is the png creation part
saveWidget(m, 'temp.html', selfcontained = FALSE)
webshot('temp.html', file=sprintf('Rplot%02d.png', i),
cliprect = 'viewport')
}
Then, it is just converting pngs to gif. I did this on a Windows, so command might be slightly different on a mac/linux (I think just single quotes instead of double quotes or something). These commands are from a command line/shell, but you could also use system/system2 to call from R or try the animation package that has some wrapper functions for ImageMagick. To make a simle gif with nothing fancy is simply, convert *.png animation.gif. I used a slightly longer code to make the pngs smaller/add some delays/and have the sequence go in and out.
convert Rplot%02d.png[1-5] -duplicate 1,-2-1, -resize "%50" gif:- | convert - -set delay "%[fx:(t==0||t==4)?240:40]" -quiet -layers OptimizePlus -loop 0 cycle.gif
You can create a series of PNG files as answered by jenesaisquoi (first answer). Then create gif with the png files using the below code with magick package.
library(magick)
png.files <- sprintf("Rplot%02d.png", 1:20) #Mention the number of files to read
GIF.convert <- function(x, output = "animation.gif")#Create a function to read, animate and convert the files to gif
{
image_read(x) %>%
image_animate(fps = 1) %>%
image_write(output)
}
GIF.convert(png.files)
You don't require to install ImageMagick software on PC.
Code Link: Animation.R
I have table with 3 columns: lat,lon,day (376 days).
The process is: create the map -> save the map as HTML -> save the map as PNG -> import the pic -> plot it (with plot + ggimage)
All this process, will be in a loop
library(leaflet)
library(animation)
library(png)
library(htmlwidgets)
library(webshot)
library(ggmap)
saveGIF({
for (i in 1:376) {
map = leaflet() %>%
addTiles() %>%
setView(lng = lon_lat[1,2], lat = lon_lat[1,1], zoom = 5)%>%
addMarkers(lng = lon_lat[lon_lat$day == i,2],lat = lon_lat[lon_lat$day == i,1])
saveWidget(map, 'temp.html', selfcontained = FALSE) ## save the html
webshot('temp.html', file=sprintf('Rplot%02d.png', 1),cliprect = 'viewport') ## save as png
img = readPNG("Rplot01.png") ### read the png
plot(ggimage(img)) ###reading png file
}
})