Skip to content

Instantly share code, notes, and snippets.

@kunjee17
Created May 31, 2022 01:22
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 kunjee17/5ba9667e20df180e730a4904e0203fe9 to your computer and use it in GitHub Desktop.
Save kunjee17/5ba9667e20df180e730a4904e0203fe9 to your computer and use it in GitHub Desktop.
QR Code scan using rqrr rust.
/// Scan current video frame for a valid QR code containing customer id, returning it if found.
fn process_frame(&self) -> anyhow::Result<Option<i32>> {
// Get necessary elements
let video = self
.ref_video
.cast::<HtmlVideoElement>()
.ok_or(anyhow!("Video required"))?;
let context = self.context.as_ref().ok_or(anyhow!("Context required"))?;
let (width, height) = self.camera_dim;
// Draw frame to canvas
context
.draw_image_with_html_video_element_and_dw_and_dh(
&video,
0.0,
0.0,
width as f64,
height as f64,
)
.map_err(|e| anyhow!("{:?}", e))?;
// Get frame data
let frame = context
.get_image_data(0.0, 0.0, width as f64, height as f64)
.map_err(|e| anyhow!("{:?}", e))?
.data()
.0;
// Scan image data for a QR code
let image: image::RgbaImage =
image::ImageBuffer::from_vec(width as u32, height as u32, frame)
.ok_or(anyhow!("Error creating image buffer"))?;
let image = image::DynamicImage::ImageRgba8(image);
// rqrr will sometimes panic, so we need to catch it.
// See https://github.com/WanzenBug/rqrr/issues/3
std::panic::catch_unwind(|| {
let mut results = rqrr::PreparedImage::prepare(image.to_luma8());
for result in results.detect_grids().into_iter() {
// If a QR code is found and it can be parsed into a user ID, return it without
// looking at any other results.
if let Ok(Ok(id)) = result.decode().map(|(_, r)| r.parse::<i32>()) {
return Ok(Some(id));
}
}
Ok(None)
})
.map_err(|e| anyhow!("rqrr error: {:?}", e))?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment