Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RGB-image to one-channel gray image in R EBImage

An R-beginner question:

I wanted to convert an RGB-Image to grayscale and display/plot it with image()

library(EBImage)
orig = readImage("c:/test/b/s2.png")
gray = orig
colorMode(gray) = Grayscale

display(gray) #works
image(gray) #Error 'z' should be a matrix

The image converted by colorMode(gray) = Grayscale seems to be incompatible with image-function. Does Crayscale image in R EBImage has more than one channel?

Then I converted it manually and was able to call image() on it

r = channel(orig,"r")
g = channel(orig,"g")
b = channel(orig,"b")

gray1 = 0.21*r+0.71*g+0.07*b

display(gray1) 
image(gray1) #works

However, the images both gray differed slightly concerning intensity. Is there a way to convert RGB to one channel gray in R EBImage?

EDIT For answering the question, why EBImage:

The package provides some image-processing functions. E.g. I could display easily the intensity graph (img2) of a scanned test-stripe (img1) using further EBImage commands:

blotgraph = resize(gblur(gray1,3),200,1)
plot(blotgraph, type="l")

I was not aware how to solve such kind of tasks without EBImage

img1img2

like image 464
Valentin H Avatar asked Dec 12 '22 09:12

Valentin H


2 Answers

This might be simpler, though there are faster and cleaner ways to compress the color layers.

library(png)
foo<-readPNG("c:/test/b/s2.png")
#that's an array n by m by 3 . Now reduce to grey
bar<- foo[,,1]+foo[,,2]+foo[,,3]
# normalize
bar <- bar/max(bar)
# one of many ways to plot
plot(c(0,1),c(0,1),t='n')
rasterImage(bar, 0,0,1,1)

Note that this has created a greyscale image object bar while 'saving' the full-color object foo .

like image 106
Carl Witthoft Avatar answered Jan 30 '23 21:01

Carl Witthoft


Sorry if I am wrong, but as I understand your conversion to greyscale is not being done in a proper way. In general with EBImage conversion to grayscale is done with the command grayimage<-channel(yourimage,"gray") and image(grayimage) gives

Image
  colormode: Grayscale 
  storage.mode: double 
  dim: X Y 
  nb.total.frames: 1 
  nb.render.frames: 1 

where the colormode gives the nb.total.frames:3

like image 35
Tony Avatar answered Jan 30 '23 23:01

Tony