Convert ImageBuffer<image::color::Luma<u8>, Vec<u8>> to byte array?


How to convert ImageBuffer<image::color::Luma, Vec> to byte array?

to pass image to tesseract - source

Example code:

  let img3=adaptive_threshold(&imgg,10);

  let tesseract = Tesseract::new(None, Some("eng")).unwrap();

  let imgbuf=img3.as_raw();
  let text = tesseract
  // .set_image("test/01.PNG").unwrap()
  .set_image_from_mem(&imgbuf).unwrap() // <-- WHAT TO PASS HERE?

Example project docclassifierrs/ at master · slavb18/docclassifierrs · GitHub

The ImageBuffer::as_raw() method will return a reference to the underlying container, Vec in this case. If your Luma type uses u8 pixels then you'll have a byte buffer that can be passed to tesseract.

There should be valid image, like PNG
Trying to use
let mut buf = Vec::new();
img.write_to(&mut buf, image::ImageOutputFormat::Png);

But "the trait Seek is not implemented for Vec<u8>"

Looking for example how to use img.write_to with buffer

You can wrap your buf in a std::io::Cursor to make it track the current location (Seek).

use std::io::Cursor;

let img = ...;
let mut buffer: Vec<u8> = Vec::new();
let mut writer = Cursor::new(&mut buffer);

img.write_to(&mut buf, image::ImageOutputFormat::Png)?;

Note that using write_to() will serialize the image using a specific format, while the phrase "byte array" is normally applied the image's uncompressed pixels.

Thank you!

This is working
let mut bytes = Vec::new();
img.write_to(&mut Cursor::new(&mut bytes), image::ImageOutputFormat::Png);

This is what tesseract (and libleptonica under hood) wants

There is source code of set_image_from_mem - source

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.