How to Generate and Read QR Code using Python and OpenCV?

How to Generate and Read QR Code using Python and OpenCV?

In this tutorial, you will learn how to generate a QR code in Python, as well as reading it using OpenCV.

QR code is a type of matrix barcode that is machine readable optical label that contains information about the item to which it is attached. In practice, QR codes often contain data for a locator, identifier, or tracker that points to a website or application.

Installing required dependencies:

pip3 install opencv-python qrco
Generate QR Code

It is basically straight forward to generate QR code using qrcode library:

import qrcode
# example data
data = "https://www.thepythoncode.com"
# output file name
filename = "site.png"
# generate qr code
img = qrcode.make(data)
# save img to a file
img.save(filename)

This will generate a new file in the current directory with the name of "site.png", which contains a QR code image of the data specified, easy enough?

Read QR Code

There are many tools that reads QR code. However, we will be using OpenCV for that, as it is popular and easy to integrate with the webcam. Alright, open up a new Python file and follow along with me:

Let's read the image that is just generated:

import cv2
# read the QRCODE image
img = cv2.imread("site.png")

Luckily for us, OpenCV already got QR code detector built in:

# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()

We have the image and the detector, let's detect and decode that data:

# detect and decode
data, bbox, straight_qrcode = detector.detectAndDecode(img)

detectAndDecode() function takes an image as an input and returns a tuple of 3 values: the data decoded from the QR code, the output array of vertices of the found QR code quadrangle and the output image containing rectified and binarized QR code.

We just need data and bbox here, bbox will help us draw the quadrangle in the image and data will be printed to the console!

Let's do it:

# if there is a QR code
if bbox is not None:
    print(f"QRCode data:\n{data}")
    # display the image with lines
    # length of bounding box
    n_lines = len(bbox)
    for i in range(n_lines):
        # draw all lines
        point1 = tuple(bbox[i][0])
        point2 = tuple(bbox[(i+1) % n_lines][0])
        cv2.line(img, point1, point2, color=(255, 0, 0), thickness=2)

cv2.line() function draws a line segment connecting two points, we retrieve these points from bbox array that was decoded by detectAndDecode() previously. we specified a blue color ( (255, 0, 0) is blue as OpenCV uses BGR colors ) and thickness of 2.

Finally, let's show the image and quit when a key is pressed:

# display the result
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

We are done with this script, try to run it and see your own results!

If you want to detect and decode QR codes live using your webcam (and I'm sure you do), here is a code for that:

import cv2
# initalize the cam
cap = cv2.VideoCapture(0)
# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()
while True:
    _, img = cap.read()
    # detect and decode
    data, bbox, _ = detector.detectAndDecode(img)
    # check if there is a QRCode in the image
    if bbox is not None:
        # display the image with lines
        for i in range(len(bbox)):
            # draw all lines
            cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255, 0, 0), thickness=2)
        if data:
            print("[+] QR Code detected, data:", data)
    # display the result
    cv2.imshow("img", img)    
    if cv2.waitKey(1) == ord("q"):
        break
cap.release()
cv2.destroyAllWindows()

Awesome, we are done with this tutorial, you can now integrate this in your own applications!

Check the full code here.

Happy Coding ♥

OpenCV Python Tutorial: Computer Vision With OpenCV In Python

OpenCV Python Tutorial: Computer Vision With OpenCV In Python

OpenCV Python Tutorial: Computer Vision With OpenCV In Python: Learn Vision Includes all OpenCV Image Processing Features with Simple Examples. Face Detection, Face Recognition. Computer Vision is an AI based, that is, Artificial Intelligence based technology that allows computers to understand and label images. Use OpenCV to work with image files. Create Face Detection Software. Detect Objects, including corner, edge, and grid detection techniques with OpenCV and Python. Use Python and Deep Learning to build image classifiers. Use Python and OpenCV to draw shapes on images and videos. Create Color Histograms with OpenCV

OpenCV Python Tutorial: Computer Vision With OpenCV In Python

Learn Vision Includes all OpenCV Image Processing Features with Simple Examples.

Computer Vision is an AI based, that is, Artificial Intelligence based technology that allows computers to understand and label images. Its now used in Convenience stores, Driver-less Car Testing, Security Access Mechanisms, Policing and Investigations Surveillance, Daily Medical Diagnosis monitoring health of crops and live stock and so on and so forth..

A common example will be face detection and unlocking mechanism that you use in your mobile phone. We use that daily. That is also a big application of Computer Vision. And today, top technology companies like Amazon, Google, Microsoft, Facebook etc are investing millions and millions of Dollars into Computer Vision based research and product development.

Computer vision allows us to analyze and leverage image and video data, with applications in a variety of industries, including self-driving cars, social network apps, medical diagnostics, and many more.

As the fastest growing language in popularity, Python is well suited to leverage the power of existing computer vision libraries to learn from all this image and video data.

What you'll learn

  • Use OpenCV to work with image files
  • Perform image manipulation with OpenCV, including smoothing, blurring, thresholding, and morphological operations.
  • Create Face Detection Software
  • Detect Objects, including corner, edge, and grid detection techniques with OpenCV and Python
  • Use Python and Deep Learning to build image classifiers
  • Use Python and OpenCV to draw shapes on images and videos
  • Create Color Histograms with OpenCV
  • Study from MIT notes and get Interview questions
  • Crack image processing limits by developing Applications.

A guide to Face Detection in Python

Face Detection using Open-CV

A guide to Face Detection with Golang and OpenCV

Implement Face Detection Using Python

Python Face Detection Tutorial for Beginners

OpenCV Python for Beginners - Learn Computer Vision with OpenCV 2020

 OpenCV Python for Beginners - Learn Computer Vision with OpenCV 2020

