Skip to main content

tesseract_ocr_static/
common.rs

1use core::ffi::CStr;
2use core::ptr::NonNull;
3use std::ffi::OsStr;
4use std::path::Path;
5
6use crate::OcrEngineMode;
7use crate::PageSegmentationMode;
8
9/// Common tesseract methods.
10pub struct Tesseract {
11    pub(crate) ptr: NonNull<c::TessBaseAPI>,
12}
13
14impl Tesseract {
15    /// Returns data directory.
16    pub fn data_dir(&self) -> &Path {
17        let ptr = unsafe { c::TessBaseAPIGetDatapath(self.ptr.as_ptr()) };
18        assert!(!ptr.is_null());
19        let c_str = unsafe { CStr::from_ptr(ptr) };
20        let os_str = unsafe { OsStr::from_encoded_bytes_unchecked(c_str.to_bytes()) };
21        Path::new(os_str)
22    }
23
24    /// Returns OCR engine mode.
25    pub fn ocr_engine_mode(&self) -> OcrEngineMode {
26        let ret = unsafe { c::TessBaseAPIOem(self.ptr.as_ptr()) };
27        OcrEngineMode::from_raw(ret)
28    }
29
30    pub fn page_segmentation_mode(&self) -> PageSegmentationMode {
31        let ret = unsafe { c::TessBaseAPIGetPageSegMode(self.ptr.as_ptr()) };
32        PageSegmentationMode::from_raw(ret)
33    }
34
35    pub fn set_page_segmentation_mode(&mut self, mode: PageSegmentationMode) {
36        unsafe { c::TessBaseAPISetPageSegMode(self.ptr.as_ptr(), mode as u32) };
37    }
38
39    pub fn set_source_resolution(&mut self, pixels_per_inch: u32) {
40        unsafe { c::TessBaseAPISetSourceResolution(self.ptr.as_ptr(), pixels_per_inch as i32) };
41    }
42
43    pub fn set_min_orientation_margin(&mut self, margin: f64) {
44        unsafe { c::TessBaseAPISetMinOrientationMargin(self.ptr.as_ptr(), margin) };
45    }
46
47    pub fn clear(&mut self) {
48        unsafe { c::TessBaseAPIClear(self.ptr.as_ptr()) };
49    }
50
51    pub fn clear_cache(&mut self) {
52        unsafe { c::TessBaseAPIClearPersistentCache(self.ptr.as_ptr()) };
53    }
54
55    pub fn clear_adaptive_classifier(&mut self) {
56        unsafe { c::TessBaseAPIClearAdaptiveClassifier(self.ptr.as_ptr()) };
57    }
58}
59
60impl Drop for Tesseract {
61    fn drop(&mut self) {
62        unsafe { c::TessBaseAPIEnd(self.ptr.as_ptr()) };
63        unsafe { c::TessBaseAPIDelete(self.ptr.as_ptr()) };
64    }
65}