I am trying to work with some image data in R, and cannot figure out how to resize the images I have to ensure they are all the same size.
In Python, I approached this problem as follows:
from PIL import Image
import numpy as np
size = (100, 100)
img = Image.open(filename)
img = img.resize(size)
img = np.array(img.getdata())
In R, I've been unable to locate a library that would accomplish the same thing. The farthest I've been able to get is:
library(jpeg)
img <- readJPEG(filename)
# Need something here to resize
img <- as.matrix(img)
The easiest approach would be a library like Pillow that I could call on, but as I said, I can't seem to find anything.
Thanks,
To resize the image, use image_scale() function. where value is either relative to parent object or fixed size values. Value = 100% or 500 or 200%, etc.
Method 1: Using OpenImageR First install OpenImageR package in Rstudio. OpenImageR is an image processing Toolkit that Incorporates functions for image preprocessing, filtering and image recognition. The image to be resized is imported to the environment and the required resizing is done using image_scale() function.
One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.
You can easily accomplish this with the help of the Bioconductor package EBImage, an image processing and analysis toolbox for R. To install the package use:
source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
You can then use the functionality provided by EBImage to load and scale the image, as in the following example.
library("EBImage")
x <- readImage(system.file("images", "sample-color.png", package="EBImage"))
# width and height of the original image
dim(x)[1:2]
# scale to a specific width and height
y <- resize(x, w = 200, h = 100)
# scale by 50%; the height is determined automatically so that
# the aspect ratio is preserved
y <- resize(x, dim(x)[1]/2)
# show the scaled image
display(y)
# extract the pixel array
z <- imageData(y)
# or
z <- as.array(y)
For more examples on the functionality provided by EBImage see the the package vignette .
The package imager
is a nice fit and hides all the details about splines, interpolations and simply stores the images in a 4 dimensional array (the fourth dimension being used in the case of videos)
library(imager)
im <- load.image(my_file)
thmb <- resize(im,round(width(im)/10),round(height(im)/10))
plot(im)
plot(thmb,main="Thumbnail")
More informations can be found here: on the official introduction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With