Jay
Jay

Reputation: 23

Passing image from C# to R

I want to pass image from C# to R. I'm uploading my image using FileUpload and storing it into a folder "images".When i'm passing images location to R it gives me error. So,can you guys suggest me any alternate way to solve this error.Following are my code.

// Get Filename from fileupload control

string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);             

engine.Evaluate("imgPath<-'~/images/filename'"); //error in this line

// Read the image into a raster array

engine.Evaluate("img<-readJPEG(imgPath, native = FALSE)");

// convert the array to a data.frame 

engine.Evaluate("mystring<-as.data.frame(img)");

engine.Evaluate("myfreqs <- mystring / sum(mystring)");

// vectorize

engine.Evaluate("abc <- as.data.frame(myfreqs)[,2]");

// create input matrices

engine.Evaluate(@"a <- matrix(c(abc), nrow=4)"); 

Upvotes: 1

Views: 602

Answers (2)

Parfait
Parfait

Reputation: 107707

PREFACE: I know nothing of C#. However, your situation is familiar. Why not call a shell command or a R process from C#? I have done this numerous times between Python and R. Consider abstracting the two languages by using R's automated executable RScript and pass image name as argument from C# using Process.Start or a new Process object?

C# Script

string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string args = @"C\Path\To\RScript.R" + " " + filename;

// SHELL COMMAND
// (RScript path can be shortened if using environment variable)
System.Diagnostics.Process.Start(@"C:\Path\To\RScript.exe", args);

// PROCESS OBJECT
var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = @"C:\Path\To\RScript.exe",
        Arguments = @"C\Path\To\RScript.R" + " " + filename,
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

R Script

options(echo=TRUE)
args <- commandArgs(trailingOnly = TRUE)

# pass argument into string 
imgPath <- args[1]

img <- readJPEG(imgPath, native = FALSE)

# convert the array to a data.frame 
mystring <- as.data.frame(img)    
myfreqs <- mystring / sum(mystring)

# vectorize
abc <- as.data.frame(myfreqs)[,2]

# create input matrices
a <- matrix(c(abc), nrow=4)

Upvotes: 0

nabuchodonossor
nabuchodonossor

Reputation: 2060

And here as answer:

 engine.Evaluate("imgPath<-'" + filename + "'");

filename should be the complete path

Upvotes: 1

Related Questions