Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert jpg to greyscale csv using R

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.

like image 464
barker Avatar asked Dec 15 '14 17:12

barker


People also ask

How do I convert a JPEG to grayscale?

Right-click the picture that you want to change, and then click Format Picture on the shortcut menu. Click the Picture tab. Under Image control, in the Color list, click Grayscale or Black and White.

How do I convert a JPEG to a csv file?

To convert a JPG image to CSV format, simply drag and drop the JPG file into the data upload area, select the 'OCR' option, and click the 'Convert' button. You'll get an CSV spreadsheet populated with data from the JPG file.

Can we store image in csv file?

Adding images to a CSV file requires that your images are available on the internet and that you have a public URL for them, which you can add to your CSV file. If the images are already on a website, you can just use their existing URL.


1 Answers

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")
like image 98
Mike.Gahan Avatar answered Oct 01 '22 17:10

Mike.Gahan