Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created October 30, 2012 15:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dsparks/3981069 to your computer and use it in GitHub Desktop.
Save dsparks/3981069 to your computer and use it in GitHub Desktop.
Image Manipulation, Part 4
doInstall <- TRUE # Change to FALSE if you don't want packages installed.
toInstall <- c("ReadImages", "reshape", "ggplot2")
if(doInstall){install.packages(toInstall, repos = "http://cran.r-project.org")}
lapply(toInstall, library, character.only = TRUE)
imageLoader <- function(url){ # This function takes a URL, and generates a data.frame with pixel locations and colors
# Download to disk, load
download.file(url, "tempPicture.jpg", mode = "wb") # Stash image locally
readImage <- read.jpeg("tempPicture.jpg")
longImage <- melt(readImage)
rgbImage <- reshape(longImage, timevar = "X3",
idvar = c("X1", "X2"), direction = "wide")
rgbImage$X1 <- -rgbImage$X1
return(rgbImage)
}
##########
# Part 4 # Finding a bright object
##########
# Load NASA's image
rgbImage <- imageLoader("http://www.nasa.gov/images/content/694811main_pia16225-43_full.jpg")
with(rgbImage, plot(X2, X1, col = rgb(rgbImage[, 3:5]), asp = 1, pch = "."))
# Look at a region of only sand
sandOnly <- with(rgbImage, rgbImage[X2 > 1000 & X1 > -300, ])
with(sandOnly, plot(X2, X1, col = rgb(sandOnly[, 3:5]), asp = 1, pch = "."))
sandMean <- apply(sandOnly[, 3:5], 2, mean) # Find typical sand color values
sandSD <- apply(sandOnly[, 3:5], 2, sd)
colorZ <- sweep(rgbImage[, 3:5], 2, sandMean, "-") # How much do all colors
colorZ <- sweep(colorZ, 2, sandSD, "/") # deviate from sand colors?
plot(density(rowSums(colorZ)))
# Plot a "binarized" image, based on color Z-scores
with(rgbImage, plot(X2, X1, col = rgb(colorZ>4), asp = 1, pch = "."))
points(830, -920, cex = 4, col = "RED")
# That little blue dot, at about 830, -920, is the anomaly! Science!
@lytze
Copy link

lytze commented Aug 31, 2014

I found your code as a sample tutorial in stackoverflow, but I found this code is kind of out of data.

The ReadImages package is removed by cran, and substituted by the jpeg package. And the function is now readJPEG().

The result for the image loading might be a little bit different.

This is really a good example for image recognition, if it is okay, hope that you could update this code.

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment