QR codes can be seen everywhere. Especially in restaurants, gas pumps, stores mainly to make payments. There are also many other applications. The main reason is that it is a simple way to store information in the form of a small, easy-to-scan image. In this guide, I'll help you master QR codes and how they work, and walk you through creating them using Python.
Learning outcomes
- Understand the basics of QR codes and their functionality.
- Mastering QR Codes allows you to efficiently create, customize, and apply QR Codes in various real-world scenarios using Python.
- Learn how to generate and customize QR codes using Python.
- Explore the history and benefits of QR codes in various applications.
- Get hands-on experience creating a Wi-Fi QR code for easy network access.
- Discover real-world uses for QR codes, including in public spaces and businesses.
This article was published as part of the Data Science Blogathon.
What are QR codes?
Quick Response (QR) codes are actually two-dimensional array barcodes that can store various types of data, such as URLs, text, contact information, or Wi-Fi credentials. Fast response indicating that the code content must be decoded very quickly at high speed. speed. Typically, the code consists of black modules arranged in a square pattern on a white background. Unlike traditional barcodes, which only contain information in one direction (horizontally). QR codes can store data both horizontally and vertically. Allowing much greater storage capacity.
History of QR codes
It was invented by Denso Wave in 1994 for the Toyota Group. The purpose was to track car parts during manufacturing. Their ability to store a significant amount of data and be able to scan it quickly made them popular in various industries over time.
Why use QR codes?
QR codes have several advantages:
- Easy to use: It can be scanned with a smartphone camera or with a dedicated QR scanner.
- Versatile : can store different types of data, including URLs, text, and more.
- Quick access: Provides information quickly with just one scan.
- Contactless: useful for contactless transactions and sharing.
QR codes with Python
In this section, I will explain how to generate QR codes using Python. We'll cover different examples to demonstrate the process, from creating a simple QR code to further customizing it. We will use the qrcode library, which provides an easy way to create QR codes. To get started, make sure you have the library installed:
pip install qrcode(pil)
Example 1: Generate a simple QR code
In this first example, create a basic QR code with the default settings. Here is the code:
import qrcode
from PIL import Image
#Data to be encoded
data = "Welcome to QR Code Tutorial"
#Create a QR code object
qr = qrcode.QRCode(
version=1, # Size of the QR code
box_size=10, # Size of each box in the QR code grid
border=4 # Border thickness
)
qr.add_data(data)
qr.make(fit=True)
#Generate QR code image
img = qr.make_image(fill="black", back_color="white")
img.show()
img.save('simple_qr_code.png')
Here is an explanation of the parameters used in the code:
- version: It will control the complexity and size of the code.
- box_size: Size of each box in the QR code.
- edge: the thickness of the outer blank.
The above code will generate a simple QR code that encodes the text “Welcome to the QR code tutorial.” The following will be the result, just scan the code to see the result.
Example 2: Generate a QR code with custom colors
What we are doing here is making the QR code more visually appealing. To achieve this, we have to change the foreground color or the background color or change both. In this example, I have changed both the foreground and background colors. You can try the code with different color combinations.
import qrcode
from PIL import Image
#Data to be encoded
data = "Welcome to QR Code Tutorial"
#Create a QR code object
qr = qrcode.QRCode(
version=1, # Size of the QR code
box_size=10, # Size of each box in the QR code grid
border=4 # Border thickness
)
qr.add_data(data)
qr.make(fit=True)
#Create a QR code with custom colors
img_colored = qr.make_image(fill_color="darkgreen", back_color="lightyellow")
img_colored.show()
img_colored.save('custom_color_qr_code.png')
The code above will generate a QR code with a dark green foreground and a light yellow background. Scan the code to see the result with these custom colors.
Example 3: Generating QR Code from Analytics Vidhya URL
In this example, a QR code is created that encodes the Analytics Vidhya URL. This allows anyone who scans the code to directly visit the website. Here is the code:
import qrcode
from PIL import Image
#Create the QR code as usual
qr = qrcode.QRCode(
version=5, # Version adjusted to include the logo
box_size=10,
border=4
)
qr.add_data("https://www.analyticsvidhya.com/")
qr.make(fit=True)
#Generate the QR code image
img = qr.make_image(fill="black", back_color="white")
#Save and show the result
img.save('QR_code_AnalyticsVidhya.png')
img.show()
Just scan it. The QR will direct you to the official Analytics Vidhya page
Example 4: QR code with embedded logo and URL combined
Here we will test a custom QR code that not only links to the Analytics Vidhya website but also features a custom logo embedded in the center. It can provide a distinctive and branded look. Let's dive into the code example.
import qrcode
from PIL import Image
# Create the QR code as usual
qr = qrcode.QRCode(
version=5, # Version adjusted to include a logo
box_size=10,
border=4
)
qr.add_data("https://www.analyticsvidhya.com/")
qr.make(fit=True)
# Generate the QR code image
img = qr.make_image(fill="black", back_color="white")
# Open the logo image
logo = Image.open('AV_logo.png')
# Calculate the size for the logo
logo_size = 100 # Set this according to your needs
logo = logo.resize((logo_size, logo_size), Image.Resampling.LANCZOS) # Use LANCZOS for high-quality downsampling
# Paste the logo onto the QR code
pos = ((img.size(0) - logo_size) // 2, (img.size(1) - logo_size) // 2)
img.paste(logo, pos, mask=logo)
# Save and show the result
img.save('QR_code_with_AnalyticsVidhya_Logo.png')
img.show()
The following cropped image is an example that you can try with your code:
This version of the code adds a touch of excitement and emphasizes the unique and branded aspect of the QR code.
Example 5: Read QR codes from an image
Here, I will show how to read and decode a QR code from an image using OpenCV. This is useful when you need to extract data from a QR code that has already been created or shared in an image file. Here is the code: Just take the above output QR code image as new input and then try the following code.
# !pip install opencv-python
import cv2
# Read the image file
image = cv2.imread('/home/Tutorials/Analytics Vidya/QR_code_with_AnalyticsVidhya_Logo.png')
# Initialize the QR code detector
detector = cv2.QRCodeDetector()
# Detect and decode the QR code
data, vertices_array, _ = detector.detectAndDecode(image)
if vertices_array is not None:
print(f"Decoded Data: {data}")
else:
print("QR code not detected.")
The output will be:
" Decoded Data: https://www.analyticsvidhya.com/ "
Miniproject: Creating a Wi-Fi QR code
The QR code is a simple way to allow users to connect to a network. Just by scanning the code. Using this we can avoid manually typing the wifi name or password. We can implement a QR code that contains all the necessary information.
In this mini project, I will guide you to create a QR code to store wifi details. It can be very useful in public places, offices and for personal use. The generated qr code will store wifi credentials such as network name. (SSID), password and security type (in my case WPA2), allowing devices to connect easily.
To try this mini project, you first need to find out your Wi-Fi SSID, Wi-Fi security type and password using the following Linux commands in the terminal. Remember, try one after another.
#1 Find the Wi-Fi SSID (Network Name)
nmcli -t -f active,ssid dev wifi | grep '^yes'
#2 Get Wi-Fi Security Type
# here my SSID Name is RAGAI_4G
nmcli -f ssid,security dev wifi | grep "RAGAI_4G"
#3Get Password
sudo grep -r "psk=" /etc/NetworkManager/system-connections/
Code implementation
Let's now implement the following code:
# Import the necessary library
import qrcode
# Define Wi-Fi credentials
wifi_ssid = "RAGAI_4G"#replace with your SSID Name
wifi_password = "PASSWORD" #Ur PASSWORD
wifi_security = "WPA2" # Can be 'WEP', 'WPA', or 'nopass' (no password)
# Create the QR code data in the format that encodes Wi-Fi information
wifi_data = f"WIFI:T:{wifi_security};S:{wifi_ssid};P:{wifi_password};;"
# Create a QR code object with desired settings
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4
)
# Add the Wi-Fi data to the QR code object
qr.add_data(wifi_data)
qr.make(fit=True)
# Generate the QR code image
img = qr.make_image(fill="black", back_color="white")
# Save the QR code image to a file
img.save('wifi_qr_code.png')
# Display the QR code image (for testing)
img.show()
print("Wi-Fi QR code saved successfully")
Scanning the QR code
I hope you have successfully tested the code I have shared. You now have the output QR code image. You can simply scan it with a smartphone or scanner to connect to the Wi-Fi network. Follow the steps one by one:
- Open the camera app or QR scanner on your phone.
- Point the camera at the QR code.
- Android phones will display the Wi-Fi network name and ask you to connect automatically.
Remember, if your phone does not have built-in apps, you can download any scanner app from Play Store.
Practical use cases for QR codes
This Wi-Fi QR code can be especially useful in:
- Public Spaces: In cafes, libraries, gas stations or hotels where visitors can simply scan the code to connect without requiring credentials.
- Home Networks: Giving friends and family an easy way to connect to your network without sharing your password.
- Business configuration: Share network access with guests or employees without compromising security.
Conclusion
The examples in this article can help you for various purposes and both in your hobby projects and in real-time projects. If any function occurs at your home, you can invite your friends by providing the location information with the help of a QR code. In the office or school, it can be used to schedule events and fill out forms.
Here is the Github link.
Key takeaways
- QR codes are versatile tools that store various types of data, from URLs to Wi-Fi credentials.
- piton
qrcode
The library simplifies the process of creating and customizing QR codes. - QR codes improve the user experience by allowing quick, contactless sharing of information.
- Customizing QR codes with colors or logos can improve branding and visual appeal.
- Wi-Fi QR codes provide a seamless way to connect devices to a network without needing to enter them manually.
- Mastering QR codes unlocks the potential to streamline data sharing, improve user experiences, and improve access to information quickly and efficiently.
Frequently asked questions
A. A QR code is a two-dimensional barcode that stores information such as URLs, text, or Wi-Fi credentials and can be quickly scanned with a camera or scanner.
A. You can use the qrcode
Python library to generate QR codes by installing it with pip install qrcode(pil)
and creating a QR code object with your data.
A. Yes, you can change the foreground and background colors, and even embed logos within the QR code for a more personalized look.
A. A Wi-Fi QR code stores network credentials (SSID, password, and security type) so users can connect to a network simply by scanning the code.
A. Yes, QR codes serve a variety of applications, such as sharing URLs, contact information, event details, and even Wi-Fi credentials.
A. Mastering QR codes allows you to easily create and customize codes for various purposes, such as sharing URLs, Wi-Fi credentials, and more, improving convenience and accessibility in digital interactions.
The media shown in this article is not the property of Analytics Vidhya and is used at the author's discretion.