how can i generate hocr using the tesseract wrapper here
currently i need to dynamically add the location of the tessdata to the environment variables and run my code
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + #"\tesseract-3.05.00dev-win32-vc19\tesseract.exe";
string inputImg = #"00067.jpg";
string hocrLocation = #"00067";
string argsPdf = "\"" + inputImg + "\"" + " " + "\"" + hocrLocation + "\"" + " hocr ";
Console.WriteLine(argsPdf);
pProcess.StartInfo.Arguments = argsPdf;
pProcess.StartInfo.CreateNoWindow = false;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.Start();
string strOutput = pProcess.StandardOutput.ReadToEnd();
Console.WriteLine("OUtput: " + strOutput);
pProcess.WaitForExit();
and then i found the tesseract wrapper. how can i generate an hocr file using the wrapper? i cant find an example how to do it.
this is the current code(from the example ) im using but how to output an hocr file?
var testImagePath = "./phototest.tif";
if (args.Length > 0)
{
testImagePath = args[0];
}
try
{
using (var engine = new TesseractEngine(#"./tessdata", "eng", EngineMode.Default))
{
using (var img = Pix.LoadFromFile(testImagePath))
{
using (var page = engine.Process(img))
{
}
}
}
}
catch (Exception e)
{
Trace.TraceError(e.ToString());
Console.WriteLine("Unexpected Error: " + e.Message);
Console.WriteLine("Details: ");
Console.WriteLine(e.ToString());
}
string hocrText = page.GetHOCRText(pageNum - 1);
Related
My c# code
public static string RunRScript(string filePath, string rScriptExecutablePath, string args, int totalFiles,
int RowsInChunk, int TotalRows, string identity)
{
string rCodeFilePath = filePath; //RScriptPath.GetFilePath();
//string file = rCodeFilePath;
string result = string.Empty;
// IEnumerable<string> connections = _connections.GetConnections(identity)
try
{
var info = new ProcessStartInfo();
info.FileName = rScriptExecutablePath;
info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath);
info.Arguments = "\"" + rCodeFilePath + "\"" + " " + args;
info.RedirectStandardInput = false;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
string fileName = string.Empty;
DateTime startTime = DateTime.Now;
List<ProgressTracker> lstProgress = new List<ProgressTracker>();
ProgressTracker p;
using (var proc = new Process())
{
//proc.StartInfo.Verb = "runas";
for (int i = 1; i <= totalFiles; i++)
{
p = new ProgressTracker();
p.DT = DateTime.Now;
p.Progress = i;
lstProgress.Add(p);
info.Arguments = "\"" + rCodeFilePath + "\"" + " " + args + " " + i.ToString();
proc.StartInfo = info;
proc.Start();
proc.WaitForExit();
result = proc.StandardOutput.ReadToEnd();
p.TimeTaken = (DateTime.Now - p.DT).TotalSeconds;
Functions.SendProgress("Process in progress...", i, totalFiles, RowsInChunk, TotalRows, lstProgress, identity);
}
}
return FormatOutput(result);
}
catch (Exception ex)
{
throw new Exception("R Script failed: " + result, ex);
}
}
Now objects have values like
info.FileName = C:\Program Files\R\R-3.4.3\bin\Rscript.exe
info.WorkingDirectory = C:\Program Files\R\R-3.4.3\bin
info.Arguments = "C:\MANOJ R\Topic modelling v2\TM_Webapi\Honeywell.UOP.TopicModel.Api\Uploads\h481821\TopicSearch.R" h481821 1
But process is not creating and its not calling R script and even it doesn't throwing any exception
Even I tried running VS as admin but no luck!
I have changed the .exe file path from
C:\Program Files\R\R-3.4.3\bin\Rscript.exe
to
C:\Program Files\R\R-3.4.3\bin\x64\Rscript.exe
Since I am using 64 bit machine
Now the process is working
My program allow user to insert bunch of images and one audio file, then can generate them into a video file. My program also allow user to provide duration for each images.
I am able to adding audio background into video output, but when video length is more longer than audio length, audio is not looping.
Also when audio length is more longer than video length, the video output will show blank till the end of audio.
Create Video
public bool CreateVideo(string name, List<string> imgs)
{
Bitmap bitmap = (Bitmap)null;
try
{
if (!Directory.Exists(this.outputFolder + "\\temp"))
Directory.CreateDirectory(this.outputFolder + "\\temp");
int num = this.rand.Next(this.delayMin, this.delayMax + 1);
List<string> stringList = new List<string>((IEnumerable<string>)imgs);
if (this.randomizeImages)
this.Shuffle((IList)stringList);
if (!string.IsNullOrEmpty(this.waterImage) && File.Exists(this.waterImage))
bitmap = (Bitmap)Image.FromFile(this.waterImage, true);
if (!string.IsNullOrEmpty(this.introImage))
{
int index = stringList.IndexOf(this.introImage);
if (index > 0)
{
string str = stringList[index];
stringList[index] = stringList[0];
stringList[0] = str;
}
}
for (int position = 0; position < stringList.Count; ++position)
this.ApplyWatermarkImage(stringList[position], position, (Image)bitmap);
if (bitmap != null)
bitmap.Dispose();
string str1 = "";
if (!string.IsNullOrEmpty(this.audioFile))
{
str1 = " -i \"" + this.audioFile + "\" -ar 22050 -ab 64k ";
if (this.GetAudioLength(this.audioFile) > num * stringList.Count)
str1 += "-shortest ";
}
string str2 = this.outputFolder + "\\" + name + ".avi";
ProcessStartInfo processStartInfo = new ProcessStartInfo(Environment.CurrentDirectory + "\\sm\\ffmpeg.exe", str1 + "-fflags +genpts -r 1/" + (object)num + " -b 32K -f image2 -i \"" + this.outputFolder + "\\temp\\%3d.jpg\" -vcodec mjpeg -s " + this.width.ToString() + "x" + this.height.ToString() + " -y -r 30 \"" + str2 + "\"");
Process process = new Process();
processStartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardError = true;
process.StartInfo = processStartInfo;
process.Start();
StreamReader standardError = process.StandardError;
Trace.WriteLine(standardError.ReadToEnd());
standardError.Close();
process.WaitForExit();
return process.ExitCode != 1 && process.ExitCode != -1;
}
catch (Exception ex)
{
Trace.WriteLine("CreateVideo: " + ex.Message);
return false;
}
finally
{
if (bitmap != null)
bitmap.Dispose();
try
{
if (Directory.Exists(this.outputFolder + "\\temp"))
Directory.Delete(this.outputFolder + "\\temp", true);
}
catch
{
}
}
}
Get Audio Length
public int GetAudioLength(string path)
{
string output = this.GetOutput(path);
int num = 0;
if (output == "" || output.Contains("Invalid data found when processing input") || output.Contains("could not find codec parameters"))
return num;
string str;
try
{
str = Regex.Match(output, "(?:Duration\\:)(.*?)(?:,)", RegexOptions.Singleline).Groups[1].Value.Trim();
}
catch (Exception ex)
{
str = "";
}
if (str != "")
{
try
{
num = int.Parse(str.Split(':')[0]) * 3600;
num += int.Parse(str.Split(':')[1]) * 60;
num += (int)double.Parse(str.Split(':')[2]);
}
catch (Exception ex)
{
}
}
return num;
}
Get Output
private string GetOutput(string video_file)
{
try
{
return Process.Start(new ProcessStartInfo()
{
FileName = Environment.CurrentDirectory + "\\sm\\ffmpeg.exe",
Arguments = "-i \"" + video_file + "\"",
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
}).StandardError.ReadToEnd();
}
catch (Exception ex)
{
return "";
}
}
I've looked around but couldn't find a solution. Any help will be greatly appreciated.
I'm using windows 10.
I'm trying to compile a c++ file within c# using MinGW(the MinGW folder is in the projects directory), but it won't compile a resource script (using windres).
Whenever I use windres in cmd it says: "C:/Users/username/AppData/Local/Temp/my.rc:1: unrecognized escape sequence".
but still works.
But when I run the exact same command through c# (by creating a process) it doesn't work at all and says: "The filename, directory name, or volume label syntax is incorrect.".
My code:
String tempDir = Path.GetTempPath();
String file = tempDir + "my.rc";
using (StreamWriter writer = new StreamWriter(file, false, Encoding.ASCII))
{
if (!textIcon.Text.Equals(""))
await writer.WriteLineAsync("25 ICON \"" + textIcon.Text + "\"");
if (checkAdmin.Checked)
{
String manifest = tempDir + #"\manifest.xml";
createManifest(manifest);
await writer.WriteLineAsync("55 24 \"" + manifest + "\"");
}
}
String args2 = "/c \"" + Path.Combine(gccLocation, "windres.exe") + "\" -o \"" + Path.Combine(tempDir, "my.o").Replace("\\", "/") + "\" \"" + file.Replace("\\", "/") + "\"";
//Debug
//args2 = "/k echo " + args2;
ProcessStartInfo psi2 = new ProcessStartInfo();
psi2.FileName = "CMD.exe";
psi2.Arguments = args2;
psi2.UseShellExecute = false;
psi2.CreateNoWindow = true;
//Debug
//psi2.CreateNoWindow = false;
Process windres = Process.Start(psi2);
windres.WaitForExit();
if(windres.ExitCode != 0)
{
MessageBox.Show("Error: Could not create resource file (" + windres.ExitCode + ")");
}
Ended up using a batch file to run the command.
String args2 = "windres.exe -i \"" + Path.GetFullPath(file) + "\" -o \"" + Path.Combine(tempDir, "my.o") + "\"" ;
using (StreamWriter writer = new StreamWriter(tempDir + #"\my.bat", false, Encoding.ASCII))
{
await writer.WriteLineAsync("#echo off");
await writer.WriteLineAsync("cd " + Path.GetFullPath(gccLocation));
await writer.WriteLineAsync(args2);
}
//Debug
//args2 = "/k echo " + args2;
ProcessStartInfo psi2 = new ProcessStartInfo();
psi2.FileName = tempDir + #"\my.bat";
psi2.UseShellExecute = false;
psi2.CreateNoWindow = true;
//Debug
//psi2.CreateNoWindow = false;
Process windres = Process.Start(psi2);
windres.WaitForExit();
I have winforms c# project and in that I have two .txt files i.e., credentials.txt and RetailButton_Exception.txt. Now I have given path to D: drive at development side. Now what if I install my application in different pc which does not have D: ?
I have given the code for saving these files as follow:-
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string Log_API = "http://api.retailbutton.co/WS/Service.php?Service=employeeLogin";
if (LoginUser(Log_API))
{
logIn_Status = "true";
GlolbalUtil.authenticate = "true";
GlolbalUtil.LogIn_Status = logIn_Status;
this.Hide();
//string credentialPath = #"D:\credentials.txt";
String test = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (File.Exists(test + "credentials.txt"))
{
using (StreamWriter writer = new StreamWriter(test, true))
{
//writer.WriteLine("UserName :" + txtUsername.Text + Environment.NewLine + "Password :" + txtPassword.Text);
writer.WriteLine(txtUsername.Text);
writer.WriteLine(txtPassword.Text);
}
frmDash frmDash = new frmDash();
frmDash.Owner = this;
frmDash.Show();
txtUsername.Text = "";
txtPassword.Text = "";
}
else
{
using(FileStream fs = File.Create(test))
{
#region
using (StreamWriter writer = new StreamWriter(test, true))
{
//writer.WriteLine("UserName :" + txtUsername.Text + Environment.NewLine + "Password :" + txtPassword.Text);
writer.WriteLine(txtUsername.Text);
writer.WriteLine(txtPassword.Text);
}
frmDash frmDash = new frmDash();
frmDash.Owner = this;
frmDash.Show();
txtUsername.Text = "";
txtPassword.Text = "";
#endregion
}
#region
//using (StreamWriter writer = new StreamWriter(credentialPath, true))
//{
// //writer.WriteLine("UserName :" + txtUsername.Text + Environment.NewLine + "Password :" + txtPassword.Text);
// writer.WriteLine(txtUsername.Text);
// writer.WriteLine(txtPassword.Text);
//}
//frmDash frmDash = new frmDash();
//frmDash.Owner = this;
//frmDash.Show();
//txtUsername.Text = "";
//txtPassword.Text = "";
#endregion
}
//GlolbalUtil.accept_status = "1";
}
else
{
MessageBox.Show("Please Check Username and password");
}
}
catch (Exception ex)
{
string filePath = #"D:\RetailButton_Exception.txt";
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
}
}
The answer is simple - you shouldn't use absolute path. Choose one of specific system folders depending on what you're doing. Check folders here I suggest using ApplicationData if it's per user files. Or use CommonApplicationData if it's per system files.
That's how most of the applications behave now. Don't try to store app created files in your installation folder cause it's not per user. It's per machine.
It may be even prohibited for your app to write to Program Files cause it's folder is not intended to store application configuration.
An example from msdn on how to use SpecialFolders.
// Sample for the Environment.GetFolderPath method
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
Console.WriteLine("GetFolderPath: {0}",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
}
Sample how to store info there:
static void Main(string[] args)
{
var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "userinfo.txt");
using (var writer = new StreamWriter(file))
{
writer.WriteLine("Hello, World!");
}
}
You can also use Application.StartupPath for building you path, it is the path where you executable is placed.
string credentialFilePath = Path.Combine(Application.StartupPath, "credentials.txt");
string retailExceptionFilePath = Path.Combine(Application.StartupPath, "RetailButton_Exception.txt");
You can place your txt files in the same folder with your compiled exe file.
Then, you can use a relative path like this:
File.WriteAllText(#"credentials.txt", String.Empty);
If your application will be installed on:
C:\Program Files\YourApplication\yourapplication.exe
Then it will try to open
C:\Program Files\YourApplication\credentials.txt
Moreover, you can add your txt files to a Visual Studio project and set a property Copy To Output Directory to Copy if newer.
After that your output directory will always have these two files and it will be easier for you to work with it.
Just use your application folder, you can use it by Application.StartupPath
try doing this
string yourfilepath = Application.StartupPath + "credentials.txt";
string secondfile = Application.StartupPath + "RetailButton_Exception.txt";
when I run this code:
static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var searchDirectory = new DirectoryInfo(currentDirectory);
var queryMatchingFiles =
from file in searchDirectory.GetFiles()
let fileContent = System.IO.File.ReadAllText(file.Name)
select file.Name;
StreamWriter outputCacheMeta = new StreamWriter(#"output.txt");
foreach (var fileName in queryMatchingFiles.Where(fileName => !fileName.EndsWith(".txt") && !fileName.EndsWith(".exe") && !fileName.EndsWith(".xz")))
{
// start the converion utility
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "xz.exe";
startInfo.Arguments = "-k -z " + fileName;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
using (Process p = Process.Start(startInfo))
{
while (!p.HasExited)
{
Thread.Sleep(300);
}
}
//Process.Start(startInfo);
Console.WriteLine(string.Format("Compressing file: '{0}'", fileName.ToString()));
// generate final string
FileInfo inFile = new FileInfo(fileName);
FileInfo outFile = new FileInfo(fileName + ".xz");
outputCacheMeta.WriteLine("<ContentFile Name=\"" + fileName.ToString() + "\" Size=\"" + inFile.Length.ToString() + "\" SHA1Hash=\"" + HashCalc.GetSHA1Hash(fileName).ToString() + "\" CompressedSize=\"" + outFile.Length.ToString() + "\" />");
//Console.WriteLine(string.Format(("<ContentFile Name=\"" + fileName.ToString() + "\" Size=\"" + inFile.Length.ToString() + "\" SHA1Hash=\"" + HashCalc.GetSHA1Hash(fileName).ToString() + "\" CompressedSize=\"" + outFile.Length.ToString() + "\" />")));
}
}
it does not print everything in the output file (output.txt), it prints this: http://pastebin.com/1vTQZVih (sorry for external link).
The problem is that it suddenly 'stops' writing to the output file.
Thanks!
You are not Flush()ing or Close()ing your StreamWriter before your program exits. Some of your file data is buffered to be written to the file, but will not actually get written until your flush and and close the stream.