Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active October 26, 2020 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/3830491066e58e54903b3025d04e5b0c to your computer and use it in GitHub Desktop.
Save aspose-com-gists/3830491066e58e54903b3025d04e5b0c to your computer and use it in GitHub Desktop.
This Gist contains code snippets from examples of Aspose.OCR for Java.
This Gist contains code snippets from examples of Aspose.OCR for Java.
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
OmrTemplate template = new OmrTemplate();
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
java.awt.geom.Point2D.Float choiceBoxPosition = new java.awt.geom.Point2D.Float(20, 5); // 20 mm to the right, 5 mm from
// the top
java.awt.Dimension choiceBoxSize = new java.awt.Dimension(12, 24);
ChoiceBoxElement choiceBox = new ChoiceBoxElement("anElement", choiceBoxPosition, choiceBoxSize);
choiceBox.setHorizontal(false);
choiceBox.getCells().add(new OmrCell("A")); // Three marks: (A) (B) (C)
choiceBox.getCells().add(new OmrCell("B"));
choiceBox.getCells().add(new OmrCell("C"));
page.getElements().add(choiceBox);
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
template.save(dataDir + "new-template.amr");
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
OmrPage page = template.getPages().getItem(0);
page.setWidth(215.9);
page.setHeight(279.4);
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExtractingPreprocessedImages.class);
// Set the Image property by loading the image from file path location or an instance of InputStream
ocrEngine.setImage(ImageStream.fromFile(dataDir + "aspose-logo.png"));
// Process the image
if (ocrEngine.process()) {
try {
// Save binarized image on disc
ImageIO.write(ocrEngine.getPreprocessedImages().getBinarizedImage(), "PNG",
new File(dataDir + "BinarizedImage.png"));
// Save filtered image on disc
ImageIO.write(ocrEngine.getPreprocessedImages().getFilteredImage(), "PNG",
new File(dataDir + "FilteredImage.png"));
// Save image after removing non-textual fragments
ImageIO.write(ocrEngine.getPreprocessedImages().getNonTextRemovedImage(), "PNG",
new File(dataDir + "NonTextRemovedImage.png"));
// Save image after skew correction
ImageIO.write(ocrEngine.getPreprocessedImages().getRotatedImage(), "PNG",
new File(dataDir + "RotatedImage.png"));
// Save image after textual block detection
ImageIO.write(ocrEngine.getPreprocessedImages().getTextBlocksImage(), "PNG",
new File(dataDir + "TextBlocksImage.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(PerformingOCROnPDFDocuments.class);
// Create an instance of Document to load the PDF
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document(dataDir + "Disclosure(SDK).pdf");
// Create an instance of OcrEngine for recognition
com.aspose.ocr.OcrEngine ocrEngine = new com.aspose.ocr.OcrEngine();
// Iterate over the pages of PDF
for (int pageCount = 1; pageCount <= pdfDocument.getPages().size(); pageCount++) {
// Create Resolution object with DPI value
com.aspose.pdf.devices.Resolution resolution = new com.aspose.pdf.devices.Resolution(300);
// Create JPEG device with specified attributes (Width, Height, Resolution, Quality), where Quality [0-100], 100 is
// Maximum
com.aspose.pdf.devices.JpegDevice jpegDevice = new com.aspose.pdf.devices.JpegDevice(resolution, 100);
// Create stream object to save the output image
java.io.OutputStream imageStream = new java.io.FileOutputStream("Converted_Image" + pageCount + ".jpg");
// Convert a particular page and save the image to stream
jpegDevice.process(pdfDocument.getPages().get_Item(pageCount), imageStream);
// Set Image property of OcrEngine to the stream obtained from previous step
ocrEngine.setImage(ImageStream.fromFile("Converted_Image" + pageCount + ".jpg"));
// Perform OCR operation on one page at a time
if (ocrEngine.process()) {
System.out.println(ocrEngine.getText());
}
// Close the stream
imageStream.close();
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(UsageOfNotifierFactoryClass.class);
// Create an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// Set image file
ocrEngine.setImage(ImageStream.fromFile(dataDir + "aspose-logo.png"));
final int[] totalWords = { 0 };
// Get an instance of INotifier
INotifier processorWord = NotifierFactory.wordNotifier();
// Write a delegate to handle the Elapsed event
processorWord.Elapsed.add(new NotifierHandler() {
public void invoke(Object sender, IRecognizedText recognizedText) {
totalWords[0]++;
}
});
// Add the word processor to the OcrEngine
ocrEngine.addNotifier(processorWord);
// Perform OCR and get extracted text
ocrEngine.process();
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
//Set license
String file = "Aspose.Total.lic"; //change the path to point to a valid license
License.setLicense(file);
//Check license
boolean resLicense = License.isValid();
System.out.println("License is set: " + resLicense);
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// Clear notifier list
ocrEngine.clearNotifies();
// Clear recognition blocks
ocrEngine.getConfig().clearRecognitionBlocks();
// Add 3 rectangle blocks to user defined recognition blocks
// Reading text from multiple recognition blocks work with a valid license
ocrEngine.getConfig().addRecognitionBlock(RecognitionBlock.createTextBlock(27, 35, 857, 75));
ocrEngine.getConfig().addRecognitionBlock(RecognitionBlock.createTextBlock(899, 104, 552, 63));
ocrEngine.getConfig().addRecognitionBlock(RecognitionBlock.createTextBlock(702, 163, 623, 68));
// Ignore everything else on the image other than the user defined
// recognition blocks
ocrEngine.getConfig().setDetectTextRegions(false);
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(AddingUserDefinedRecognitionBlocks.class);
// The image path
String imagePath = dataDir + "Sampleocr.bmp";
// Set Image property by loading an image from file path
ocrEngine.setImage(ImageStream.fromFile(imagePath));
// Run recognition process
if(ocrEngine.process()) {
// Retrieve user defined blocks that determines the page layout
List<IRecognitionBlock> blocks = ocrEngine.getConfig().getRecognitionBlocks();
// Loop over the list of blocks
for (IRecognitionBlock block : blocks) {
// Check if block has recognition data
if (block.getRecognitionData() == null) {
System.out.println("Null");
continue;
}
// Display dimension & size of rectangle that defines the recognition block
System.out.println("Block: " + block.getRectangle());
// Display the recognition results
IRecognizedTextPartInfo textPartInfo = (IRecognizedTextPartInfo) block.getRecognitionData();
System.out.println("Text: " + textPartInfo.getText());
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize OcrEngine
OcrEngine ocr = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ApplyingCorrectionFilters.class);
// The image path
String imagePath = dataDir + "Sampleocr.bmp";
// Set the image for instance of OcrEngine
ocr.setImage(ImageStream.fromFile(imagePath));
//// Set filters
// Create CorrectionFilters collection
CorrectionFilters filters = new CorrectionFilters();
Filter filter = null;
// Initialize Median filter
filter = new MedianFilter(5);
filters.add(filter);
// Create Gaussian Blur filter
filter = new GaussBlurFilter();
filters.add(filter);
// Assign filters collection to OcrEngine
ocr.getConfig().setCorrectionFilters(filters);
// Perform OCR operation
ocr.process();
System.out.println("Whole result is " + ocr.getText());
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Create an instance of OcrEngine class
OcrEngine ocr = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(DisableReadingOrderDetection.class);
// The image path
String imagePath = dataDir + "Sampleocr.bmp";
// Set Image property by loading an image from file path
ocr.setImage(ImageStream.fromFile(imagePath));
// Set the DetectReadingOrder to false to improve performance
// Default value of DetectReadingOrder is true
ocr.getConfig().setDetectReadingOrder(false);
// Perform OCR operation
if (ocr.process()) {
// Display results
System.out.println(ocr.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ExtractPreprocessedImages.class);
// The image path
String imagePath = dataDir + "Sample.jpg";
// Set Image property by loading an image from file path
ocrEngine.setImage(ImageStream.fromFile(imagePath));
// Set the SavePreprocessedImages property to true to save the images
ocrEngine.getConfig().setSavePreprocessedImages(true);
if (ocrEngine.process()) {
//Save binarized image on disc
ImageIO.write(ocrEngine.getPreprocessedImages().getBinarizedImage(), "png", new File(dataDir + "Output\\BinarizedImage.png"));
//Save filtered image on disc
ImageIO.write(ocrEngine.getPreprocessedImages().getFilteredImage(), "png", new File(dataDir + "Output\\FilteredImage.png"));
//Save image after removing non-textual fragments
ImageIO.write(ocrEngine.getPreprocessedImages().getNonTextRemovedImage(), "png", new File(dataDir + "Output\\NonTextRemovedImage.png"));
//Save image after skew correction
ImageIO.write(ocrEngine.getPreprocessedImages().getRotatedImage(), "png", new File(dataDir + "Output\\RotatedImage.png"));
//Save image after textual block detection
ImageIO.write(ocrEngine.getPreprocessedImages().getTextBlocksImage(), "png", new File(dataDir + "Output\\TextBlocksImage.png"));
System.out.println(ocrEngine.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// Create text recognition block by supplying X,Y coordinates and Width,Height values
com.aspose.ocr.IRecognitionBlock block1 = com.aspose.ocr.RecognitionBlock.createTextBlock(10, 9, 258, 46);
// Set the Whitelist property to recognize numbers only
block1.setWhitelist(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' });
// Create text recognition block by supplying X,Y coordinates and Width,Height values
com.aspose.ocr.IRecognitionBlock block2 = com.aspose.ocr.RecognitionBlock.createTextBlock(23, 62, 220, 50);
// Set the Whitelist property to recognize L,M,N,O,P letters only
block2.setWhitelist(new char[] { 'L', 'M', 'N', 'O', 'P' });
// Set different configurations and add the recognition block(s)
ocrEngine.getConfig().clearRecognitionBlocks();
ocrEngine.getConfig().addRecognitionBlock(block1);
ocrEngine.getConfig().addRecognitionBlock(block2);
ocrEngine.getConfig().setDetectTextRegions(false);
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(RecognizeMultipleWhiteLists.class);
// The image path
String imagePath = dataDir + "SampleNumbersAndLetters.bmp";
// Set Image property by loading an image from file path
ocrEngine.setImage(ImageStream.fromFile(imagePath));
if (ocrEngine.process()) {
System.out.println(ocrEngine.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Create an instance of OcrEngine class
OcrEngine ocr = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingOcrEnginetoAutomaticallyDetectTextBlocks.class);
/// Set the paths
String imagePath = dataDir + "Sample1.jpg";
// Set Image property by loading an image from file path
ocr.setImage(ImageStream.fromFile(imagePath));
// Set the DetectTextRegions to true
ocr.getConfig().setDetectTextRegions(true);
// Perform OCR operation
if (ocr.process()) {
// Display results
System.out.println(ocr.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Create an instance of OcrEngine class
OcrEngine ocr = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingOcrEnginetoAutomaticallyDetecttheReadingOrder.class);
/// Set the paths
String imagePath = dataDir + "Sample1.jpg";
// Set Image property by loading an image from file path
ocr.setImage(ImageStream.fromFile(imagePath));
// Set the DetectReadingOrder to true
ocr.getConfig().setDetectReadingOrder(true);
// Perform OCR operation
if (ocr.process()) {
// Display results
System.out.println(ocr.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// Retrieve the OcrConfig of the OcrEngine object
OCRConfig ocrConfig = ocrEngine.getConfig();
// Set the Whitelist property to recognize numbers only
ocrConfig.setWhitelist(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' });
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SettingOcrEnginetoRecognizeOnlyWhiteListedCharacters.class);
// The image path
String imagePath = dataDir + "SampleNumbers.jpg";
// Set Image property by loading an image from file path
ocrEngine.setImage(ImageStream.fromFile(imagePath));
// Call the Process method to retrieve the results
ocrEngine.process();
// Filtration can be done using different approaches such as by using the regular expressions as demonstrated below
if (ocrEngine.process()) {
IRecognizedText text = ocrEngine.getText();
System.out.println(text);
String expression = "(\\d+)";
// Create a Pattern object
Pattern pattern = Pattern.compile(expression);
// Now create matcher object
Matcher matcher = pattern.matcher(text.toString());
if (matcher.find()) {
System.out.println("Found value: " + matcher.group(0));
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Create an instance of OcrEngine class
OcrEngine ocr = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SettingtheOcrEnginetoAutomaticallyCorrecttheSpellings.class);
// The image path
String imagePath = dataDir + "SampleSpellingCorrection.jpg";
// Set Image property by loading an image from file path
ocr.setImage(ImageStream.fromFile(imagePath));
// Set the DoSpellingCorrection to true
ocr.getConfig().setDoSpellingCorrection(true);
// Perform OCR operation
if (ocr.process()) {
// Display results
System.out.println(ocr.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
String FileName = "";
// Initialize an instance of OcrEngine
OcrEngine ocr = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingtheOcrEnginetoExcludesavingpreprocessedimages.class);
/// Set the paths
String imagePath = dataDir + "Sample1.jpg";
// Set Image property by loading an image from file path
ocr.setImage(ImageStream.fromFile(imagePath));
// Set the SavePreprocessedImages property to false
ocr.getConfig().setSavePreprocessedImages(false);
if (ocr.process()) {
// Do processing
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Create an instance of OcrEngine class
OcrEngine ocr = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SettingtheOcrEnginetoIgnoreNonTextualBlocks.class);
// The image path
String imagePath = dataDir + "Sampleocr.bmp";
// Set Image property by loading an image from file path
ocr.setImage(ImageStream.fromFile(imagePath));
// Set the RemoveNonText to true
ocr.getConfig().setRemoveNonText(true);
// Perform OCR operation
if (ocr.process()) {
// Display results
System.out.println(ocr.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CalculateSkewAngle.class);
// The image path
String imagePath = dataDir + "p3.png";
//Create api instance
AsposeOCR api = new AsposeOCR();
// Get test skew
try {
double angle = api.CalcSkewImage(imagePath);
System.out.println("Skew text is:" + angle + " degrees.");
} catch (IOException e1) {
e1.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// Clear notifier list
ocrEngine.clearNotifies();
// Clear recognition blocks
ocrEngine.getConfig().clearRecognitionBlocks();
// Add 2 rectangle blocks to user defined recognition blocks
// Reading text from multiple recognition blocks work with a valid license
ocrEngine.getConfig().addRecognitionBlock(RecognitionBlock.createTextBlock(27, 35, 857, 75));
ocrEngine.getConfig().addRecognitionBlock(RecognitionBlock.createTextBlock(899, 104, 552, 63));
// Ignore everything else on the image other than the user defined
// recognition blocks
ocrEngine.getConfig().setDetectTextRegions(false);
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ExtractingTextfromPartofanImage.class);
// The image path
String imagePath = dataDir + "Sampleocr.bmp";
// Set the Image property
ocrEngine.setImage(ImageStream.fromFile(imagePath));
// Run recognition process
if (ocrEngine.process()) {
for (IRecognizedPartInfo info : ocrEngine.getText().getPartsInfo()) {
IRecognizedTextPartInfo textInfo = (IRecognizedTextPartInfo) info;
System.out.println("Block: " + info.getBox() + " Text: " + textInfo.getText());
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(GetRectanglesWithTextAreas.class);
// The image path
String imagePath = dataDir + "p3.png";
//Create api instance
AsposeOCR api = new AsposeOCR();
// Recognize page by full path to file
try {
String result = api.RecognizePage(imagePath);
System.out.println("Result: " + result);
} catch (IOException e) {
e.printStackTrace();
}
//Get rectangles with text areas in the image.
ArrayList<Rectangle> rectResult = api.getTextAreas();
for(Rectangle r : rectResult) {
System.out.println("Text area:" + r);
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(GetTextPartHierarchyofRecognizedText.class);
// Set the image path
String imageFileName = dataDir + "Sampleocr.bmp";
// Set the Image property by loading the image from file path location
// or an instance of MemoryStream
ocrEngine.setImage(ImageStream.fromFile(imageFileName));
// Process the image
if (ocrEngine.process()) {
// Retrieve the first block of the recognized text part
IRecognizedTextPartInfo firstBlock = (IRecognizedTextPartInfo) ocrEngine.getText().getPartsInfo()[0];
// Get the children of the first block that will be the lines in the block
IRecognizedPartInfo[] linesOfFirstBlock = firstBlock.getChildren();
// Retrieve the fist line from the collection of lines
IRecognizedTextPartInfo firstLine = (IRecognizedTextPartInfo) linesOfFirstBlock[0];
// Display the level of line
System.out.println(getLevelText(firstLine.getLevel()));
// Retrieve the fist word from the collection of words
IRecognizedTextPartInfo firstWord = (IRecognizedTextPartInfo) firstLine.getChildren()[0];
// Display the level of word
System.out.println(getLevelText(firstWord.getLevel()));
// Retrieve the fist character from the collection of characters
IRecognizedTextPartInfo firstCharacter = (IRecognizedTextPartInfo) firstWord.getChildren()[0];
// Display the level of character
System.out.println(getLevelText(firstCharacter.getLevel()));
}
// Method to identify level
public static String getLevelText(int level) {
if(level == TextPartLevel.Character) {
return "Character";
} else if (level == TextPartLevel.Line) {
return "Line";
} else if (level == TextPartLevel.Textblock) {
return "Textblock";
} else {
return "Word";
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Create an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(GettingNotificationforEachRecognizedWord.class);
// The image path
String imageFileName = dataDir + "Sampleocr.bmp";
// Set the Image property
ocrEngine.setImage(ImageStream.fromFile(imageFileName));
final int[] totalWords = { 0 };
// Get an instance of INotifier
INotifier processorWord = NotifierFactory.wordNotifier();
// Write a delegate to handle the Elapsed event
processorWord.Elapsed.add(new NotifierHandler() {
public void invoke(Object sender, IRecognizedText recognizedText) {
totalWords[0]++;
System.out.println(recognizedText);
}
});
// Add the word processor to the OcrEngine
ocrEngine.addNotifier(processorWord);
// Perform OCR and get extracted text
ocrEngine.process();
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// Set the Image property by loading the image from remote location
ocrEngine.setImage(ImageStream.fromUrl("https://blog.aspose.com/wp-content/uploads/sites/2/2019/03/SampleTextOnline.jpg"));
// Process the image
if (ocrEngine.process()) {
// Display the recognized text
System.out.println(ocrEngine.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OCROperationWithLanguageSelection.class);
// The image path
String file = dataDir + "p3.png";
//Create api instance
AsposeOCR api = new AsposeOCR();
// set recognition options
RecognitionSettings settings = new RecognitionSettings();
settings.setAutoSkew(false);
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
rectangles.add(new Rectangle(90,186,775,95));
settings.setRecognitionAreas(rectangles);
settings.setSkew(0.5);
settings.setLanguage(RecognitionSettings.Language.en);
// get result object
RecognitionResult result = null;
try {
result = api.RecognizePage(file, settings);
} catch (IOException e) {
e.printStackTrace();
}
// print result
System.out.println("Result: \n" + result.recognitionText+"\n\n");
for(String n: result.recognitionAreasText) {
System.out.println ( n );
}
for(Rectangle n: result.recognitionAreasRectangles) {
System.out.println(n.height+":"+n.width+":"+n.x+":"+n.y);
}
System.out.println("\nJSON:" + result.GetJson());
System.out.println("angle:" + result.skew);
for(String n: result.warnings) {
System.out.println ( n );
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Create an initialize an instance of OcrEngine
OcrEngine engine = new OcrEngine();
String dataDir = Utils.getSharedDataDir(PerformingOCRonMultipageTIFF.class);
// The image path
String imagePath = dataDir + "SampleTiff.tiff";
// Set the OcrEngine.Image property by loading a multipage TIFF from
// disk, memory or URL
engine.setImage(ImageStream.fromFile(imagePath));
// Set OcrEngine.ProcessAllPages to true in order to process all pages
// of TIFF in single run
engine.setProcessAllPages(true);
// Call OcrEngine.Process method to perform OCR operation
if (engine.process()) {
// Retrieve the list of Pages
Page[] pages = engine.getPages();
// Iterate over the list of Pages
for (Page page : pages) {
// Display the recognized text from each Page
System.out.println(page.getPageText());
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(PerformOCROnBufferedImage.class);
// The image path
String imagePath = dataDir + "p3.png";
//Create api instance
AsposeOCR api = new AsposeOCR();
// Recognize page from BufferedImage
try {
BufferedImage loaded = ImageIO.read(new File(imagePath));
String result = api.RecognizePage(loaded);
System.out.println("Result BufferedImage: " + result);
} catch (IOException e) {
e.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(PerformOCROnImage.class);
// The image path
String imagePath = dataDir + "Sampleocr.bmp";
// Create an instance of OcrEngine
OcrEngine ocr = new OcrEngine();
// Set the Image property
ocr.setImage(ImageStream.fromFile(imagePath));
// Perform OCR and get extracted text
try {
if (ocr.process()) {
System.out.println(ocr.getText());
}
} catch (Exception e) {
e.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
//Create api instance
AsposeOCR api = new AsposeOCR();
String uri = "https://www.castlegateit.co.uk/wp-content/uploads/2016/09/justified_text.png";
// set recognition options
RecognitionSettings settings = new RecognitionSettings();
settings.setAutoSkew(false);
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
rectangles.add(new Rectangle(90,186,775,95));
settings.setRecognitionAreas(rectangles);
// get result object
RecognitionResult result = null;
try {
result = api.RecognizePageFromUri(uri, settings);
} catch (IOException e) {
e.printStackTrace();
}
// print result
System.out.println("Result: \n" + result.recognitionText+"\n\n");
System.out.println("RecognitionAreasText: \n");
for(String text: result.recognitionAreasText) {
System.out.println(text);
}
System.out.println("JSON: \n" + result.GetJson());
System.out.println("Warnings: \n");
for(String warning: result.warnings) {
System.out.println(warning);
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(PerformOCROnPage.class);
// The image path
String imagePath = dataDir + "p3.png";
//Create api instance
AsposeOCR api = new AsposeOCR();
// Recognize page by full path to file
try {
String result = api.RecognizePage(imagePath);
System.out.println("Result: " + result);
} catch (IOException e) {
e.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(PerformOCROnPDF.class);
//Create an instance of Document to load the PDF file
Document pdfDocument = new Document(dataDir + "Sample.pdf");
// Create an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
//Iterate over the pages of PDF
for(int pageCount = 1; pageCount <= pdfDocument.getPages().size(); pageCount++) {
//Create Resolution object with DPI value
Resolution resolution = new com.aspose.pdf.devices.Resolution(300);
//Create JPEG device with specified attributes (Width, Height, Resolution, Quality)
//where Quality [0-100], 100 is Maximum
JpegDevice jpegDevice = new com.aspose.pdf.devices.JpegDevice(resolution, 100);
// Create stream object to save the output image
java.io.OutputStream imageStream = new java.io.FileOutputStream(dataDir + "Output\\Converted_PDF_Image" + pageCount + ".jpg");
//Convert a particular page and save the image to stream
jpegDevice.process(pdfDocument.getPages().get_Item(pageCount), imageStream);
//Set Image property of OcrEngine to the image obtained from previous step
ocrEngine.setImage(ImageStream.fromFile(dataDir + "Output\\Converted_PDF_Image" + pageCount + ".jpg"));
//Perform OCR operation
if (ocrEngine.process())
{
System.out.println(ocrEngine.getText());
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(PrepareRectangles.class);
// The image path
String imagePath = dataDir + "p.png";
//Create api instance
AsposeOCR api = new AsposeOCR();
//Prepare rectangles with texts.
ArrayList<Rectangle> rectArray = new ArrayList<Rectangle>();
rectArray.add(new Rectangle(138, 352, 2033, 537));
rectArray.add(new Rectangle(147, 890, 2033, 1157));
rectArray.add(new Rectangle(923, 2045, 465, 102));
rectArray.add(new Rectangle(104, 2147, 2076, 819));
try {
String result = api.RecognizePage(imagePath, rectArray);
System.out.println("Result with rect: " + result);
} catch (IOException e) {
e.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
String dataDir = Utils.getSharedDataDir(ReadingPartInformation.class);
// The image path
String imagePath = dataDir + "Sampleocr.bmp";
// Set Image property by loading an image from file path
ocrEngine.setImage(ImageStream.fromFile(imagePath));
// Run recognition process
if (ocrEngine.process()) {
System.out.println(ocrEngine.getText());
// Retrieve an array of recognized text by parts
IRecognizedPartInfo[] text = ocrEngine.getText().getPartsInfo();
// Iterate over the text parts
for (int i = 0; i < text.length; i++) {
IRecognizedTextPartInfo symbol = (IRecognizedTextPartInfo) text[i];
// Display part information
System.out.println("isItalic : " + symbol.getItalic());
System.out.println("Text Color : " + symbol.getTextColor());
System.out.println("Text : " + symbol.getText());
System.out.println("isTrimmed : " + symbol.isTrimmed());
float[] quality = symbol.getCharactersQuality();
System.out.println("Quality of first Character : " + quality[0]);
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(RecognizeLine.class);
// The image path
String imagePath = dataDir + "0001460985.Jpeg";
//Create api instance
AsposeOCR api = new AsposeOCR();
try {
String result = api.RecognizeLine(imagePath);
System.out.println("File: " + imagePath);
System.out.println("Result line: " + result);
} catch (IOException e) {
e.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SpecifyAllowedCharacters.class);
// The image path
String imagePath = dataDir + "0001460985.Jpeg";
//Create api instance
AsposeOCR api = new AsposeOCR("123456789");
try {
String result = api.RecognizeLine(imagePath);
System.out.println("File: " + imagePath);
System.out.println("Result line: " + result);
} catch (IOException e) {
e.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Initialize an instance of OcrEngine
OcrEngine ocrEngine = new OcrEngine();
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ReadingPartInformation.class);
// The image path
String imageFileName = dataDir + "SpanishOCR.bmp";
// Set the Image property by loading the image from file path location
ocrEngine.setImage(ImageStream.fromFile(imageFileName));
// Clear the default language (English)
ocrEngine.getLanguageContainer().clear();
// Load the resources of the language from file path location or an instance of InputStream
ocrEngine.getLanguageContainer().addLanguage(LanguageFactory.load(dataDir + "Aspose.OCR.Spanish.Resources.zip"));
// Process the image
if (ocrEngine.process()) {
// Display the recognized text
System.out.println(ocrEngine.getText());
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DetectingtheImageResolution.class);
// Load the image to be analyzed
OmrImage image = OmrImage.load(dataDir + "answers.jpg");
// Set the auto image resolution detection property
image.setAutoDetectResolution(true);
// Load template file
OmrTemplate template = OmrTemplate.load(dataDir + "questions.amr");
// Instantiate the recognition engine for the template
OmrEngine engine = new OmrEngine(template);
// Extract data. This template has only one page.
OmrProcessingResult result = engine.extractData(new OmrImage[] { image });
// Get page data of extracted data
Hashtable[] pages = result.getPageData();
int index = 0;
// Iterate over the pages and display the data
for (Hashtable page : pages) {
System.out.println("------Page: " + index++);
Set<String> keys = page.keySet();
for (Object key : keys) {
String value = (String) page.get(key);
System.out.println("key: " + key);
System.out.println("value: '" + value + "'");
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
String dataDir = Utils.getDataDir(ExtractingBarcodeData.class);
String templateFile = dataDir + "questions.amr";
String imageFile = dataDir + "answers.jpg";
// Set the license for Aspose.BarCode for Java in case BarCode elements
// are used in the project
License licenseBarCode = new License();
licenseBarCode.setLicense(dataDir + "Aspose.Total.Java.lic");
// Set the license for OMR package
com.aspose.ocr.License licenseOmr = new com.aspose.ocr.License();
licenseOmr.setLicense(dataDir + "Aspose.Total.Java.lic");
// Load the template for mapping of elements
OmrTemplate template = OmrTemplate.load(templateFile);
// Add the BarCode element while specifying the location and size of
// barcode
java.awt.Dimension objDimension = new java.awt.Dimension(205, 205);
BarcodeElement barcodeElement = new BarcodeElement("aztec", new Point2D.Float(0, 0), objDimension);
// Add the BarCode element to the template page
template.getPages().getItem(0).getElements().add(barcodeElement);
// Load image to perform OMR
OmrImage image = OmrImage.load(imageFile);
// Initialize the OmrEngine with template file
OmrEngine engine = new OmrEngine(template);
// Start the recognition process by calling OmrEngine.extractData method
OmrProcessingResult result = engine.extractData(new OmrImage[] { image });
// Get all pages of extracted data
Hashtable[] pages = result.getPageData();
int index = 0;
// Iterate over the pages
for (Hashtable page : pages) {
System.out.println("------Page: " + index++);
Set<String> keys = page.keySet();
for (String key : keys) {
// Display the result for each key
String value = (String) page.get(key);
System.out.println("key: " + key);
System.out.println("value: '" + value + "'");
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExtractingOMRData.class);
// Initialize a string with template file location
String templateFile = dataDir + "questions.amr";
// Initialize a string with scanned image file location
String imageFile = dataDir + "answers.jpg";
// Create an instance of OmrTemplate class and load the template using
// the factory method Load
OmrTemplate template = OmrTemplate.load(templateFile);
// Create an instance of OmrImage class and load the template using the
// factory method Load
OmrImage image = OmrImage.load(imageFile);
// Create an instance of OmrEngine class
OmrEngine engine = new OmrEngine(template);
// Extract the OMR data
OmrProcessingResult result = engine.extractData(new OmrImage[] { image });
// Get page data of extracted data
Hashtable[] pages = result.getPageData();
int index = 0;
// Iterate over the pages and display the data
for (Hashtable page : pages) {
System.out.println("------Page: " + index++);
Set<String> keys = page.keySet();
for (Object key : keys) {
String value = (String) page.get(key);
System.out.println("key: " + key);
System.out.println("value: '" + value + "'");
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExtractTextDatafromScannedOMRForm.class);
/// Set the paths
String imageFile = dataDir + "answers.jpg";
String templateFile = dataDir + "questions.amr";
// Create an instance of OmrTemplate and load the template file
OmrTemplate template = OmrTemplate.load(templateFile);
// Set resource for TextOcrElement
TextOcrElement.setResource(dataDir + "Aspose.OCR.Spanish.Resources.zip");
// Create an instance of TextOcrElement and initialize it by specifying
// the location of text and its size in mm
java.awt.Dimension objDimension = new java.awt.Dimension(15, 5);
TextOcrElement textElement = new TextOcrElement("OCR Text", new Point2D.Float(23.6f, 15.5f), objDimension);
// Add TextOcrElement to the template's element collection
template.getPages().getItem(0).getElements().add(textElement);
// Create an instance of OmrImage and load the scanned image
OmrImage image = OmrImage.load(imageFile);
// Create an instance of OmrEngine and initialize it with an object of
// OmrTemplate
OmrEngine engine = new OmrEngine(template);
// Start the recognition process by calling OmrEngine.extractData method
OmrProcessingResult result = engine.extractData(new OmrImage[] { image });
// Get all pages of extracted data
Hashtable[] pages = result.getPageData();
int index = 0;
// Iterate over the pages
for (Hashtable page : pages) {
System.out.println("------Page: " + index++);
Set<String> keys = page.keySet();
// Display the result for each key
for (String key : keys) {
String value = (String) page.get(key);
System.out.println("key: " + key);
System.out.println("value: '" + value + "'");
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
String templateUrl = "https://Github.com/asposeocr/Aspose_OCR_NET/raw/master/Examples/Data/OCR/questions.amr";
String imageUrl = "https://Github.com/asposeocr/Aspose_OCR_NET/raw/master/Examples/Data/OCR/answers.jpg";
// Initialize an instance of OmrTemplate by loading the OMR template
// from URL
OmrTemplate template = OmrTemplate.loadFromUrl(templateUrl);
// image loading from url
OmrImage image = OmrImage.loadFromUrl(imageUrl);
// continue working with template and image as usual
OmrEngine engine = new OmrEngine(template);
OmrProcessingResult result = engine.extractData(new OmrImage[] { image });
// Get all pages of extracted data
Hashtable[] pages = result.getPageData();
int index = 0;
// Iterate over the pages
for (Hashtable page : pages) {
System.out.println("------Page: " + index++);
Set<String> keys = page.keySet();
// Display the result for each key
for (String key : keys) {
String value = (String) page.get(key);
System.out.println("key: " + key);
System.out.println("value: '" + value + "'");
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Create an instance of OCR Metered class
com.aspose.ocr.metered.Metered metered = new com.aspose.ocr.metered.Metered();
// Access the setMeteredKey property and pass public and private keys as parameters
metered.setMeteredKey("publicKeyValue", "privateKeyValue");
// Get consumed qantity value before accessing API
double amountBefore = com.aspose.ocr.metered.Metered.getConsumptionQuantity();
System.out.println(amountBefore);
// DO PROCESSING
// set up OMR engine
// com.aspose.omr.OmrEngine omr = new com.aspose.omr.OmrEngine(new com.aspose.omr.OmrTemplate());
// String path = "sampleimage.png";
// com.aspose.omr.OmrImage omrImage = com.aspose.omr.OmrImage.load(path);
// Since upload data is running on another thread, so we need wait some time
Thread.sleep(10000);
// get metered data amount
double amountAfter = com.aspose.ocr.metered.Metered.getConsumptionQuantity();
System.out.println(amountAfter);
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(OMRElements.class);
// Initialize a string with file path to the template
String templateFile = dataDir + "template.amr";
// Create an instance of OmrTemplate and load the template
OmrTemplate template = OmrTemplate.load(templateFile);
// Iterate over the pages in template
for (Object opage : template.getPages()) {
OmrPage page = (OmrPage) opage;
// Get elements of each page
OmrElementsCollection collection = page.getElements();
// Iterate over the element collection
for (Object obj : collection) {
// Display element name
System.out.println(obj.getClass().toString());
}
}
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingElementLevelThreshold.class);
// Load template
OmrTemplate template = OmrTemplate.load(dataDir + "template.amr");
// Load image
OmrImage image = OmrImage.load(dataDir + "sample1.jpg");
// Get the first page of the template
OmrPage page = template.getPages().getItem(0);
// Create an element by passing the name, location and size
java.awt.Dimension objDimension = new java.awt.Dimension(60, 30);
GridElement element = new GridElement("grid1", new Point2D.Float(10, 20), objDimension);
// Add element to the page
page.getElements().add(element);
// Create configuration for the element
element.setConfiguration(new OmrConfig());
// Set the TrimWhitePixels to false
element.getConfiguration().setTrimWhitePixels(false);
// Create an instance of OmrEngine and pass object of OmrTemplate as
// parameter
OmrEngine engine = new OmrEngine(template);
// Extract the data
OmrProcessingResult result = engine.extractData(new OmrImage[] { image });
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingGlobalThreshold.class);
// Load template
OmrTemplate template = OmrTemplate.load(dataDir + "template.amr");
// Load image
OmrImage image = OmrImage.load(dataDir + "sample1.jpg");
// Create an instance of OmrEngine and pass object of OmrTemplate as
// parameter
OmrEngine engine = new OmrEngine(template);
// Get the configurations of OmrEngine
OmrConfig config = engine.getConfiguration();
// Set fill threshold
config.setFillThreshold(0.12);
// Extract the data
OmrProcessingResult result = engine.extractData(new OmrImage[] { image });
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingPageLevelThreshold.class);
// Load template
OmrTemplate template = OmrTemplate.load(dataDir + "template.amr");
// Load image
OmrImage image = OmrImage.load(dataDir + "sample1.jpg");
// Get the first page of the template
OmrPage page = template.getPages().getItem(0);
// Create page configurations
page.setConfiguration(new OmrConfig());
// Set fill threshold
page.getConfiguration().setFillThreshold(0.21);
// Create an instance of OmrEngine and pass object of OmrTemplate as
// parameter
OmrEngine engine = new OmrEngine(template);
// Extract the data
OmrProcessingResult result = engine.extractData(new OmrImage[] { image });
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingtheResolutionforOMRImage.class);
// Load the image to be analyzed
OmrImage image = OmrImage.load(dataDir + "sample1.jpg");
// Define new value of image resolution in double format
image.setResolution(210.0); // overwrites the old DPI value
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Load image
String dataDir = Utils.getDataDir(SkewImageCorrectionAlgorithm.class);
com.aspose.omr.OmrImage image = com.aspose.omr.OmrImage.load(dataDir + "answers.jpg");
// Area of the image to be processed
java.awt.Rectangle area = new java.awt.Rectangle(0, 0, image.getWidth(), image.getHeight());
// Grayscale conversion
com.aspose.omr.imageprocessing.GrayscaleAlgorithm gs = new com.aspose.omr.imageprocessing.GrayscaleAlgorithm();
gs.process(image, area);
// Binarization
com.aspose.omr.imageprocessing.AverageThresholdAlgorithm threshold = new com.aspose.omr.imageprocessing.AverageThresholdAlgorithm();
threshold.process(image, area);
// Skew correction
com.aspose.omr.imageprocessing.SkewCorrectionAlgorithm skewCorrection = new com.aspose.omr.imageprocessing.SkewCorrectionAlgorithm();
skewCorrection.process(image, area);
// save image
java.io.File fileObj = new java.io.File(dataDir + "result.jpg");
ImageIO.write(image.asBitmap(), "jpg", fileObj);
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
// Load image
String dataDir = Utils.getDataDir(SkewImageCorrectionUsingAlgorithm.class);
OmrImage image = OmrImage.load(dataDir + "sample1.jpg");
// Use empty template or load any existing template
OmrEngine engine = new OmrEngine(new OmrTemplate());
// Get skew degree of the image
int degree = engine.getSkewDegree(image);
// Rotate image to correct skew
engine.rotateImage(image, degree);
// Save image
File fileObj = new java.io.File(dataDir + "result.jpg");
ImageIO.write(image.asBitmap(), "jpg", fileObj);
// For complete examples and data files, please go to https://github.com/aspose-ocr/Aspose.OCR-for-Java
String dataDir = Utils.getDataDir(SpecifydifferentBarcodetypes.class);
String templateFile = dataDir + "sample_1.amr";
String imageFile = dataDir + "sample1.jpg";
// Set the license for Aspose.BarCode for Java in case BarCode elements
// are used in the project
com.aspose.barcode.License licenseBarCode = new com.aspose.barcode.License();
licenseBarCode.setLicense(dataDir + "Aspose.Total.Java.lic");
// Set the license for OMR package
com.aspose.ocr.License licenseOmr = new com.aspose.ocr.License();
licenseOmr.setLicense(dataDir + "Aspose.Total.Java.lic");
// Load the template for mapping of elements
OmrTemplate template = OmrTemplate.load(templateFile);
// Add the BarCode element while specifying the location and size of
// barcode
java.awt.Dimension objDimension = new java.awt.Dimension(205, 205);
BarcodeElement barcodeElement = new BarcodeElement("aztec", new Point2D.Float(0, 0), objDimension);
// Set the symbologies type of the element.
barcodeElement.setBarCodeType(com.aspose.barcoderecognition.BarCodeReadType.Aztec);
// Do Processing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment