I am currently working on an application of Principal Component Analysis to visual data in R.
In Matlab, one can invoke commands such as "im2double" and "mat2gray" to convert a bitmap into a numerical matrix and back again to an image.
I was wondering whether this can be achieved in R, maybe via additional packages.
I've used the EBImage package (vignette here) available on bioconductor to work with and manipulate images:
# installing package if needed
source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
library(EBImage)
f = readImage(system.file("images", "lena-color.png", package="EBImage"))
str(f)
#Formal class 'Image' [package "EBImage"] with 2 slots
# ..# .Data : num [1:512, 1:512, 1:3] 0.886 0.886 0.875 0.875 0.886 ...
# ..# colormode: int 2
I was curious enough to try this out; clearly a package is a better solution, but if you really want to stick to base R, this will load a png (albeit upside down and backwards; that's probably fixable). It assumes the presence of the netpbm tools, so probably won't work out of the box on Windows systems.
readPng <- function(pngFile) {
contents <- system(paste('pngtopnm',pngFile,'| pnmtoplainpnm'),intern=TRUE)
imgDims <- strsplit(contents[2], ' ')
width <- as.numeric(imgDims[[1]][1])
height <- as.numeric(imgDims[[1]][2])
rawimg <- scan(textConnection(contents),skip=3)
return(list(
x=1:width,
y=1:height,
z=matrix(rawimg,width),
width=width,
height=height))
}
You can run image(img) on the list returned from this function directly, or access the per-pixel values using img$z.
Two methods to install the package.
install through command line if you have no Editor like RStudio
install the command line by entering into R interpreter using R command in bash.
Go to prompt where you can execute R commands. here these the basic image processing command.
execute this command to install the Bio conductor backage biocLite, which will help to install the EBIMage package( This package is used widely for image processing)
source("http://bioconductor.org/biocLite.R")
install the EMImage package to use image processing commands.
biocLite("EBImage")
Load the EBIMage package to use the image processing
library("EBImage")
# Reading image from computer
img=readImage(files="~/Desktop/Prog/R/tinago.JPG")
display(img)
img1=img+ 0.2 # increase brightness
img2=img- 0.2 # decrease brightness
display(img1) # Display images in browser or graphical window
display(img2) # Display images in browser or graphical window
img3= img * 0.5 # decrease contrast
img4=img * 2 # increase contrast
display(img3); display(img4) # show result images
img5=img^2 # increase Gamma correction
img6=img^0.7 # decrease Gamma correction
display(img5); display(img6) # Display result images
Note : readImage to read the image. Display is used to view the image in Graphical Window.
The relatively new package tiff will read and write TIF images quite nicely.
All the same, for anything other than relatively simple image manipulation, I'd recommend using ImageJ or SAOImage9 from the Harvard-Smithsonian group: http://www.cfa.harvard.edu/resources/software.html .
I've written tools in R to do pixel merging, pixel splitting, Sobel & Hough transforms, decolorization, etc., with great success. Ultimately the choice of application depends on the size of your images and the type of processing you need to do.
Related
I have written some functions to facilitate repeated tasks among my R projects. I am trying to use an environment to load them easily but also prevent them from appearing when I use ls() or delete them with rm(list=ls()).
As a dummy example I have an environment loader function in a file that I can just source from my current project and an additional file for each specialized environment I want to have.
currentProject.R
environments/env_loader.R
environments/colors_env.R
env_loader.R
.environmentLoader <- function(env_file, env_name='my_env') {
sys.source(env_file, envir=attach(NULL, name=env_name))
}
path <- dirname(sys.frame(1)$ofile) # this script's path
#
# Automatically load
.environmentLoader(paste(path, 'colors_env.R', sep='/'), env_name='my_colors')
colors_env.R
library(RColorBrewer) # this doesn't work
# Return a list of colors
dummyColors <- function(n) {
require(RColorBrewer) # This doesn't work
return(brewer.pal(n, 'Blues'))
}
CurrentProject.R
source('./environments/env_loader.R')
# Get a list of 5 colors
dummyColors(5)
This works great except when my functions require me to load a library. In my example, I need to load the RColorBrewer library to use the brewer.pal function in colors_env.R, but the way is now I just get an error Error in brewer.pal(n, "Blues") : could not find function "brewer.pal".
I tried just using library(RColorBrewer) or using require inside my dummyColors function or adding stuff like evalq(library("RColorBrewer"), envir=parent.env(environment())) to the colors_env.R file but it doesn't work. Any suggestions?
If you are using similar functions across projects, I would recommend creating an R package. It's essentially what you're doing in many ways, but you don't have reinvent a lot of the loading mechanisms, etc. Hadley Wickham's book R Packages is very good for this topic. It doesn't need to be a completely fully built out, CRAN ready sort of thing. You can just create a personal package with misc. functions you frequently use.
That being said, the solution for your specific question would be to explicitly use the namespace to call the function.
dummyColors <- function(n) {
require(RColorBrewer) # This doesn't work
return(RColorBrewer::brewer.pal(n, 'Blues'))
}
Create a package and then run it. Use kitten to build the boilerplate, copy your file to it, optionally build it if you want a .tar.gz file or omit that step if you don't need it and finally install it. Then test it out. We have assumed colors_env.R, shown in the question, is in current directory.
(Note that require should always be within an if so that if it does not load then the error is caught. If not within an if use library which will guarantee an error message in that case.)
# create package
library(devtools)
library(pkgKitten)
kitten("colors")
file.copy("colors_env.R", "./colors/R")
build("colors") # optional = will create colors_1.0.tar.gz
install("colors")
# test
library(colors)
dummyColors(5)
## Loading required package: RColorBrewer
## [1] "#EFF3FF" "#BDD7E7" "#6BAED6" "#3182BD" "#08519C"
I search for a command to compute Walsh-Hadamard Transform of an image in R, but I don't find anything. In MATLAB fwht use for this. this command implement Walsh-Hadamard Tranform to each row of matrix. Can anyone introduce a similar way to compute Walsh-Hadamard on rows or columns of Matrix in R?
I find a package here:
http://www2.uaem.mx/r-mirror/web/packages/boolfun/boolfun.pdf
But why this package is not available when I want to install it?
Packages that are not maintained get put in the Archive. They get put there when that aren't updated to match changing requirements or start making errors with changing R code base. https://cran.r-project.org/web/packages/boolfun/index.html
It's possible that you might be able to extract useful code from the archive version, despite the relatively ancient version of R that package was written under.
The R code for walshTransform calls an object code routine:
walshTransform <- function ( truthTable ) # /!\ should check truthTable values are in {0,1}
{
len <- log(length(truthTable),base=2)
if( len != round(len) )
stop("bad truth table length")
res <- .Call( "walshTransform",
as.integer(truthTable),
as.integer(len))
res
}
Installing the package succeeded on my Mac, but would require the appropriate toolchain on whatever OS you are working in.
I am clustering time series in R using package KmL. I have read both manual and paper how to use this package, but Im not very clear how to export the results (data frame, where each trajectories are assign to some clusters e.g.
trajectory (i), time1, time2, time3, clustername)
I have read several answers here Output from 'choice' in R's kml
but if I do the same (run choice(myCld, typeGraph= "bmp")) my R says:
~ Choice : menu ~ 'Arrow' : change partition 'Space' : select/unselect a partition ... etc. e : change the display (both)
~ 'Return' when its done ~
And only thing that is saved to my library is myCld.Rdata and it runs for very long time without any more results. (my dataset: N trajectories, with time= 1:53) I want to have csv. files as manual suggest (objectName-Cx-y-Clusters.csv)
I am also not very clear WHERE should I PRESS on "Return" or "Arrow"? There is no option to press on anything in my Rstudio workplace.
I am really a beginner with R so any help would be appreciated. Thanks!
I am not sure that kml is compatible with Rstudio. The older version of Rstudio did not handle instruction like getGraphicsEvent that was used by choice.
Is it possible, to control the mouse pointer from the R console?
I have something like this in mind:
move_mouse(x_pos=100,y_pos=200) # move the mouse pointer to position (100,200)
mouse_left_button_down # simulate a press of the left button
move_mouse(x_pos=120,y_pos=250) # move mouse to select something
mouse_release_left_button # release the pressed button
In MATLAB, something like this is possible with the following code
import java.awt.Robot;
mouse = Robot;
mouse.mouseMove(0, 0);
mouse.mouseMove(100, 200);
I tried a direct conversion of the above into R that looks like this:
install.packages("rJava") # install package
library(rJava) # load package
.jinit() # this starts the JVM
jRobot <- .jnew("java/awt/Robot") # Create object of the Robot class
Once I got jRobot in R, I tried to call its metho "MouseMove(100,200)" using the two command below which both resulted in an error.
jRobot$mouseMove(10,10)
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, :
java.lang.NoSuchMethodException: No suitable method for the given parameters
or
.jcall(jRobot,, "mouseMove",10,10)
Error in .jcall(jRobot, , "mouseMove", 10, 10) :
method mouseMove with signature (DD)V not found
Finally I found the problem. You have to tell R that 100 is an integer, in order to pass it to java correctly.
install.packages("rJava") # install package
library(rJava) # load package
.jinit() # this starts the JVM
jRobot <- .jnew("java/awt/Robot") # Create object of the Robot class
# Let java sleep 500 millis between the simulated mouse events
.jcall(jRobot,, "setAutoDelay",as.integer(500))
# move mouse to 100,200 and select the text up to (100,300)
.jcall(jRobot,, "mouseMove",as.integer(100),as.integer(200))
.jcall(jRobot,, "mousePress",as.integer(16))
.jcall(jRobot,, "mouseMove",as.integer(100),as.integer(300))
.jcall(jRobot,, "mouseRelease",as.integer(16))
As of 2017, CRAN has a package called rMouse to handle mouse movement.
library(rMouse)
move(0,0) # move to top left corner (0,0)
move(50,30) # move to pixel x = 50, y = 30
left() # left click
right() # right click
Under the hood it still uses Java's robot.
Similarly, KeyboardSimulator package published in 2018 seems to be doing pretty much the same thing
If you are using Windows, library(KeyboardSimulator) is the easiest way.
You can use it to make a bot in R
see the example:
Move Mouse in R (RStudio)
make a bot in R (Rstudio) for social media
What operating system? In Linux, you could use xdotool and call it from the R system function.
> mousemove=function(x,y){system(paste0("xdotool mousemove ",x," ",y))}
> mousemove(0,0)
> mousemove(500,500)
Note these are screen coordinates, nothing to do with the coordinates in your R graphics window, but you weren't clear about what you wanted. You might be able to get the screen coords of your R graphics window with some other X11 utilities and position on a plot if that's what you want.
In Windows, there's probably some other mouse-tweaking program you can leech onto. IDK.
xdotool info: http://tuxradar.com/content/xdotool-script-your-mouse
further reading of that article shows how to activate particular windows and do mouse actions in them.
I know this has been asked before but the existing answers seem out of date, as I can't install either Bio7 or rimage using install.packages and searching the cran repository for Bio7 gives a 404 link (am I missing something?).
So as of now, what are the right packages for loading / saving images in R so one can process the pixels from within R?
I don't need it to provide processing routines. As long as it can reliably turn a jpeg into a grid of pixel values and vice versa (and preferably do the same for a png) I can write processing code.
I think raster is what you need.
library(png)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
## convert it to a raster, interpolate =F to select only sample of pixels of img
img.r <- as.raster(img,interpolate=F)
Now you have a vector of color:
str(img.r)
'raster' chr [1:76, 1:100] "#00000000" "#0