I am trying to find RGB values in R.
The jpeg images that I am using have an object with white background.
Like this one: http://www.wild-wonders.com/blog/wp-content/uploads/2009/11/nba_france_16.jpg
Right now, in order to just select the object, I have to trace each object manually (by plotting dots which makes the selection into a shape that will later be used to get the RGB values). Is there any tools or packages like magic wand tool in photoshop that will automatically select the white background?
Have a look at the functionality provided by 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")
The example below illustrates how to automatically extract an object from white background, and get its #rrggbb pixel values. I used a value of 0.95 for thresholding rather than 1.0 (corresponding to white pixels) because of the artifacts introduced by jpeg compression.
library(EBImage)
## load the array representing pixel intensities into R
img <- readImage("http://www.wild-wonders.com/blog/wp-content/uploads/2009/11/nba_france_16.jpg")
## convert to grayscale before thresholding
gray <- channel(img, "gray")
## create a mask separating objects from background
mask <- gray < 0.95
## label objects (connected sets of pixels)
obj <- bwlabel(mask)
## indices of pixels within the object
idx <- which(mask==1, arr.ind=TRUE)
## extract the red, green, and blue pixel intensities
rgb <- cbind(channel(img, "r")[idx],
channel(img, "g")[idx],
channel(img, "b")[idx])
## convert to #RRGGBB representation
rgb(rgb)
Related
The goal is to get the vector polygons from raster areas accordingly to their gray scale. For example:
Dark pixels to dark_relief.shp
Gray pixels to gray_relief.shp
Light pixels to light_relief.shp
First I got GeoTIFF from SRTM file using Raster – Analysis – DEM (Terrain models) in Hillshade mode:
Then I use Raster - Conversion - Polygonize (Raster to Vector), but result is too many small polygons. Obviously I should prepare the image before a conversion.
Any hints what to do?
May be other right way exists?
Regards!
If you know the cut off points for each contour/band/classification you can reclassify your raster file in qGIS with the raster calculator. From there you can use raster to vector to create polygons only for the contours/bands/classifications you specified.
The example raster calculator calculation below should divide a layer into three pieces, areas below 1000, areas between 1000 and 1200, and areas above 1200.
("layer" > 1000) * 1 + ("layer" > 1200) * 1
With a starting raster of:
And the above calculation, I got:
Which will polygonize pretty easily and cleanly.
I am not an R expert, but i use it for all kinds of image processing. Now I am trying to apply Gaussian blur smoothing (spatstat package) on my satellite S-2 image. Original type of my image is Raster (Raster layer) tiff, actually a subtract image from two Sentinel-2 bands (green and blue). To apply blur on this kind of image I have to first convert it to a pixel image. I've tried doing this following few other questions (like this one Converting a raster object to an im object in R), but i did not succed. I have tried few possibilities, like converting raster image into matrix and than to pixel image, but this does not work, because the image is than too large (although I use small, croped area of the whole Sentinel-2 image).
So, my function in brief looks something like that:
blue <- raster("S2A_OPER_MSI_T33TWH_B02.tif")
green <- raster("S2A_OPER_MSI_T33TWH_B03.tif")
subt <- function(r1, r2) {
return(r2-r1)
}
out_sub1 <- (blue, green, fun = subt)
I tried to apply blur directly on a Raster image, but i soon realized its not working on raster data:
gauss_sub1 <- blur(out_sub1, sigma = 5)
#Error: is.im(x) is not TRUE
So, I try to convert my image into a pixel one
out_sub11 <- as.im(X = "out_sub1")
Error in as.im.function(X, W, ..., dimyx = dimyx, na.replace = na.replace): A window W is required
Therefore I try to define a window following my raster extent
e <- out_sub1#extent
sp_w <- as(e, "SpatialPolygons")
W <- as(sp_w, "owin")
Error in as(SP.win, "owin") : no method or default for coercing “SpatialPolygons” to “owin”
Can anyone tell me what am I doing wrong or how can I convert spatial polygon into owin object class, so I can further process blur command?
And can please someone explain me what difference there is between raster image and a pixel image in R?
You can apply a filter using raster library:
library(raster)
r <- blue - green
# 3 by 3 mean filter
r_mf <- focal(r, w=matrix(1/9,nrow=3,ncol=3))
# gaussian filter
gf <- focalWeight(r, 2, "Gauss")
r_gf <- focal(r, w=gf)
I want to change an image into matrix of numbers in R using EBImage package. I have tried this code but it only output all 1's:
library(EBImage)
img<-readImage("test.jpg")
imageData(img)[1:50,1:60,1]
this is the image
The following example illustrates how to load a grayscale image containing an alpha channel, convert it to single-channel grayscale image, and do some post-processing: crop the border and resize.
library(EBImage)
img <- readImage("http://i.stack.imgur.com/9VTWx.png")
# grayscale images containing an alpha channel are represented in EBImage as
# RGBA images by replicating the grayscale intensities over the red, green and
# blue channels
print(img, short=TRUE)
## Image
## colorMode : Color
## storage.mode : double
## dim : 819 460 4
## frames.total : 4
## frames.render: 1
# convert to grayscale
img <- channel(img, "gray")
# collect matrix indices of non-white pixles
ind <- which(img < 1, arr.ind=TRUE)
# find min/max indices across rows/columns
ind <- apply(ind, 2L, range)
rownames(ind) <- c("min", "max")
ind
## row col
## min 17 7
## max 819 413
# crop the image
img <- img[ind["min","row"]:ind["max","row"], ind["min","col"]:ind["max","col"]]
# resize to specific width and height
img <- resize(img, w=128, h=128)
display(img)
To extract the underlying matrix use imageData(img).
First of all, that's not a JPEG image, but PNG.
Second, it's not RGB, but greyscale + alpha (according to ImageMagick at least), although the alpha channel is completely opaque, so it doesn't hold any actual data.
Third, the reason you're getting all ones is because the section of the image you are choosing is all white, i.e. maximum intensity, which is represented by the value 1.
Try something like imageData(img)[51:100,1:60,1] and see if that doesn't give a different result.
Is there a simple way to crop a specified pixel location of a png image, and raster that image onto a plot.
Currently i am working with dissociated cells (up to 1000 cells in a field of view). Each cell has a center x (in pixels) and a center y (in pixels). We gather data in trace format, so i would like a way of displaying the picture of the cells next to the trace.
I have tried rasterImage, and grid.raster. Unfortunately i have no idea how to call upon the image array to specify the location.
Also, i do not want to use the zoom package since the functions work extremely slow and are not able to raster onto a current plot.
Take a look at the raster package. The raster::raster function, for importing or coercing your png and raster::crop for subsetting to a specific extent.
Here is an example from the crop functions help.
Create an example raster
r <- raster(nrow=45, ncol=90)
r[] <- 1:ncell(r)
Subset the raster based on a define extent
e <- extent(-160, 10, 30, 60)
rc <- crop(r, e)
Plot results
par(mfrow=c(1,2))
plot(r)
plot(rc)
It was alot easier than expected. My PNG image was an array with 3 layers.
img[xpos, ypos, layer]
Therefore i could simply specify the location of my cells increased by a factor,
rasterImage(img[(x-x*.2):(x+x*.2), (y-y*.2):(y+y*.2),],-2, 4, 3, 1)
Now i need to code around for cells at the limits of my plots.
Is there any R function to convert grey scale image to binary image. There is one to convert from RGB to Grey but I want to convert Grey to Binary.
This is called thresholding or binarization. The most robust in my experience is adaptive thresholding. This is implemented in EBImage as the thresh method
x = readImage(system.file('images', 'nuclei.tif', package='EBImage'))
if (interactive()) display(x)
y = thresh(x, 10, 10, 0.05)
if (interactive()) display(y)
You didn't say what class or "typeof" your data is, so I'm going to provide an answer in a simple case. Suppose your image is an array of integers. These integers range from 0 to, say 512 for a 9-bit greyscale image. You need to decide what the cutoff point is for 0 vs. 1 in your binary image. Then
bin_image <- round(grey_image/max(grey_image),0)
should do it. If your data range from 0 to 1, do a similar operation but adjust the rounding parameters.
Edit: ooops, I left out a choice of cutoff level. Replace max(grey_image) with K*max(grey_image) where K = 1 for cutting at half-max, K>1 to cut higher and K<1 to cut lower.
The EBImage Bioconductor package is a handy tool for performing image analysis in R.
A basic example taken from the package's Vignette:
lena = readImage(system.file("images", "lena.gif", package="EBImage"))
display(lena>0.5)