Introduction
QR codes have become ubiquitous in daily life. From restaurants and petrol pumps to retail shops, they are widely used for seamless payment transactions. But their utility goes far beyond payments. QR codes are a compact and efficient way to store information that can be quickly accessed by scanning.
In this guide, we'll explore the fundamentals of QR codes, understand how they work, and learn how to create them programmatically using Python. Whether you're a beginner or an experienced coder, this tutorial will equip you with the skills to master QR code generation and usage.
Learning Outcomes
- Learn the Fundamentals: Understand the core concepts of QR codes and their functionality in storing and sharing information seamlessly.
- Create and Customize with Python: Master the skills to generate, personalize, and utilize QR codes effectively in various scenarios using Python.
- Explore History and Benefits: Delve into the origins of QR codes and uncover their advantages across diverse applications.
- Hands-On Practice: Gain practical experience by creating a Wi-Fi QR code, simplifying network access for users.
- Discover Practical Applications: Explore the innovative ways QR codes are used in public spaces, businesses, and everyday life.
Table of contents
- Learning Outcomes
- What are QR Codes?
- QR Codes with Python
- Mini-Project : Creating a Wi-Fi QR Code
- Scanning the QR Code
- Practical Use Cases for QR Codes
- Conclusion
What are QR Codes?
Quick Response (QR) codes are two-dimensional matrix barcodes capable of storing various types of data, such as URLs, text, contact details, or Wi-Fi credentials. The term "Quick Response" reflects their ability to be decoded swiftly and efficiently at high speeds.
A typical QR code consists of black modules arranged in a square grid on a white background. Unlike traditional barcodes, which store information in a single direction (horizontally), QR codes store data both horizontally and vertically. This unique design allows them to hold significantly more information in a compact format.
Also Read: Discover GPT 4o API for Vision Text and Image Insights
History of QR Codes
QR codes were invented in 1994 by Denso Wave, a subsidiary of Toyota, in Japan. Initially, they were developed to improve the efficiency of tracking automobile parts during the manufacturing process. Traditional barcodes were limited in the amount of data they could store, prompting the need for a more robust solution.
The inventor, Masahiro Hara, and his team designed QR codes to store significantly more information while enabling fast and accurate scanning. Unlike conventional barcodes, which could only be read horizontally, QR codes introduced a two-dimensional matrix that allowed data to be encoded both horizontally and vertically.
Denso Wave chose not to patent the technology, making QR codes freely available to developers and businesses worldwide. This decision played a crucial role in their rapid adoption across industries. Over the years, QR codes have evolved far beyond their original purpose, becoming indispensable in various applications, including payments, marketing, logistics, and personal use. Today, QR codes are ubiquitous, bridging the gap between physical and digital worlds, and their simplicity and versatility continue to make them a vital technology in the modern age.
Why Use QR Codes?
QR codes have become a popular tool for various industries due to their versatility, efficiency, and ease of use. Here are some of the key reasons to use QR codes:
1- High Storage Capacity
Unlike traditional barcodes, QR codes can store diverse data types, such as URLs, contact details, email addresses, Wi-Fi credentials, and more. Their two-dimensional structure allows for significantly higher data capacity.
2- Quick and Easy Access
QR codes provide a seamless way to access information instantly by simply scanning them with a smartphone or scanner, eliminating the need for manual entry.
3- Cost-Effective Solution
Generating and printing QR codes is inexpensive, making them an accessible solution for businesses of all sizes.
4- Versatile Applications
QR codes are used across industries for various purposes, including mobile payments, marketing campaigns, product tracking, and event management.
5- User Engagement
By linking to dynamic content such as videos, forms, or social media profiles, QR codes enhance user interaction and engagement.
6- Contactless Convenience
In the age of digital transactions and hygiene awareness, QR codes enable contactless solutions for payments, menus, or information sharing, ensuring safety and convenience.
7- Easy to Customize and Track
QR codes can be branded and customized to include logos and colors, and dynamic QR codes can track user activity for analytics purposes.
8- Global Accessibility
With widespread smartphone adoption, QR codes are universally accessible, bridging the gap between offline and online environments.
Their ability to provide a simple, efficient, and interactive way to share information makes QR codes an essential tool in the digital age.
QR Codes with Python
In this section, we’ll learn how to create QR codes using Python. Starting with a simple QR code, we’ll explore various examples to demonstrate the process and eventually customize them further. We’ll use the qrcode library, a straightforward and efficient tool for generating QR codes.
pip install qrcode[pil]
Example1 : Generating a Simple QR Code
In this first example, we'll generate a basic QR code using the default settings. Here's the code:
import qrcode
from PIL import Image
# Data to be encoded
data = "Welcome to Genius Data Science"
# Create a QR code object with custom settings
qr = qrcode.QRCode(
version=5, # Size of the QR code (larger version for more data)
box_size=8, # Size of each box in the QR code grid
border=6 # Border thickness
)
# Add data to the QR code
qr.add_data(data)
qr.make(fit=True)
# Generate QR code image with custom colors
img = qr.make_image(fill='blue', back_color='yellow')
# Display the QR code
img.show()
# Save the image to a file
img.save('custom_qr_code.png')
Here’s an explanation of the parameters used in the code:
- Version: Controls the complexity and size of the QR code. Higher values result in larger QR codes with more data capacity.
- box_size: Defines the size of each individual box in the QR code grid.
- border: Determines the thickness of the outer white space (border) around the QR code.
The code above will generate a simple QR code encoding the text "Welcome to to Genuis Data Science." To view the output, simply scan the generated QR code with a QR code reader.
Example2: Generating a QR Code with Custom Colors
In this example, we focus on making the QR code more visually appealing by customizing its colors. To achieve this, you can change either the foreground color, the background color, or both. In this case, I've modified both the foreground and background colors. Feel free to experiment with different color combinations to see how the QR code looks with your own design preferences.
import qrcode
from PIL import Image
# Data to be encoded
data = "Welcome to Genius Data Science"
# Create a QR code object with custom settings
qr = qrcode.QRCode(
version=5, # Size of the QR code
box_size=10, # Size of each box in the QR code grid
border=4 # Border thickness
)
# Add data to the QR code
qr.add_data(data)
qr.make(fit=True)
# Generate the QR code with custom colors
img = qr.make_image(fill='green', back_color='black')
# Display the QR code
img.show()
# Save the image to a file
img.save('custom_colored_qr_code.png')
The code above will generate a QR code with a dark green foreground and a light yellow background. Simply scan the QR code to view the output with these custom colors.
Example3: QR Code Generation from Analytics Vidhya URL
In this example, we'll create a QR code that encodes the URL of Genius Data Science. This allows anyone who scans the code to directly visit the website. Here’s 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://geniusdatascience.blogspot.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 towards official page of Analytics Vidhya
Example4: QR Code with Embedded Logo and URL Combined
In this example, we will create a personalized QR code that not only links to the Genius Data Science website but also features a custom logo embedded in the center. This adds a unique and branded touch to the QR code. Let’s explore 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://geniusdatascience.blogspot.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 serves as an example that you can try with your code.
This version of the code brings an exciting flair and highlights the unique, branded nature of the QR code.
Example5: Reading QR Codes from an Image
In this section, I will demonstrate how to read and decode a QR code from an image using OpenCV. This is helpful when you need to extract data from a QR code that has already been created or shared as an image file. Simply use the previously generated QR code image as the new input, and then try out 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://geniusdatascience.blogspot.com/ "
Mini-Project : Creating a Wi-Fi QR Code
A QR code is a simple way to enable users to easily connect to a network by simply scanning the code. This method eliminates the need to manually type the Wi-Fi name or password. By using this approach, we can create a QR code that contains all the necessary information.
In this mini project, I will guide you through creating a QR code that stores Wi-Fi details. This can be highly useful in public spaces, offices, or even for personal use. The generated QR code will store Wi-Fi credentials, such as the network name (SSID), password, and security type (in my case, WPA2), making it easy for devices to connect. To get started with this mini project, you'll first need to find your Wi-Fi SSID, security type, and password by using the following Linux commands in the terminal. Make sure to run them 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 us now implement the code below:
# 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
Assuming you have successfully run the code I shared, you should now have the output QR code image. Simply scan it with a smartphone or QR scanner to connect to the Wi-Fi network. Follow these steps:
- Open the camera app or QR scanner on your phone.
- Point the camera at the QR code.
- On Android phones, the Wi-Fi network name will appear, and you’ll be prompted to connect automatically.
Practical Use Cases for QR Codes
This Wi-Fi QR code can be particularly useful in:
- Public Spaces: In places like cafes, libraries, gas stations, or hotels, where visitors can simply scan the code to connect without needing to ask for credentials.
- Home Networks: Allowing friends and family to connect easily to your network without the need to share your password.
- Business Settings: Enabling guests or employees to access the network without compromising security.
Conclusion
The examples in this article can be helpful for a wide range of purposes, whether for hobby projects or real-time applications. For instance, if something important occurs at home, you can easily invite friends by sharing the location information through a QR code.
Similarly, in an office or school setting, QR codes can be used for event scheduling and form filling, streamlining communication and making tasks more efficient.
Here is the Github link.
Key Takeaways
- QR codes are versatile tools that can store various types of data, such as URLs and Wi-Fi credentials.
- Python’s qrcode library makes it easy to create and customize QR codes.
- These codes enhance user experience by enabling quick, contactless sharing of information.
- Customizing QR codes with colors or logos can boost branding and visual appeal.
- Wi-Fi QR codes offer a seamless way to connect devices to a network without the need for manual entry.
- Mastering QR codes opens up the potential to streamline data sharing, improve user experiences, and facilitate rapid access to information.
More in this topic
- Step-by-Step: PDF Chatbots with Langchain and Ollama
- 7 Steps to Master Large Language Models
- 4 Essential Steps to Create Multi-Agent Nested Chats with AutoGen
- Step-by-Step: Your Own YouTube and Web Summarizer with LangChain
- 8 Popular Tools for RAG Applications You Need to Know
- Creating a Personal Assistant with LangChain: A Step-by-Step Guide