/***************************************************************************/ /* This function will OCR and convert the source image from the input */ /* path specified through the Job class and will save the converted file */ /* into the output path the client also specified. */ /***************************************************************************/ public override void OnJobReceived(string id, string userToken, string jobMetadata, string jobType, int progressRate) { _jobId = id; try { // Check if we have valid job information and job metadata if (string.IsNullOrEmpty(jobMetadata)) { SetFailureStatus(_jobId, (int)RasterExceptionCode.InvalidParameter, Leadtools.RasterException.GetCodeMessage(RasterExceptionCode.InvalidParameter), null); return; } using (Timer updateStatusTimer = new Timer(new TimerCallback(UpdateStatusProc), _jobId, 0, progressRate * SECONDS_TO_MILLISECONDS_FACTOR)) { OcrData data = OcrData.DeserializeFromString(jobMetadata); data.DocumentFileName = BuildOutputFile(data); DoRecognizeAndSave(data); } } catch (RasterException ex) { SetFailureStatus(id, (int)ex.Code, ex.Message, null); } catch (OcrException ex) { SetFailureStatus(id, (int)ex.Code, ex.Message, null); } catch (Exception ex) { SetFailureStatus(id, 0, ex.Message, null); } }
protected void _btnAddJob_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(_cmbSourceFiles.Text)) { return; } OcrData ocrData = new OcrData(_cmbSourceFiles.Text, _outputFilesUrl, _cmbDocumentFormats.Text); // Add new job. AddJobRequest jobRequest = new AddJobRequest(); jobRequest.JobType = "OCR"; jobRequest.UserToken = _hiddenFieldClientMetadata.Value; jobRequest.JobMetadata = OcrData.SerializeToString(ocrData); AddJobResponse addJobResponse = _jobService.AddJob(jobRequest); GetJobInformationRequest getJobInfoRequest = new GetJobInformationRequest(); getJobInfoRequest.ID = addJobResponse.Id; GetJobInformationResponse getJobInfoResponse = _jobService.GetJobInformation(getJobInfoRequest); AddJobToGridView(getJobInfoResponse.JobInformation); GetClientJobs(); }
private void _menuItemOpenConvertedFile_Click(object sender, EventArgs e) { foreach (DataGridViewRow selectedJob in _dgvJobs.SelectedRows) { try { if (selectedJob.Cells[JobProcessorConstants.Database.StatusColumn].Value != DBNull.Value && String.Compare((string)selectedJob.Cells[JobProcessorConstants.Database.StatusColumn].Value, JobStatus.Completed.ToString(), true) == 0) { string jobType = selectedJob.Cells[JobProcessorConstants.Database.JobTypeColumn].Value != DBNull.Value ? (string)selectedJob.Cells[JobProcessorConstants.Database.JobTypeColumn].Value : String.Empty; string jobMetadata = selectedJob.Cells[JobProcessorConstants.Database.JobMetadataColumn].Value != DBNull.Value ? (string)selectedJob.Cells[JobProcessorConstants.Database.JobMetadataColumn].Value : String.Empty; if (String.Compare(jobType, "OCR", true) == 0) { StartProcess(OcrData.DeserializeFromString(jobMetadata).DocumentFileName); } else if (String.Compare(jobType, "Multimedia", true) == 0) { StartProcess(MultimediaData.DeserializeFromString(jobMetadata).TargetFile); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } }
private void button2_Click(object sender, EventArgs e) { button2.Enabled = false; var tx = button2.Text; button2.Text = "Reading..."; Bitmap imgFor = processImgForScanning(origImg); OcrData OcrData1 = Processor.RunOCR(imgFor, OcrPageMode.SingleBlock); richTextBox1.Text = OcrData1.ReadText; button2.Enabled = true; button2.Text = tx; //Stream imageStreamSource = new FileStream(@"D:\\ocrd_image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read); // using (MemoryStream memstream = new MemoryStream()) //{ // memstream.SetLength(imageStreamSource.Length); // imageStreamSource.Read(memstream.GetBuffer(), 0, (int)imageStreamSource.Length); // imageStreamSource.Close(); // pictureBox2.BackgroundImage = Bitmap.FromStream(memstream); //} pictureBox2.BackgroundImage = Crop(imgFor, OcrData1.TargetArea.X1, OcrData1.TargetArea.Y1, OcrData1.TargetArea.Width, OcrData1.TargetArea.Height); //GetSlices(origImg); // Bitmap imgI = (Bitmap)pictureBox2.BackgroundImage; //imgI =FixBG(imgI); //DetectColorWithUnsafeParallel(imgI, 255, 255, 255,(byte)int.Parse(textBox1.Text)); // pictureBox2.BackgroundImage = imgI; }
/// <summary> /// Initializes a new instance of the PhotoSelector class. /// </summary> public PhotoSelector() { InitializeComponent(); this.ocrData = OcrData.Instance; this.cameraCaptureTask = new CameraCaptureTask(); this.photoChooserTask = new PhotoChooserTask(); this.cameraCaptureTask.Completed += new System.EventHandler <PhotoResult>(this.PhotoChooserCompleted); this.photoChooserTask.Completed += new EventHandler <PhotoResult>(this.PhotoChooserCompleted); }
private double photoAngle; // Wrapped by this.PhotoAngle /// <summary> /// Initializes a new instance of the PhotoAreaViewModel class. /// </summary> /// <param name="ocrData"> /// A reference to the OcrData instance that stores the /// photo stream and the text obtained after the OCR conversion. /// </param> /// <param name="ocrConversionStateManager"> /// A reference to the OcrConversionStateManager instance that stores the /// status of the last OCR conversion. /// </param> public PhotoAreaViewModel(OcrData ocrData, OcrConversionStateManager ocrConversionStateManager) : base(ocrData, ocrConversionStateManager) { this.OcrData.PropertyChanged += new PropertyChangedEventHandler(this.OcrData_PropertyChanged); // If the photo stream is available when this instance is created we'll call OnPhotoStreamChanged // to update all properties related to the photo. if (this.OcrData.PhotoStream != null) { this.OnPhotoStreamChanged(); } }
/// <summary> /// Initializes a new instance of the OcrViewModelBase class. /// </summary> /// <param name="ocrData"> /// A reference to the OcrData instance that stores the /// photo stream and the text obtained after the OCR conversion. /// </param> /// <param name="ocrConversionStateManager"> /// A reference to the OcrConversionStateManager instance that stores the /// status of the last OCR conversion. /// </param> public OcrViewModelBase(OcrData ocrData, OcrConversionStateManager ocrConversionStateManager) { if (ocrData == null) { throw new ArgumentNullException("ocrData"); } if (ocrConversionStateManager == null) { throw new ArgumentNullException("ocrConversionStateManager"); } this.OcrData = ocrData; this.OcrConversionStateManager = ocrConversionStateManager; }
string BuildOutputFile(OcrData ocrData) { //Format the target file like <output directory>\<source filename>_<source file extension>_<Guid>.<new extension> string ext = Path.GetExtension(ocrData.ImageFileName); if (!string.IsNullOrEmpty(ext)) { ext = ext.Replace(".", ""); } if (!string.IsNullOrEmpty(ext)) { ext = "_" + ext; } else { ext = string.Empty; } string name = Path.GetFileNameWithoutExtension(ocrData.ImageFileName); DocumentFormat documentFormat = (DocumentFormat)Enum.Parse(typeof(DocumentFormat), ocrData.DocumentFormat, true); name = string.Format( "{0}{1}_{2}.{3}", name, ext, Guid.NewGuid(), DocumentWriter.GetFormatFileExtension(documentFormat)); string fullPath = string.Empty; // If DocumentFileName is a file, this is a full path (from a previous conversion). In this case need, we to get the directory name and append the new file name. // We cannot check the file itself because it may no longer exist so we use the extension in the path to indicate if it is a file if (String.IsNullOrEmpty(Path.GetExtension(ocrData.DocumentFileName))) { fullPath = ocrData.DocumentFileName; //path is a directory } else { fullPath = Path.GetDirectoryName(ocrData.DocumentFileName);//This is a file } if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } return(Path.Combine(fullPath, name)); }
/// <summary> /// Initializes a new instance of the MainPage class. /// </summary> public OcrMainPage() { InitializeComponent(); if (this.VerifyHawaiiAppId()) { this.ocrData = OcrData.Instance; this.ocrData.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(this.OcrData_PropertyChanged); this.ocrConversionStateManager = OcrConversionStateManager.Instance; this.ocrConversionStateManager.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(this.ConversionStateManager_PropertyChanged); this.mainPivot.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.MainPivot_SelectionChanged); } Debug.WriteLine("----------------------------\ntesting REST CLIENT\n------------------------------------"); RestClient rc = new RestClient(); }
public static async Task <ContactCard> ReadBusinessCard(byte[] fileContent) { OcrData data = await GetOCRData(fileContent).ConfigureAwait(false); ContactCard contact = new ContactCard(); Region region = data.Regions[0]; contact.Name = region.Lines.Count > 0 ? string.Join(" ", region.Lines[0].Words.Select(a => a.Text)) : string.Empty; contact.Company = region.Lines.Count > 1 ? string.Join(" ", region.Lines[1].Words.Select(a => a.Text)) : string.Empty; contact.Position = region.Lines.Count > 2 ? string.Join(" ", region.Lines[2].Words.Select(a => a.Text)) : string.Empty; contact.PhoneNo = GetFromRegex(region, Constants.RegexPatterns.Phone); contact.Email = GetFromRegex(region, Constants.RegexPatterns.Email); contact.Website = GetFromRegex(region, Constants.RegexPatterns.Website, Constants.RegexPatterns.WebsiteFacebook); contact.Facebook = GetFromRegex(region, Constants.RegexPatterns.Facebook); contact.Twitter = GetFromRegex(region, Constants.RegexPatterns.Twitter); return(contact); }
/// <summary> /// Set OCR Results, and Orientation Confidence on an Object /// </summary> /// <param name="results"> The Orientation Results from the OCR execution </param> /// <param name="orienationConfidence"> Absolute Orientation Confidence </param> /// <param name="isUpsideDown"> Indicates if True orientation is different than the current </param> public void AddOcrData(OcrData results, long orienationConfidence, bool isUpsideDown) { AddOcrData(results); _trueOrientation = isUpsideDown ? Enumeration.Opposite(Orientation) : Orientation; OrientationConfidence = orienationConfidence; }
private void BindGrid(int rowcount, JobServiceReference.JobInformation jobInformation) { if (jobInformation == null) { return; } //Only show ocr jobs in this demo if (String.Compare(jobInformation.JobType, "OCR", true) != 0) { return; } OcrData ocrData = OcrData.DeserializeFromString(jobInformation.Metadata.JobMetadata); string inputFileName = ocrData.ImageFileName.Length > 0 ? Path.GetFileName(ocrData.ImageFileName) : String.Empty; string outputFileName = jobInformation.Status == JobStatus.Completed && ocrData.DocumentFileName.Length > 0 ? Path.GetFileName(ocrData.DocumentFileName) : String.Empty; DataColumn[] dataColums = new DataColumn[] { new DataColumn("Job ID", typeof(string)), new DataColumn("Status", typeof(string)), new DataColumn("Worker", typeof(string)), new DataColumn("Percentage", typeof(int)), new DataColumn("Added Data/Time", Nullable.GetUnderlyingType(typeof(Nullable <DateTime>))), new DataColumn("Completed Data/Time", Nullable.GetUnderlyingType(typeof(Nullable <DateTime>))), new DataColumn("Error ID", typeof(int)), new DataColumn("Error Message", typeof(string)), new DataColumn("Input File", typeof(string)), new DataColumn("Output File", typeof(string)), new DataColumn("Full Path", typeof(string)), new DataColumn("Target Format", typeof(string)), }; DataTable dt = new DataTable(); dt.Columns.AddRange(dataColums); DataRow dr; if (ViewState["CurrentData"] != null) { for (int i = 0; i < rowcount; i++) { dt = (DataTable)ViewState["CurrentData"]; if (dt.Rows.Count > 0) { dr = dt.NewRow(); dr[0] = dt.Rows[i][0].ToString(); dr[1] = dt.Rows[i][1].ToString(); dr[2] = dt.Rows[i][2].ToString(); dr[3] = dt.Rows[i][3].ToString(); if (dt.Rows[i][3] != null) { dr[4] = dt.Rows[i][4]; } else { dr[4] = DBNull.Value; } if (dt.Rows[i][4] != null) { dr[5] = dt.Rows[i][5]; } else { dr[5] = DBNull.Value; } dr[6] = dt.Rows[i][6].ToString(); dr[7] = dt.Rows[i][7].ToString(); dr[8] = dt.Rows[i][8].ToString(); dr[9] = dt.Rows[i][9].ToString(); dr[10] = dt.Rows[i][10].ToString(); dr[11] = dt.Rows[i][11].ToString(); } } if (jobInformation != null) { dr = dt.NewRow(); dr[0] = jobInformation.ID; dr[1] = jobInformation.Status; dr[2] = jobInformation.Worker; dr[3] = jobInformation.Percentage; if (jobInformation.AddedTime != null) { dr[4] = jobInformation.AddedTime; } else { dr[4] = DBNull.Value; } if (jobInformation.CompletedTime != null) { dr[5] = jobInformation.CompletedTime; } else { dr[5] = DBNull.Value; } dr[6] = jobInformation.FailureInformation.FailedErrorID; dr[7] = jobInformation.FailureInformation.FailedMessage; dr[8] = inputFileName; dr[9] = outputFileName; dr[10] = _outputFilesName + outputFileName; dr[11] = ocrData.DocumentFormat; dt.Rows.Add(dr); } } else { if (jobInformation != null) { dr = dt.NewRow(); dr[0] = jobInformation.ID; dr[1] = jobInformation.Status; dr[2] = jobInformation.Worker; dr[3] = jobInformation.Percentage; if (jobInformation.AddedTime != null) { dr[4] = jobInformation.AddedTime; } else { dr[4] = DBNull.Value; } if (jobInformation.CompletedTime != null) { dr[5] = jobInformation.CompletedTime; } else { dr[5] = DBNull.Value; } dr[6] = jobInformation.FailureInformation.FailedErrorID; dr[7] = jobInformation.FailureInformation.FailedMessage; dr[8] = inputFileName; dr[9] = outputFileName; dr[10] = _outputFilesName + outputFileName; dr[11] = ocrData.DocumentFormat; dt.Rows.Add(dr); } } // If ViewState has a data then use the value as the DataSource if (ViewState["CurrentData"] != null) { _gridViewClientJobs.DataSource = (DataTable)ViewState["CurrentData"]; _gridViewClientJobs.DataBind(); } else { // Bind GridView with the initial data associated in the DataTable _gridViewClientJobs.DataSource = dt; _gridViewClientJobs.DataBind(); } // Store the DataTable in ViewState to retain the values ViewState["CurrentData"] = dt; }
/// <summary> /// Parallelized Recognize Function takes in a list or array of images, /// A specified length and for each image returns an OCRData object /// </summary> /// <param name="images"> Array or List of Bitmaps </param> /// <param name="length"> Number of items to be Recognized from the array </param> /// <param name="mode"> Accuracy Mode </param> /// <param name="lang"> Desired OCR Language </param> /// <param name="enableTimer"> Enables OCR Scan Timer if true </param> /// <returns> </returns> public static OcrData[] ParallelRecognize(IEnumerable<Bitmap> images, int length, Accuracy mode = Accuracy.High, string lang = "eng", bool enableTimer = false) { Tuple<int, Bitmap>[] indexedImages = new Tuple<int, Bitmap>[length]; int index = 0; foreach (Bitmap image in images) { if (index >= length) { break; } indexedImages[index] = new Tuple<int, Bitmap>(index, image); index += 1; } ConcurrentDictionary<int, OcrData> safeMap = new ConcurrentDictionary<int, OcrData>(); Parallel.ForEach(indexedImages, pair => { int position = pair.Item1; Bitmap image = pair.Item2; safeMap[position] = Recognize(image, mode, lang, enableTimer); }); OcrData[] data = new OcrData[length]; foreach (KeyValuePair<int, OcrData> kvpair in safeMap) { data[kvpair.Key] = kvpair.Value; } return data; }
private void DoRecognizeAndSave(OcrData ocrData) { // Read and retrieve the Ocr job parameters from the JobMetadata XML string sent through Job.JobMetadata using (IOcrEngine ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, false)) { try { string executingAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string ocrEnginePath = null; if (!String.IsNullOrEmpty(executingAssemblyPath)) { ocrEnginePath = Path.Combine(executingAssemblyPath, @"..\..\common\OcrLEADRuntime"); if (!Directory.Exists(ocrEnginePath)) { ocrEnginePath = null; } } ocrEngine.Startup(null, null, null, ocrEnginePath); DocumentFormat documentFormat = (DocumentFormat)Enum.Parse(typeof(DocumentFormat), ocrData.DocumentFormat, true); if (ocrEngine.DocumentWriterInstance != null) { SetDocumentWriterOptions(ocrEngine.DocumentWriterInstance, documentFormat); } using (DocumentConverter documentConverter = new DocumentConverter()) { documentConverter.SetOcrEngineInstance(ocrEngine, true); documentConverter.Diagnostics.EnableTrace = true; var jobData = DocumentConverterJobs.CreateJobData(ocrData.ImageFileName, ocrData.DocumentFileName, documentFormat); var job = documentConverter.Jobs.CreateJob(jobData); if (null != documentConverter.OcrEngineInstance) { documentConverter.OcrEngineInstance.AutoRecognizeManager.JobOperation += new EventHandler <OcrAutoRecognizeJobOperationEventArgs>(AutoRecognizeManager_JobOperation); documentConverter.OcrEngineInstance.AutoRecognizeManager.JobCompleted += new EventHandler <OcrAutoRecognizeRunJobEventArgs>(AutoRecognizeManager_JobCompleted); } documentConverter.Jobs.RunJob(job); if (null != documentConverter.OcrEngineInstance) { documentConverter.OcrEngineInstance.AutoRecognizeManager.JobOperation -= new EventHandler <OcrAutoRecognizeJobOperationEventArgs>(AutoRecognizeManager_JobOperation); documentConverter.OcrEngineInstance.AutoRecognizeManager.JobCompleted -= new EventHandler <OcrAutoRecognizeRunJobEventArgs>(AutoRecognizeManager_JobCompleted); } //Update job metadata with new filename SetCompletedStatus(_jobId, OcrData.SerializeToString(ocrData)); } } catch (RasterException ex) { SetFailureStatus(_jobId, (int)ex.Code, ex.Message, null); } catch (OcrException ex) { SetFailureStatus(_jobId, (int)ex.Code, ex.Message, null); } catch (Exception ex) { SetFailureStatus(_jobId, 0, ex.Message, null); } finally { ocrEngine.Shutdown(); } } }
public OcrTrainingDataViewModel() { ocrData = new OcrData(); Tolerance = 0.2f; FoundWords = new List<FoundTextData>(); }
public void Load(string fileName) { OcrData deserializedData = Serializer.DeSerialize(File.ReadAllBytes(fileName)) as OcrData; ocrData = deserializedData; foreach (string property in this.GetType().GetProperties().Select(p => p.Name)) { OnPropertyChanged(property); } }
private TextViewMode textViewMode; // Wrapped by this.TextViewMode /// <summary> /// Initializes a new instance of the TextAreaViewModel class. /// </summary> /// <param name="ocrData"> /// A reference to the OcrData instance that stores the /// photo stream and the text obtained after the OCR conversion. /// </param> /// <param name="ocrConversionStateManager"> /// A reference to the OcrConversionStateManager instance that stores the /// status of the last OCR conversion. /// </param> public TextAreaViewModel(OcrData ocrData, OcrConversionStateManager ocrConversionStateManager) : base(ocrData, ocrConversionStateManager) { }
private void _btnOCRAddJob_Click(object sender, EventArgs e) { //Validate conversion profile if (_cmbOCRFormat.SelectedIndex == -1) { MessageBox.Show("You must select a valid format", "Invalid Format"); return; } try { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Multiselect = true; ofd.Filter = "Image Files(*.CMP;*.CMW;*.PDF;*.TIF;*.TIFF;*.PNG;*.BMP;*.JPG;*.GIF)|*.CMP;*.CMW;*.PDF;*.TIF;*.TIFF;*.PNG;*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"; if (ofd.ShowDialog(this) == DialogResult.OK) { List <AddJobRequest> addJobRequestList = new List <AddJobRequest>(ofd.FileNames.Length); foreach (string file in ofd.FileNames) { //Create output directory. string outputDirectory = Path.Combine(Path.GetDirectoryName(file), "Dashboard Output"); if (!Directory.Exists(outputDirectory)) { try { Directory.CreateDirectory(outputDirectory); } catch { outputDirectory = Path.GetDirectoryName(file); } } //Create job metadata OcrData ocrData = new OcrData(file, outputDirectory, _cmbOCRFormat.Text); AddJobRequest addJobRequest = new AddJobRequest(); addJobRequest.UserToken = _userName; addJobRequest.JobMetadata = OcrData.SerializeToString(ocrData); addJobRequest.JobType = "OCR"; addJobRequestList.Add(addJobRequest); } using (JobServiceClient jobService = new JobServiceClient()) { //Add jobs as in a batch jobService.Endpoint.Address = new System.ServiceModel.EndpointAddress(string.Format("{0}/JobService.svc", _wcfAddress)); AddJobsRequest addJobsRequest = new AddJobsRequest(); addJobsRequest.AddRange(addJobRequestList); jobService.AddJobs(addJobsRequest); } MessageBox.Show("Job added successfully", "Success"); GetClientJobs(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } UpdateUI(); }
/// <summary> /// Standard Add OCR will filter a shred if it is empty /// </summary> /// <param name="results"> Shreds Ocr Data </param> public void AddOcrData(OcrData results) { OcrResult = results; if (OCR.StripNewLine(OcrResult.Text).Length <= OCR_EMPTY_THRESHOLD) { using (Bitmap bmp = new Bitmap(Filepath)) { IsEmpty = Filter.IsEmpty(bmp); } } else { IsEmpty = false; } }