convert jpg to greyscale csv using R
Asked Answered
P

1

8

I have a folder of JPG images that I'm trying to classify for a kaggle competition. I have seen some code in Python that I think will accomplish this on the forums, but was wondering is it possible to do in R? I'm trying to convert this folder of many jpg images into csv files that have numbers showing the grayscale of each pixel, similar to the hand digit recognizer here http://www.kaggle.com/c/digit-recognizer/

So basically jpg -> .csv in R, showing numbers for the grayscale of each pixel to use for classification. I'd like to put a random forest or linear model on it.

Pietrek answered 15/12, 2014 at 17:46 Comment(2)
you can use the jpeg package and readJPEG to read the files. If they are truly single-channel (greyscale) images, then the value at the x/y coord will be 0:1 and be the corresponding to the greyscale level.Cental
@Cental might be worth noting that "most" JPEG files are 8-bit so one could convert from 0:1 to 0:255 if desired.Christiansen
H
10

There are some formulas for how to do this at this link. The raster package is one approach. THis basically converts the RGB bands to one black and white band (it makes it smaller in size, which I am guessing what you want.)

library(raster)
color.image <- brick("yourjpg.jpg")

# Luminosity method for converting to greyscale
# Find more here http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
color.values <- getValues(color.image)
bw.values <- color.values[,1]*0.21 + color.values[,1]*0.72 + color.values[,1]*0.07

I think the EBImage package can also help for this problem (not on CRAN, install it through source:

source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
library(EBImage)

color.image <- readImage("yourjpg.jpg")
bw.image <- channel(color.image,"gray")
writeImage(bw.image,file="bw.png")
Haematite answered 15/12, 2014 at 19:49 Comment(1)
Thanks for sharing the knowledge Mike :)Pietrek

© 2022 - 2024 — McMap. All rights reserved.