OpenCV Python for Beginners - Learn Computer Vision with OpenCV in 10 Hours (2020). You'll learn: Introduction to OpenCV; How to Install OpenCV for Python on Windows 10; How to Read, Write, Show Images in OpenCV; How to Read, Write, Show Videos from Camera in OpenCV; matplotlib with OpenCV; Image Pyramids with Python and OpenCV; Canny Edge Detection in OpenCV; Image Blending using Pyramids in OpenCV; Face Detection using Haar Cascade Classifiers ...

Welcome to this courese on OpenCV Python Tutorial For Beginners.
OpenCV is an image processing library created by Intel and later supported by Willow Garage and now maintained by Itseez. opencv is available on Mac, Windows, Linux. Works in C, C++, and Python.
it is Open Source and free. opencv is easy to use and install.

Starting with an overview of what the course will be covering, we move on to discussing morphological operations and practically learn how they work on images. We will then learn contrast enhancement using equalization and contrast limiting. Finally we will learn 3 methods to subtract the background from the video and implement them using OpenCV.

At the end of this course, you will have a firm grasp of Computer Vision techniques using OpenCV libraries. This course will be your gateway to the world of data science.

Feel the real power of Python and programming! The course offers you a unique approach of learning how to code by solving real world problems.

1 - Introduction to OpenCV
2 - How to Install OpenCV for Python on Windows 10
3 - How to Read, Write, Show Images in OpenCV
4 - How to Read, Write, Show Videos from Camera in OpenCV
5 - Draw geometric shapes on images using Python OpenCV
6 - Setting Camera Parameters in OpenCV Python
7 - Show Date and Time on Videos using OpenCV Python
8 - Handle Mouse Events in OpenCV
9 - More Mouse Event Examples in OpenCV Python
10 - cv.split, cv.merge, cv.resize, cv.add, cv.addWeighted, ROI
11- Bitwise Operations (bitwise AND, OR, NOT and XOR)
12 - How to Bind Trackbar To OpenCV Windows
13 - Object Detection and Object Tracking Using HSV Color Space
14 - Simple Image Thresholding
15 - Adaptive Thresholding
16 - matplotlib with OpenCV
17 - Morphological Transformations
18 - Smoothing Images | Blurring Images OpenCV
19 - Image Gradients and Edge Detection
20 - Canny Edge Detection in OpenCV
21 - Image Pyramids with Python and OpenCV
22 - Image Blending using Pyramids in OpenCV
22 - Image Blending using Pyramids in OpenCV
23 - Find and Draw Contours with OpenCV in Python
24 - Motion Detection and Tracking Using Opencv Contours
25 - Detect Simple Geometric Shapes using OpenCV in Python
26 - Understanding image Histograms using OpenCV Python
27 - Template matching using OpenCV in Python
28 - Hough Line Transform Theory
29 - Hough Line Transform using HoughLines method in OpenCV
30 - Probabilistic Hough Transform using HoughLinesP in OpenCV
31 - Road Lane Line Detection with OpenCV (Part 1)
32 - Road Lane Line Detection with OpenCV (Part 2)
33 - Road Lane Line Detection with OpenCV (Part 3)
34 - Circle Detection using OpenCV Hough Circle Transform
35 - Face Detection using Haar Cascade Classifiers
36 - Eye Detection Haar Feature based Cascade Classifiers
37 - Detect Corners with Harris Corner Detector in OpenCV
38 - Detect Corners with Shi Tomasi Corner Detector in OpenCV
39 - How to Use Background Subtraction Methods in OpenCV
40 - Mean Shift Object Tracking
41 - Object Tracking Camshift Method

Machine Learning, Data Science and Deep Learning with Python

Machine Learning, Data Science and Deep Learning with Python

Complete hands-on Machine Learning tutorial with Data Science, Tensorflow, Artificial Intelligence, and Neural Networks. Introducing Tensorflow, Using Tensorflow, Introducing Keras, Using Keras, Convolutional Neural Networks (CNNs), Recurrent Neural Networks (RNNs), Learning Deep Learning, Machine Learning with Neural Networks, Deep Learning Tutorial with Python

Machine Learning, Data Science and Deep Learning with Python

Complete hands-on Machine Learning tutorial with Data Science, Tensorflow, Artificial Intelligence, and Neural Networks

Explore the full course on Udemy (special discount included in the link): http://learnstartup.net/p/BkS5nEmZg

In less than 3 hours, you can understand the theory behind modern artificial intelligence, and apply it with several hands-on examples. This is machine learning on steroids! Find out why everyone’s so excited about it and how it really works – and what modern AI can and cannot really do.

In this course, we will cover:
• Deep Learning Pre-requistes (gradient descent, autodiff, softmax)
• The History of Artificial Neural Networks
• Deep Learning in the Tensorflow Playground
• Deep Learning Details
• Introducing Tensorflow
• Using Tensorflow
• Introducing Keras
• Using Keras to Predict Political Parties
• Convolutional Neural Networks (CNNs)
• Using CNNs for Handwriting Recognition
• Recurrent Neural Networks (RNNs)
• Using a RNN for Sentiment Analysis
• The Ethics of Deep Learning
• Learning More about Deep Learning

At the end, you will have a final challenge to create your own deep learning / machine learning system to predict whether real mammogram results are benign or malignant, using your own artificial neural network you have learned to code from scratch with Python.

Separate the reality of modern AI from the hype – by learning about deep learning, well, deeply. You will need some familiarity with Python and linear algebra to follow along, but if you have that experience, you will find that neural networks are not as complicated as they sound. And how they actually work is quite elegant!

This is hands-on tutorial with real code you can download, study, and run yourself.