Friday, June 10, 2011

Image color palette replacement

Here is an example of a function I wrote to change the color palette used in an image. The above example comes from a black and white original, although color images can also be used. The function first converts the image to grayscale in order to have levels of color intensity between 0-255. Using a new color palette with 256 color levels, the gray levels are replaced with a rgb (red, blue, green) vector from the new palette. The results can be very strange...
The package biOps is required for reading and writing the .jpeg files.

the function...

image2pal<-function(img, pal){
 img_grey <- imagedata(img, type="grey")
 img_pal <- imagedata(img_grey, type="rgb")
 colorlevels <- pal(256)
 lut <- col2rgb(colorlevels)
 for(i in 1:3){
  temp <- lut[i,img_grey+1]
  dim(temp) <- dim(img_grey)
  img_pal[,,i] <- temp 
Created by Pretty R at

The original image (from Wikimedia Commons):

the script used to create the modified image using the image2pal() function...
x_pal <- image2pal(x, cpal)
writeJpeg("Uss-akron-manhattan_w_pal.jpg", x_pal)
Created by Pretty R at

No comments:

Post a Comment