|
| 1 | +--- |
| 2 | +slug: opencv-qr |
| 3 | +title: 'Scanning QR codes in R' |
| 4 | +date: '2023-10-30' |
| 5 | +author: Jeroen Ooms |
| 6 | +description: 'The new version of the opencv package includes a cool QR code scanner.' |
| 7 | +photogallery: true |
| 8 | +tags: |
| 9 | + - tech notes |
| 10 | + - packages |
| 11 | + - opencv |
| 12 | +--- |
| 13 | + |
| 14 | +The latest version of the [opencv R package](https://ropensci.r-universe.dev/opencv) can detect and decode QR codes! |
| 15 | + |
| 16 | +```r |
| 17 | +# Install latest opencv |
| 18 | +install.packages("opencv", repos = "https://ropensci.r-universe.dev") |
| 19 | +``` |
| 20 | + |
| 21 | +There are two ways of using this: the [`ocv_qr_detect`](https://docs.ropensci.org/opencv/reference/qrcode.html) 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: |
| 22 | + |
| 23 | +```r |
| 24 | +img <- opencv::ocv_read('https://jeroen.github.io/images/qrtest.jpg') |
| 25 | +opencv::ocv_qr_detect(img) |
| 26 | +## https://www.r-project.org |
| 27 | +``` |
| 28 | + |
| 29 | +Alternatively if your laptop has a camera, you can use R as a true QR code scanner! The [`qr_scanner`](https://docs.ropensci.org/opencv/reference/qrcode.html) function starts the camera device and filters the video stream through the above `ocv_qr_detect` until a QR code has been detected. |
| 30 | + |
| 31 | +```r |
| 32 | +# This requires a camera |
| 33 | +txt <- opencv::qr_scanner() |
| 34 | +``` |
| 35 | + |
| 36 | +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. |
| 37 | + |
| 38 | + |
| 39 | +{{< gallery >}} |
| 40 | +{{< figureforgallery src="input.jpg" alt="Input photo which includes a QR code" >}} |
| 41 | +{{< figureforgallery src="output.jpg" alt="Annotated output which shows the input plus highlighted QR area" >}} |
| 42 | +{{< /gallery >}} |
| 43 | + |
| 44 | +## Generating QR codes in R |
| 45 | + |
| 46 | +There exists another package on CRAN called [qrcode](https://thierryo.github.io/qrcode/) (currently maintained by Thierry Onkelinx) which can generate most types of QR codes using R graphics, which is super cool. |
| 47 | + |
| 48 | +We can combine the two packages to roundtrip text to QR codes in R: |
| 49 | + |
| 50 | +```r |
| 51 | +## generate a qr code image |
| 52 | +png("qr-test.png") |
| 53 | +plot(qrcode::qr_code("This is a test!")) |
| 54 | +dev.off() |
| 55 | + |
| 56 | +# Verify that we can read it: |
| 57 | +ocv_qr_detect(ocv_read('qr-test.png')) |
| 58 | +## [1] "This is a test!" |
| 59 | +``` |
| 60 | + |
| 61 | +So this provides a quick way to exchange small blobs of information between computers running R, without the need for any network connection. |
0 commit comments