使用R将jpg转换为greyscale csv

时间:2022-01-16 16:52:10

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/

我有一个JPG图像的文件夹,我正在尝试为一个讨人喜欢的比赛进行分类。我已经看到Python中的一些代码,我认为会在论坛上实现这一点,但是想知道是否可以在R中完成?我正在尝试将许多jpg图像的文件夹转换为csv文件,其中数字显示每个像素的灰度,类似于手数字识别器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.

所以在R中基本上是jpg - > .csv,显示了用于分类的每个像素的灰度数。我想在它上面放一个随机森林或线性模型。

1 个解决方案

#1


7  

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.)

有一些公式可以在这个链接上执行此操作。光栅包是一种方法。这基本上将RGB波段转换为一个黑白带(它使它的尺寸更小,我猜你想要的。)

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:

我认为EBImage包也可以帮助解决这个问题(不是在CRAN上,通过源安装它:

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")

#1


7  

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.)

有一些公式可以在这个链接上执行此操作。光栅包是一种方法。这基本上将RGB波段转换为一个黑白带(它使它的尺寸更小,我猜你想要的。)

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:

我认为EBImage包也可以帮助解决这个问题(不是在CRAN上,通过源安装它:

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")