Capture Check Routing Number Using Tesseract C# - ocr

I am using Tesseract library to capture account and routing number from check but some how it is not able to fetch the required information correctly. How can I get the correct information using tesseract?
C# Code:
using (var engine = new TesseractEngine(Server.MapPath(#"~/tessdata"), "eng", EngineMode.Default))
{
engine.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:;,.!-()#&÷");
// have to load Pix via a bitmap since Pix doesn't support loading a stream.
using (var image = new System.Drawing.Bitmap(imageFile.PostedFile.InputStream))
{
using (var pix = PixConverter.ToPix(image))
{
using (var page = engine.Process(pix))
{
meanConfidenceLabel.InnerText = String.Format("{0:P}", page.GetMeanConfidence());
resultText.InnerText = page.GetText();
}
}
}
}
Check Routing Number Image:
Result:

Related

Embedding MS-Office Documents Into AutoCAD Drawings Using Design Automation

I have a need to embed MS-Office documents (Excel, Word) into AutoCAD using Design Automation. Searching around the web, it seems that this is not possible because the MS-Office applications, which would act as an OLE Client, would need to be running on the Forge Server. Could someone confirm that this is the case?
If I am correct in my above statement, my next best alternative would be to embed .EMF files created from each page of the document I want to embed; alternatively using raster images would also be acceptable. Creating the .EMF or raster files is not a problem. I just can't find a solution for embedding the file that does not involve copying them to the clipboard and using the PASTECLIP command. This approach has worked for me in the AutoCAD application using a C# AutoCAD.NET plugin, an OLE2Frame object is created, but it fails in accoreconsole (because PASTECLIP uses a UI class which is not available). This leads me to think that the same would occur while running the bundle in Design Automation.
The best I have been able achieve so far is to write a raster image files to the working directory and linking the raster images to the AutoCAD document using RasterImageDef and RasterImage (code below). Is this the only way I can do this? Can I do something similar using an EMF image, which is vector based, instead of a raster image? Or is there a way to actually embed an EMF (preferred) or raster image instead of just linking the images?
The code below fails if I use .EMF files, because RasterImageDef and RasterImage do not support the the EMF file; the EMF file being a vector format, not a raster format?
[CommandMethod("TEST")]
public void Test()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// Get the file name of the image using the editor to prompt for the file name
// Create the prompt
PromptOpenFileOptions options = new PromptOpenFileOptions("Enter Sequence file path");
options.PreferCommandLine = true;
// Get the file name, use no quotes
PromptFileNameResult result = null;
try { result = ed.GetFileNameForOpen(options); }
catch (System.Exception ex)
{
DisplayLogMessage($"Could not get sequence file location. Exception: {ex.Message}.", ed);
return;
}
// Get the rtf filename from the results
string filename = result.StringResult;
DisplayLogMessage($"Got sequence filename: {filename}", ed);
// Load the Sequence.rtf document
Aspose.Words.Document seq;
using (FileStream st = new FileStream(filename, FileMode.Open))
{
seq = new Aspose.Words.Document(st);
st.Close();
}
DisplayLogMessage($"Aspose.Words Loaded: {filename}", ed);
Transaction trans = db.TransactionManager.StartTransaction();
// Get or create the image dictionary
ObjectId imageDictId = RasterImageDef.GetImageDictionary(db);
if (imageDictId != null)
imageDictId = RasterImageDef.CreateImageDictionary(db);
// Open the Image Dictonary
DBDictionary imageDict = (DBDictionary)trans.GetObject(imageDictId, OpenMode.ForRead);
double x = 0.0;
double y = 0.0;
try
{
// For each page in the Sequence.
for (int i = 0; i < seq.PageCount; i++)
{
DisplayLogMessage($"Starting page {i + 1}", ed);
// extract the page.
Aspose.Words.Document newSeq = seq.ExtractPages(i, 1);
Aspose.Words.Saving.ImageSaveOptions imgOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Emf);
imgOptions.Resolution = 300;
DisplayLogMessage($"Extracted page {i + 1}", ed);
string dictName = Guid.NewGuid().ToString();
filename = Path.Combine(Path.GetDirectoryName(doc.Name), dictName + ".Emf");
// Save the image
SaveOutputParameters sp = newSeq.Save(filename, imgOptions);
DisplayLogMessage($"Saved {dictName}.Emf", ed);
RasterImageDef imageDef = null;
ObjectId imageDefId;
// see if my guid is in there
if (imageDict.Contains(dictName))
imageDefId = (ObjectId)imageDict.GetAt(dictName);
else
{
// Create an image def
imageDef = new RasterImageDef();
imageDef.SourceFileName = $"./{dictName}.Emf";
// load the image
imageDef.Load();
imageDict.UpgradeOpen();
imageDefId = imageDict.SetAt(dictName, imageDef);
trans.AddNewlyCreatedDBObject(imageDef, true);
}
// create raster image to reference the definition
RasterImage image = new RasterImage();
image.ImageDefId = imageDefId;
// Prepare orientation
Vector3d uCorner = new Vector3d(8.5, 0, 0);
Vector3d vOnPlane = new Vector3d(0, 11, 0);
Point3d ptInsert = new Point3d(x, y, 0);
x += 8.5;
CoordinateSystem3d coordinateSystem = new CoordinateSystem3d(ptInsert, uCorner, vOnPlane);
image.Orientation = coordinateSystem;
// some other stuff
image.ImageTransparency = true;
image.ShowImage = true;
// Add the image to ModelSpace
BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
btr.AppendEntity(image);
trans.AddNewlyCreatedDBObject(image, true);
// Create a reactor between the RasterImage
// and the RasterImageDef to avoid the "Unreferenced"
// warning the XRef palette
RasterImage.EnableReactors(true); // in the original was true
image.AssociateRasterDef(imageDef);
}
trans.Commit();
}
catch (System.Exception ex)
{
DisplayLogMessage("ERROR: " + ex.Message,ed);
trans.Abort();
}
}
Raster images are always linked. There's no way to embed them. The only way to embed an image is to use AcDbOle2Frame (C++) or Autodesk.AutoCAD.DatabaseServices.Ole2Frame (C#). In theory, it is possible to create these objects without the "OLE server" being present but I haven't tried so I don't know if enough APIs are exposed to make it happen.
You should try it and see how far you can get.
Albert
There is way to embed raster image, it is not straightforeward, you need to use C++\ObjectARX API, please refer this https://github.com/MadhukarMoogala/EmbedRasterImage/tree/EmbedRasterImageUsingDBX

Save and retrive in forge viewer

I am using forge viewer for displaying AutoCAD files.
Also using the drawing tool over viewer based on the sample source.
I will draw the area by using box or sphere draw tools.
I need to save the current viewer including box or sphere area which I was marked over viewer and when again loading same file the area which has been marked that should be bind default.
How it is possible please help me
Suggest any way to implement this scenario.
Thanks in advance.
You can do that with 2 steps.
First, taking advantage of Object3D.toJSON() method.
Let's summarize in a sample where we generate a JSON object from our mesh:
//here we create a BoxGeometry
let geom = new THREE.BufferGeometry().fromGeometry(new THREE.BoxGeometry(100,100,100));
let phongMaterial = new THREE.MeshPhongMaterial({
color: new THREE.Color(1, 0, 0)
});
let mesh = new THREE.Mesh(geom, phongMaterial);
if (!viewer.overlays.hasScene("CustomScene")) {
viewer.overlays.addScene("CustomScene");
}
viewer.overlays.addMesh(mesh, "CustomScene");
viewer.impl.sceneUpdated(true);
//here we generate the JSON from the mesh and download it
let jsonObject = JSON.stringify(mesh.toJSON())
download(jsonObject, 'Box.json', 'text/plain');
download function can be found here.
The next step is about generating the box from the saved JSON.
For that, we'll use ObjectLoader.parse method.
And again, we can summarize in the code below:
//here we read the JSON object from our generated file
var request = new XMLHttpRequest();
request.open("GET", "js/Box.json", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
//here we generate the mesh
let mesh = new THREE.ObjectLoader().parse(my_JSON_object);
if (!viewer.overlays.hasScene("CustomScene")) {
viewer.overlays.addScene("CustomScene");
}
viewer.overlays.addMesh(mesh, "CustomScene");
viewer.impl.sceneUpdated(true);
Refer here for the function to read objects from JSON file.

Can't import geojson value as string in google maps with firebase web

So, I set up my firebase to communicate with my web app which uses google maps api and my goal is this: When a user draws a shape on the map(polygon, linestring), I want to send the geoJson value of it to the firebase(currently sending it as a String), and then retrieve it back so it appears on the map for everyone(since it's getting synced from the firebase database). My problem is that when I try to retrieve the geoJson data back and add it on google maps, at the line map.data.addGeoJson(geoJsonString);(geoJsonString = geoJson value that is stored in firebase) I get an error saying:
Uncaught Jb {message: "not a Feature or FeatureCollection", name: "InvalidValueError", stack: "Error↵ at new Jb (https://maps.googleapis.com/m…tatic.com/firebasejs/4.13.0/firebase.js:1:278304)"}
For some reason google maps api doesnt accept the geoJson value even though console.log(geoJsonString); returns a valid geoJson value (checked at http://geojsonlint.com/)
Now the strange part is that if I try to import the same geoJson value manually(storing the geoJson value in a var and then map.data.addGeoJson(geoJsonString);) it works just fine.
This function syncs firebase with the web app
function gotData(data){
paths = data.val();
if(paths == null){
console.log("firebase null");
alert('Database is empty! Try adding some paths.');
}
else{
var keys = Object.keys(paths);
for(var i = 0; i < keys.length; i++){
var k = keys[i];
var geoJsonString = paths[k].geoJsonString;
console.log(geoJsonString);
map.data.addGeoJson(geoJsonString);
}
}
}
This function updates and pushes data in firebase
function updateData(){
data = {
geoJsonString: geoJsonOutput.value
}
ref = database.ref('firebasePaths');
ref.push(data);
}
In this function(which is used to store geoJson values locally in a file), I call updateData function), after a new path is drawn on the map
// Refresh different components from other components.
function refreshGeoJsonFromData() {
map.data.toGeoJson(function(geoJson) {
geoJsonOutput.value = JSON.stringify(geoJson);
updateData();
refreshDownloadLinkFromGeoJson();
});
}
Example of my firebase that contains 2 random geoJson
I can't trace where the problem is. Any ideas?
Update: I managed to fix this issue by parsing the string with JSON.parse("retrieved string from firebase"), saving it to a variable and then adding it to the map with map.data.addgeoJson(parsed variable).
We still have not faced that issue, however, we are aware of it.
Our intended solution is to use GeoFire: An open-source library for the Firebase Realtime Database that adds support for geospatial querying.
You can find the library description in here:
https://firebase.google.com/docs/libraries/
For the Web supported library:
https://github.com/firebase/geofire-js

Creating CycleTile with remote images

I have seen a number of examples showing the CycleTile in action, but these have all used local images. Is it possible to set these images once the app is first run and point the CycleTile to the remote images? Or if I do need to save these to the phone first, how can I get the CycleTile to reference them?
CycleTileTemplate & CycleTileData only support local URIs and don't support remote web URIs. Meaning that you can only set the source of a cycle image from files installed from the XAP or from files in IsoStore.
In order to support remote images in CycleTileData, you'll need to download the images in a periodic background agent, save them to IsoStore and then update the CycleTileData with those images. Push notifications won't work here since the images need to be local and neither will ShellTileSchedule.
Make sure to save the images to IsoStore under the "/Shared/ShellContent" and set their URIs as "isostore:/Shared/Shellcontent/myImage.png" or they won't be accessible to the start screen tiles.
Let's see an example of that. First we start off by writing up a parallelized threaded algorithm that launches 9 download threads, waits for the results and then updates tiles:
private IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var threadFinishEvents = new List<WaitHandle>();
DownloadImages(threadFinishEvents);
new Thread(()=>
{
Mutex.WaitAll(threadFinishEvents.ToArray());
UpdateTiles();
isoStore.Dispose();
}).Start();
}
Next, we'll download the 9 images into IsoStore "/Shared/ShellContent". We'll take special note to add the new threading flags for each web download, and set the flag as done once the file is in IsoStore.
private void DownloadImages(List<WaitHandle> threadFinishEvents)
{
for (int i = 0; i < 9; i++)
{
var localI = i;
var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset);
threadFinishEvents.Add(threadFinish);
var request = WebRequest.CreateHttp("http://www.justinangel.net/storage/691x336.png");
request.BeginGetResponse(ir =>
{
var result = request.EndGetResponse(ir);
using (var isoStoreFile = isoStore.OpenFile("shared/shellcontent/myImage" + localI + ".png",
FileMode.Create,
FileAccess.ReadWrite))
using (var response = result.GetResponseStream())
{
var dataBuffer = new byte[1024];
while (response.Read(dataBuffer, 0, dataBuffer.Length) > 0)
{
isoStoreFile.Write(dataBuffer, 0, dataBuffer.Length);
}
}
threadFinish.Set();
}, null);
}
}
Finally, we'll update the live tile to use the new images in IsoStore.
private void UpdateTiles()
{
ShellTile.ActiveTiles
.First()
.Update(new CycleTileData()
{
Title = "Cyclical",
CycleImages = new Uri[]
{
new Uri("isostore:/Shared/ShellContent/myImage0.png", UriKind.Absolute),
new Uri("isostore:/Shared/ShellContent/myImage1.png", UriKind.Absolute),
new Uri("isostore:/Shared/ShellContent/myImage2.png", UriKind.Absolute),
new Uri("isostore:/Shared/ShellContent/myImage3.png", UriKind.Absolute),
new Uri("isostore:/Shared/ShellContent/myImage4.png", UriKind.Absolute),
new Uri("isostore:/Shared/ShellContent/myImage5.png", UriKind.Absolute),
new Uri("isostore:/Shared/ShellContent/myImage6.png", UriKind.Absolute),
new Uri("isostore:/Shared/ShellContent/myImage7.png", UriKind.Absolute),
new Uri("isostore:/Shared/ShellContent/myImage8.png", UriKind.Absolute),
}
});
}
There's a couple of interesting things to consider:
Periodic background agents only have 25 seconds to complete their operation, so it might make sense to add timer thresehold when activating Mutex.WaitAll and have it fail gracefully.
Downloading 9 images in 25 seconds might not work at all under some network conditions so it might be best to optimize for that. You can either use less images, or update only a few images every 30 minutes.
Updating the CycleTileData to the same file URIs won't trigger an update of the tile (AFAIK). So you'll need better filenames then myImage0, but rather have unique file names for the images.
For CycleTile, the images have to be local. You could set up a periodic task to refresh the images though, then store those images in the shared/shellcontent special folder in local/isolated storage (e.g., ms-appdata:///local/shared/shellcontent/image01.png)
Session 7 of the Windows Phone 8 Jumpstart is a good reference for this - specifically about 25:30 in.

Get chrome tabs and windows from localStorage

I am trying to access tabs and windows data inside a Google Chrome extension. I've apparently managed to get this info and loading it through localStorage but I don't know how to use the information, since I can't seem to parse the data back to arrays of objects through JSON parse.
Here's the code:
<html>
<head>
<script>
tabs = {};
tabIds = [];
focusedWindowId = undefined;
currentWindowId = undefined;
localStorage.windowsTabsArray = undefined;
function loadItUp() {
return arrays = chrome.windows.getAll({ populate: true }, function(windowList) {
tabs = {};
tabIds = [];
var groupsarr = new Array();
var tabsarr = new Array();
var groupstabs = new Array();
for (var i = 0; i < windowList.length; i++) {
windowList[i].current = (windowList[i].id == currentWindowId);
windowList[i].focused = (windowList[i].id == focusedWindowId);
groupsarr[windowList[i].id] = "Untitled"+i;
for (var j = 0; j < windowList[i].tabs.length; j++) {
tabsarr[windowList[i].tabs[j].id] = windowList[i].tabs[j];
groupstabs[windowList[i].id] = windowList[i].tabs;
}
}
localStorage.groupsArray = JSON.stringify(groupsarr);
localStorage.tabsArray = JSON.stringify(tabsarr);
localStorage.groupsTabsArray = JSON.stringify(groupstabs);
});
}
function addGroup() {
var name = prompt("NEW_GROUP_NAME");
var groupsarr = JSON.parse(localStorage.groupsArray);
groupsarr.push(name);
localStorage.groupsArray = JSON.stringify(groupsarr);
}
</script>
</head>
<body onload="loadItUp()">
WINDOW_QTY:
<script type="text/javascript">
var wArray = JSON.parse(localStorage.groupsArray);
document.write(wArray);
</script>
<br/>
TABS_QTY:
<script type="text/javascript">
var tArray = JSON.parse(localStorage.tabsArray)
document.write(tArray);
</script>
<br/>
WINDOWS_TABS_QTY:
<script type="text/javascript">
document.write(JSON.parse(localStorage.groupsTabsArray));
</script>
<br/>
</body>
</html>
1)
The page shows bunch of [object Object].
That's expected, objects are implicitly converted to string when you call document.write(tArray);; custom object without a custom toString implementation are converted to "[object Object]". It doesn't mean they're not "parsed".
To inspect the object you can use the Developer Tools. You can open the inspector for a background page from the Extensions page and if you get your page to open in a tab (e.g. if you use chrome_url_overrides) you can inspect it as you would inspect a regular web page.
If you replace the document.write calls with console.log(), you'll be able to inspect the objects in the Developer Tools' console.
2)
Do you realize that the document.write calls in tags run before loadItUp()?
Had no idea that the page code was being executed before loadItUp().
Scripts are executed at the moment they are inserted in the DOM by the parser (unless they are deferred or async) - see MDC documentation on <script>, - while various load events, in particular <body onload=...>, are executed after the page is finished parsing.
So right now your document.write calls print the values that were saved to localStorage the previous time the page was loaded, it's probably not what you wanted.
Instead of using document.write() from inline scripts, you should use element.innerHTML or element.textContent to update the page's text. There are many ways to get a reference to the element you need, document.getElementById() is one.
3)
Last, note that not every object can be saved to and then loaded from localStorage. For example, methods will not survive the round-trip, and the identity of the object is not preserved, meaning that the object you got from a Chrome API will not be the same object after you store it in localStorage and load it back.
You have not explained why you think you need localStorage - it's used when you want to preserve some data after the page is closed and reloaded - so maybe you don't really need it?