Site icon R-bloggers

Scanning QR codes in R

[This article was first published on rOpenSci - open tools for open science, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The latest version of the opencv R package can detect and decode QR codes!

# Install latest opencv
install.packages("opencv", repos = "https://ropensci.r-universe.dev")

There are two ways of using this: the ocv_qr_detect function tries to find the QR in an image file. It returns either a text string or NULL (if no QR code was found in the image):

img <- opencv::ocv_read('https://jeroen.github.io/images/qrtest.jpg')
opencv::ocv_qr_detect(img)
## https://www.r-project.org

Alternatively if your laptop has a camera, you can use R as a true QR code scanner! The qr_scanner function starts the camera device and filters the video stream through the above ocv_qr_detect until a QR code has been detected.

# This requires a camera
txt <- opencv::qr_scanner()

By default, both ocv_qr_detect and qr_scanner return the text value of the decoded QR code. But both functions also have an option draw = TRUE which will instead return an annotated image with the position and value of the QR drawn into the image, and qr text value as an attribute.

Generating QR codes in R

There exists another package on CRAN called qrcode (currently maintained by Thierry Onkelinx) which can generate most types of QR codes using R graphics, which is super cool.

We can combine the two packages to roundtrip text to QR codes in R:

## generate a qr code image
png("qr-test.png")
plot(qrcode::qr_code("This is a test!"))
dev.off()

# Verify that we can read it:
ocv_qr_detect(ocv_read('qr-test.png'))
## [1] "This is a test!"

So this provides a quick way to exchange small blobs of information between computers running R, without the need for any network connection.

To leave a comment for the author, please follow the link and comment on their blog: rOpenSci - open tools for open science.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version