My code
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Clear();
var img = new Bitmap(openFileDialog1.FileName);
//var ocr = new TesseractEngine("./tessdata", "eng", EngineMode.TesseractAndCube);
var ocr = new TesseractEngine("./rus", "rus", EngineMode.TesseractAndCube);
var page = ocr.Process(img);
textBox1.Text = page.GetText();
}
}
Code works fine with English trained data, but it throws an error when I change it to Russian.
Here is the error:
Tesseract.TesseractException: "Failed to initialise tesseract engine..
See https://github.com/charlesw/tesseract/wiki/Error-1 for details."
My Tesseract version is 3.0.2.
I've downloaded Russian tessdata files from https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-302
work for me
Tesseract tesseract = new Tesseract();
tesseract.setLanguage("rus");
try {
tesseract.setDatapath("/home/test/tessdata");
String text = tesseract.doOCR(new File("/home/test/Pictures/photo.jpg"));
System.out.print(text);
} catch (TesseractException e) {
e.printStackTrace();
}
test data - https://github.com/tesseract-ocr/tessdata
Confirmed that problem. Tesseract can run with single language (I've tried bul.traineddata). But "rus" always gives that result in logcat:
Could not initialize Tesseract API with language=rus!
Of cause I've had rus.traineddata file in assets :-)
Related
I am making an application which inserts text into a pdf template, but I am encountering a problem and it is that when I want to use the template it is as if I could not find it, so I did a validation with File.Exists, and it effectively returns me false, but when I look for the same path in the file explorer it finds me the pdf without problems.
This is my code:
protected void btn_Guardar_Click(object sender, EventArgs e)
{
try
{
string newName = $"numdoc_{ddl_TipoCapacitacion.SelectedValue}-{lastId.Rows[0]["ID"]}-{DateTime.Now.ToString("dd/MM/yyyy").Replace("/", String.Empty)}.pdf";
file = Path.Combine(location, newName);
string oldFile = string.Concat(Server.MapPath($#"~/plantillasPdf/capacitaciones/plantillaDiploma.pdf"));
string newFile = string.Concat(Server.MapPath($#"~/plantillasPdf/capacitaciones/{newName}"));
if (!File.Exists(oldFile))
{
}
PdfReader reader = new PdfReader(oldFile);
...
catch (Exception ex)
{
ControlarExcepcion(ex);
}
}
I am trying to load a picture from my PC as a raw image in order to use it with the Microsoft cognitive services emotion (UWP).
below is a piece of my code:
//Chose Image from PC
private async void chosefile_Click(object sender, RoutedEventArgs e)
{
//Open Dialog
FileOpenPicker open = new FileOpenPicker();
open.ViewMode = PickerViewMode.Thumbnail;
open.SuggestedStartLocation = PickerLocationId.Desktop;
open.FileTypeFilter.Add(".jpg");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".gif");
open.FileTypeFilter.Add(".png");
file = await open.PickSingleFileAsync();
if (file != null)
{//imagestream is declared as IRandomAccessStream.
imagestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var image = new BitmapImage();
image.SetSource(imagestream);
imageView.Source = image;
}
else
{
//
}
}
The part above works fine, it selects a photo from the pc (dialog box) and displays it in Image box.
private async void analyse_Click(object sender, RoutedEventArgs e)
{
try
{
emotionResult = await emotionServiceClient.RecognizeAsync(imagestream.AsStream());
}
catch
{
output.Text = "something is wrong in stream";
}
try {
if(emotionResult!= null)
{
Scores score = emotionResult[0].Scores;
output.Text = "Your emotions are: \n" +
"Happiness: " + score.Happiness + "\n" +
"Sadness: " + score.Sadness;
}
}
catch
{
output.Text = "Something went wrong";
}
}
I think the error is due to imagestream.AsStream()
imagestream is declared as IRandomAccessStream.
Can someone please tell me how to fix that part and if the error is in fact due to not loading the image correctly?
EDIT:
Also is there a better way to do this, instead of using stream to pass the emotionServiceClient a saved file instead of a stream?
Your problem is that you've advanced the stream position by virtue of creating the BitmapImage, so your read position is at the end by the time you call emotionServiceClient.RecognizeAsync. So you'll need to 'rewind':
var stream = imagestream.AsStreamForRead();
stream.Position = 0;
emotionResult = await emotionServiceClient.RecognizeAsync(stream);
Why not use their example, instead of trying to hold the file in memory, why don't you hold a path, and then use the path to read the stream at the time.
https://www.microsoft.com/cognitive-services/en-us/Emotion-api/documentation/GetStarted
In there example;
using (Stream imageFileStream = File.OpenRead(imageFilePath))
{
//
// Detect the emotions in the URL
//
emotionResult = await emotionServiceClient.RecognizeAsync(imageFileStream);
return emotionResult;
}
So you would be capturing imageFilePath as the result of the open file dialog.
I'm trying to convert a pdf into a PNG, using the code given in the following example (the first function) : https://ghostscriptnet.codeplex.com/SourceControl/latest#Ghostscript.NET/Ghostscript.NET.Samples/Samples/DeviceUsageSample.cs
However, I get this error on launch : " An error occured when call to 'gsapi_init_with_args' is made: -100"... which doesn't mean a lot.
How comes this basic example doesn't work ? I downloaded the latest Ghostscript.NET.dll here : https://ghostscriptnet.codeplex.com/ and added it to the references of the project. My OS is Windows 7 x32 bits and I run VisualStudio as an administrator.
Here is my code :
private void button6_Click(object sender, EventArgs e)
{
GhostscriptPngDevice devPNG = new GhostscriptPngDevice(GhostscriptPngDeviceType.Png256);
devPNG.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
devPNG.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
devPNG.ResolutionXY = new GhostscriptImageDeviceResolution(96, 96);
devPNG.InputFiles.Add(#"D:\Public\FOS.pdf");
devPNG.OutputPath = #"D:\Public\FOS.png";
devPNG.Process();
}
I tried replacing the path of the input and output by one without any space and it now works ! Here is the code I ended up using :
using Ghostscript.NET.Rasterizer;
private void button6_Click(object sender, EventArgs e)
{
int desired_x_dpi = 96;
int desired_y_dpi = 96;
string inputPdfPath = #"D:\Public\temp\rasterizer\FOS.pdf";
string outputPath = #"D:\Public\temp\rasterizer\output\";
using (var rasterizer = new GhostscriptRasterizer())
{
rasterizer.Open(inputPdfPath);
for (var pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++)
{
var pageFilePath = Path.Combine(outputPath, string.Format("Page-{0}.png", pageNumber));
var img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
img.Save(pageFilePath + "ImageFormat.Png");
}
}
}
Try to replace any character strange (non alpanumeric and spaces, keep filepath "clean" and in shared/temp folder to grant access to any user/process and should work just fine
I have asp:FileUpload and I want to save all uploaded images of all acceptable formats as png images in the Images forlder on website, my upload code is:
protected void btnSave_Click(object sender, EventArgs e)
{
if (fup2.HasFile)
{
Regex reg = new Regex(#"(?i).*\.(gif|jpe?g|png|tif)$");
string uFile = fup2.FileName;
if (reg.IsMatch(uFile))
{
string saveDir = Server.MapPath(#"~/Images/");
string SavePath = saveDir + uFile;
fup2.SaveAs(SavePath);
}
else
{
Response.Write("Error");
}
}
}
I also tried using
var tempImg = Image.FromFile(Server.MapPath(#"~/Images/"));
tempImg.Save("a.tiff", ImageFormat.png);
It keeps throwing file not found exception
Any new ideas?
Use Bitmap.FromStream. Something like:
using System.Drawing;
protected void btnSave_Click(object sender, EventArgs e)
{
if (fup2.HasFile)
{
Regex reg = new Regex(#"(?i).*\.(gif|jpe?g|png|tif)$");
string uFile = fup2.FileName;
if (reg.IsMatch(uFile))
{
string saveDir = Server.MapPath(#"~/Images/");
string SavePath = saveDir + Path.GetFileName(uFile) + ".png";
Bitmap b = (Bitmap)Bitmap.FromStream(fup2.PostedFile.InputStream);
b.Save(SavePath, ImageFormat.Png);
}
else
{
Response.Write("Error");
}
}
}
The Image.FromFile -> Save should do the trick, but i don't see how you are using the correct path - you just point at the directory and not the actual file when calling FromFile
As a side note, doing this processing on a web processing thread is not a great idea but for small load it could work.
While i am trying to save Image getting this error
A generic error occurred in GDI+
I searched for this error and checked write permissions for this folder ,and also checked that image file is not in use by anything else (including my code) But While I am trying to save Image still getting same error,Where is the mistake
public partial class AdsMaster : Form
{
OpenFileDialog ofd=null;
public AdsMaster()
{
InitializeComponent();
}
private void browseButton_Click(object sender, EventArgs e)
{
ofd = new OpenFileDialog();
ofd.Filter = "image files|*.jpg;*.jpeg;*.gif;*.png;*.bmp";
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);//create the bitmap
string imgName = ofd.SafeFileName;
txtImagePath.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
img.Dispose();
}
}
private void saveImage_Click(object sender, EventArgs e)
{
String str = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string path = str + "\\Image\\";
Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
try
{
img.Save(path + imgName); //getting error at this line
MessageBox.Show("Image is saved");
img.Dispose(); // dispose of your image
}
catch(Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
}
I think the problem here may be due to the fact that a lock is placed on the original image when you call
Image img = new Bitmap(ofd.FileName);
The following should do the trick
private void saveImage_Click(object sender, EventArgs e)
{
string str = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string path = str + "\\Image\\";
string imgName = ofd.SafeFileName;
try
{
File.Copy(ofd.FileName, path + imgName);
MessageBox.Show("Image is saved");
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
I resolve this error by changing the file name and path to where the file is stored.
You needs to check either one of them-
1- FileName should be different/ should not get matched with other files name which have been already present on that location where new file/image you want to store.
2- change the (save ) location of the new file from operating system drive.
try to avoid to store the new file/Image on a drive on which operating system has been already installed.
Below code works for me
IWebdriver driver;
driver = new ChromeDriver("G:\\Selenium_Csharp\\Jar\\chromedriver_win32");
driver.Navigate().GoToUrl("http://www.gmail.com");
driver.Manage().Window.Maximize();
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile("e:\\pande", System.Drawing.Imaging.ImageFormat.Jpeg);