Skip to main content

04_image_analyzer/
04_image_analyzer.rs

1use std::path::PathBuf;
2
3use visionkit::prelude::*;
4
5fn asset_path() -> PathBuf {
6    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7        .join("examples")
8        .join("assets")
9        .join("live_text.png")
10}
11
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    let configuration = ImageAnalyzerConfiguration::new(
14        ImageAnalysisTypes::TEXT | ImageAnalysisTypes::MACHINE_READABLE_CODE,
15    )
16    .with_locales(["en-US"]);
17    println!(
18        "supported OCR languages: {}",
19        ImageAnalyzer::supported_text_recognition_languages()?.len()
20    );
21
22    if !ImageAnalyzer::is_supported() {
23        println!("ImageAnalyzer is not supported on this Mac");
24        return Ok(());
25    }
26
27    let analyzer = ImageAnalyzer::new()?;
28    let asset_path = asset_path();
29    let analyses = [
30        (
31            "imageAt:url",
32            analyzer.analyze_image_at_path(&asset_path, ImageOrientation::Up, &configuration)?,
33        ),
34        (
35            "nsimage",
36            analyzer.analyze_ns_image_at_path(&asset_path, ImageOrientation::Up, &configuration)?,
37        ),
38        (
39            "cgimage",
40            analyzer.analyze_cg_image_at_path(&asset_path, ImageOrientation::Up, &configuration)?,
41        ),
42        (
43            "ciimage",
44            analyzer.analyze_ci_image_at_path(&asset_path, ImageOrientation::Up, &configuration)?,
45        ),
46        (
47            "pixelBuffer",
48            analyzer.analyze_pixel_buffer_at_path(
49                &asset_path,
50                ImageOrientation::Up,
51                &configuration,
52            )?,
53        ),
54    ];
55
56    for (label, analysis) in analyses {
57        println!("{label}: {}", analysis.transcript()?);
58    }
59    Ok(())
60}