将图像从C#传递到R

本文关键字:图像 | 更新日期: 2023-09-27 18:22:48

我想将图像从C#传递到R。我使用FileUpload上传图像并将其存储到文件夹"images"中。当我将图像位置传递到R时,会出错。所以,你们能给我建议解决这个错误的其他方法吗。以下是我的代码。

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

将图像从C#传递到R

这里是答案:

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

filename应该是完整的路径

前缀:我对C#一无所知。然而,你的情况很熟悉。为什么不从C#调用shell命令或R进程呢?我在Python和R之间已经做过很多次了。考虑使用R的自动可执行RScript抽象这两种语言,并使用Process.Start或新的Process对象从C#传递图像名称作为参数?

C#编写脚本

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编写

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)