Reputation: 6796
I want to take x, convert it into a black and white image. Then i want to convert all pixels that are below 100 to 0 and convert all pixels that are above 100 to 255. I want to get a sharper image where background will be white and objects within image will be black. And then store new x (black and white sharp image) on my hard drive. How could i do it?
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
plotRGB(x)
Based upon earlier question, i wrote below lines to convert r1 to black and white. But plotRGB function fails :(. Plot function works but it doesnt return me a black and white image
flat <- sum(x * c(0.2989, 0.5870, 0.1140))
plotRGB(flat)
flat
plot(flat)
========update1==========
in case anyone interested,
image colors can be swapped easily by using "1-twoclasses" in place of "twoclasses" in image and plot functions below
Upvotes: 1
Views: 3003
Reputation: 47591
To actually see grays you need to provide these colors.
library(raster)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
x <- crop(r1, extent(0,50,0,50))
flat <- sum(x * c(0.2989, 0.5870, 0.1140))
plot(flat, col=gray(seq(0,1,0.1)))
You can use the reclassify function to get values that are either 0 or 255 but in this case it would seem more sensible to use 1 and 2
twoclasses <- cut(flat, c(0,100,255))
plot(twoclasses, col=gray(c(0,1)))
To write to disk, you can do something like:
png(width=ncol(twoclasses)*10, height=nrow(twoclasses)*10)
par(mai=c(0,0,0,0))
image(twoclasses, col=gray(c(0,1)))
dev.off()
Upvotes: 2