This post is now the sequel to this week’s post about color spaces. I think it will be a rather short post, where I just implement the conversion back HSV to RGB and then test my methods for demonstration.

In doing so I used the corresponding wikipedia post as a rough guideline.

So let me show you how I did it.

```
library(Raspository)
calculateRGBvalue <- function(H, C, X, m){
if(H >= 0 && H <= 1){
return(c(m + C, m + X, m))
}else if(H >= 0 && H <= 2){
return(c(m + X, m + C, m))
}else if(H >= 0 && H <= 3){
return(c(m, m + C, m + X))
}else if(H >= 0 && H <= 4){
return(c(m, m + X, m + C))
}else if(H >= 0 && H <= 5){
return(c(m + X, m, m + C))
}else if(H >= 0 && H <= 6){
return(c(m + C, m, m + X))
}else{
return(c(0,0,0))
}
}
require(abind)
```

## Loading required package: abind

```
hsvArrayToRgb <- function(hsvArray){
# Calculate the chroma
C <- hsvArray[,,3] * hsvArray[,,2]
H<- hsvArray[,,1] / 60
X <- C * (1 - abs(H %% 2 - 1))
m <- hsvArray[,,3] - C
rgb<-mapply(FUN = calculateRGBvalue, H = H, C = C, X = X, m = m)
rgbArray<-abind(matrix(rgb[1,], nrow = nrow(hsvArray)),
matrix(rgb[2,], nrow = nrow(hsvArray)),
matrix(rgb[3,], nrow = nrow(hsvArray)),
along = 3)
return(rgbArray)
}
imageRGBFromHSV <- function(img){
return(new("imageRGB", original = hsvArrayToRgb(img@original),
current = hsvArrayToRgb(img@current),
operations = img@operations))
}
```

So far so goodâ€¦ That’s basically just an one to one implementation of the method from the Wikipedia article with the one difference being, that I add m beforehand and not later.

So let’s come to the fun part!

```
image <- imageRGBFromJpeg("Mountain.jpg")
```

## Loading required package: jpeg

```
plot(image)
```

What a ginormous mountain! But it isn’t even the tallest mountain in Saarland, believe it! Now we can also plot this as an black and white picture.

```
plot(imageBWFromRGB(image))
```

Then let’s convert to HSV and plot the S (saturation) and V (value/brightness) channel as black and white picture.

```
hsv <- imageHSVFromRGB(image)
plot(as.raster(hsv@current[,,2]))
```

How that looks like something from the 90s!

```
plot(as.raster(hsv@current[,,3]))
```

OK, and now compare this to the conversion to black and white from RGB. It’s a worse picture in my opinion, but in comparison to the other one it holds the accurate information about the lighting condition of each pixel. You see, how this could be useful in Computer Vision e.g.?

Let’s just say, you’re searching for something in your pictures, that absorbs a lot of light. Then this representation could be of use.

And last, but not least we have to convert the image back to confirm that we actually get back the original picture.

```
plot(imageRGBFromHSV(hsv))
```

Looks the same! I guess that concludes this blog post. And I already have some plans for the next few posts.

So, hopefully see you! đź™‚