Views
No views yet
// 1. Create a handle for the low-level TessBaseAPI
ITessAPI.TessBaseAPI handle = TessAPI1.TessBaseAPICreate();
try {
// 2. Initialize API with "osd" language for Orientation and Script Detection
if (TessAPI1.TessBaseAPIInit3(handle, tessDataPath, "osd") != 0) {
System.err.println("Could not initialize Tesseract API.");
return;
}
// 3. Set Page Segmentation Mode (PSM) to AutoOsd (Value 0)
TessAPI1.TessBaseAPISetPageSegMode(handle, ITessAPI.TessPageSegMode.PSM_AUTO_OSD);
// 4. Read and set the target image file
var pixImage = TessAPI1.pixRead(imageFile.getAbsolutePath());
TessAPI1.TessBaseAPISetImage2(handle, pixImage);
// 5. Trigger layout analysis
ITessAPI.TessPageIterator iterator = TessAPI1.TessBaseAPIAnalyseLayout(handle);
if (iterator != null) {
// Prepare native memory buffers to hold output orientation data
IntBuffer orientation = IntBuffer.allocate(1);
IntBuffer writingDirection = IntBuffer.allocate(1);
IntBuffer textlineOrder = IntBuffer.allocate(1);
FloatBuffer deskewAngle = FloatBuffer.allocate(1);
// 6. Extract orientation info from the page layout iterator
TessAPI1.TessPageIteratorOrientation(iterator, orientation, writingDirection, textlineOrder, deskewAngle);
// Map integer values to human-readable angles
int orientationValue = orientation.get(0);
int degrees = convertToDegrees(orientationValue);
System.out.println("--- Orientation Analysis Results ---");
System.out.println("Tesseract Orientation ID: " + orientationValue);
System.out.println("Calculated Orientation: " + degrees + "°");
System.out.println("Deskew Angle Needed: " + deskewAngle.get(0) + "°");
// Clean up native iterator allocation
TessAPI1.TessPageIteratorDelete(iterator);
} else {
System.out.println("Could not parse image layout. Ensure the image has text characters.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 7. Clear native memory allocations safely
TessAPI1.TessBaseAPIDelete(handle);
}
}
/**
* Maps Tesseract orientation constants to degrees.
*/
private static int convertToDegrees(int orientationValue) {
return switch (orientationValue) {
case 0 -> 0; // UP (Normal)
case 1 -> 90; // RIGHT
case 2 -> 180; // DOWN
case 3 -> 270; // LEFT
default -> -1;
};
}