QR Code and Barcode Detection
API reference for detecting and decoding QR codes, barcodes, and other graphical codes.
GraphicalCodeDetector
Base class for graphical code detection and decoding.
Methods
detect
Detects graphical code in image and returns the quadrangle containing the code.
bool detect(InputArray img, OutputArray points) const
Grayscale or color (BGR) image containing (or not) graphical code
Output vector of vertices of the minimum-area quadrangle containing the code
Returns: true if a code is detected
decode
Decodes graphical code once it’s found by the detect() method.
std::string decode(
InputArray img,
InputArray points,
OutputArray straight_code = noArray()
) const
Grayscale or color (BGR) image containing graphical code
Quadrangle vertices found by detect() method
Optional output image containing binarized code
Returns: UTF8-encoded output string or empty string if the code cannot be decoded
detectAndDecode
Both detects and decodes graphical code.
std::string detectAndDecode(
InputArray img,
OutputArray points = noArray(),
OutputArray straight_code = noArray()
) const
Grayscale or color (BGR) image containing graphical code
Optional output array of vertices of the found graphical code quadrangle
Optional output image containing binarized code
Returns: Decoded string or empty string if not found
detectMulti
Detects multiple graphical codes in image.
bool detectMulti(InputArray img, OutputArray points) const
Grayscale or color (BGR) image
Output vector of vector of vertices of the minimum-area quadrangles containing the codes
Returns: true if at least one code is detected
decodeMulti
Decodes multiple graphical codes.
bool decodeMulti(
InputArray img,
InputArray points,
std::vector<std::string>& decoded_info,
OutputArrayOfArrays straight_code = noArray()
) const
Grayscale or color (BGR) image containing graphical codes
Vector of quadrangle vertices found by detect() method
decoded_info
std::vector<std::string>&
UTF8-encoded output vector of strings or empty vector if codes cannot be decoded
Optional output vector of images containing binarized codes
Returns: true if at least one code is decoded
detectAndDecodeMulti
Both detects and decodes multiple graphical codes.
bool detectAndDecodeMulti(
InputArray img,
std::vector<std::string>& decoded_info,
OutputArray points = noArray(),
OutputArrayOfArrays straight_code = noArray()
) const
decoded_info
std::vector<std::string>&
UTF8-encoded output vector of strings or empty vector if codes cannot be decoded
If there are QR codes encoded with Structured Append mode and all are detected and decoded correctly, the method writes the full message to the position corresponding to the 0-th code in the sequence. The rest of the QR codes from the same sequence have empty strings.
QRCodeDetector
QR code detector and decoder.
Constructor
cv::QRCodeDetector::QRCodeDetector()
Methods
setEpsX
Sets the epsilon used during horizontal scan of QR code stop marker detection.
QRCodeDetector& setEpsX(double epsX)
Epsilon neighborhood for determining the horizontal pattern of the scheme 1:1:3:1:1 according to QR code standard
Returns: Reference to this QRCodeDetector
setEpsY
Sets the epsilon used during vertical scan of QR code stop marker detection.
QRCodeDetector& setEpsY(double epsY)
Epsilon neighborhood for determining the vertical pattern of the scheme 1:1:3:1:1 according to QR code standard
Returns: Reference to this QRCodeDetector
setUseAlignmentMarkers
Enables or disables use of alignment markers to improve corner position.
QRCodeDetector& setUseAlignmentMarkers(bool useAlignmentMarkers)
Flag to enable alignment markers (enabled by default)
Returns: Reference to this QRCodeDetector
decodeCurved
Decodes QR code on a curved surface once found by detect().
std::string decodeCurved(
InputArray img,
InputArray points,
OutputArray straight_qrcode = noArray()
)
Grayscale or color (BGR) image containing QR code
Quadrangle vertices found by detect() method
Optional output image containing rectified and binarized QR code
Returns: UTF8-encoded output string or empty string if the code cannot be decoded
detectAndDecodeCurved
Both detects and decodes QR code on a curved surface.
std::string detectAndDecodeCurved(
InputArray img,
OutputArray points = noArray(),
OutputArray straight_qrcode = noArray()
)
getEncoding
Returns the encoding type for the decoded info from the latest decode call.
QRCodeEncoder::ECIEncodings getEncoding(int codeIdx = 0)
Index of the previously decoded QR code. For single code detection, use 0.
Returns: Encoding type (e.g., ECI_UTF8, ECI_SHIFT_JIS)
Example Usage
#include <opencv2/objdetect.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
// Create QR code detector
cv::QRCodeDetector detector;
// Detect and decode QR code
std::vector<cv::Point> points;
std::string decoded_info = detector.detectAndDecode(image, points);
if (!decoded_info.empty()) {
std::cout << "QR Code decoded: " << decoded_info << std::endl;
// Draw quadrangle around QR code
for (size_t i = 0; i < points.size(); i++) {
cv::line(image, points[i], points[(i+1) % points.size()],
cv::Scalar(0, 255, 0), 3);
}
} else {
std::cout << "QR Code not detected" << std::endl;
}
import cv2
# Create QR code detector
detector = cv2.QRCodeDetector()
# Detect and decode QR code
decoded_info, points, _ = detector.detectAndDecode(image)
if decoded_info:
print(f"QR Code decoded: {decoded_info}")
# Draw quadrangle around QR code
if points is not None:
points = points.astype(int)
for i in range(len(points)):
cv2.line(image, tuple(points[i][0]),
tuple(points[(i+1) % len(points)][0]),
(0, 255, 0), 3)
else:
print("QR Code not detected")
QRCodeEncoder
QR code encoder for generating QR codes.
Constructor
Use the static create() method.
static Ptr<QRCodeEncoder> create(
const QRCodeEncoder::Params& parameters = QRCodeEncoder::Params()
)
Enums
EncodeMode
enum EncodeMode {
MODE_AUTO = -1,
MODE_NUMERIC = 1,
MODE_ALPHANUMERIC = 2,
MODE_BYTE = 4,
MODE_ECI = 7,
MODE_KANJI = 8,
MODE_STRUCTURED_APPEND = 3
}
CorrectionLevel
enum CorrectionLevel {
CORRECT_LEVEL_L = 0, // ~7% error correction
CORRECT_LEVEL_M = 1, // ~15% error correction
CORRECT_LEVEL_Q = 2, // ~25% error correction
CORRECT_LEVEL_H = 3 // ~30% error correction
}
ECIEncodings
enum ECIEncodings {
ECI_SHIFT_JIS = 20,
ECI_UTF8 = 26
}
Params Structure
struct Params {
int version; // QR code version
CorrectionLevel correction_level; // Error correction level
EncodeMode mode; // Encoding mode
int structure_number; // Number of QR codes in Structured Append
}
Methods
encode
Generates QR code from input string.
void encode(const String& encoded_info, OutputArray qrcode)
encodeStructuredAppend
Generates QR code in Structured Append mode, splitting the message over multiple QR codes.
void encodeStructuredAppend(
const String& encoded_info,
OutputArrayOfArrays qrcodes
)
Vector of generated QR code images
Example Usage
#include <opencv2/objdetect.hpp>
#include <opencv2/imgcodecs.hpp>
// Create encoder with parameters
cv::QRCodeEncoder::Params params;
params.version = 5; // or -1 for automatic
params.correction_level = cv::QRCodeEncoder::CORRECT_LEVEL_M;
params.mode = cv::QRCodeEncoder::MODE_BYTE;
auto encoder = cv::QRCodeEncoder::create(params);
// Generate QR code
cv::Mat qrcode;
encoder->encode("https://opencv.org", qrcode);
// Save or display
cv::imwrite("qrcode.png", qrcode);
import cv2
# Create encoder with parameters
params = cv2.QRCodeEncoder_Params()
params.version = 5 # or -1 for automatic
params.correction_level = cv2.QRCodeEncoder_CORRECT_LEVEL_M
params.mode = cv2.QRCodeEncoder_MODE_BYTE
encoder = cv2.QRCodeEncoder.create(params)
# Generate QR code
qrcode = encoder.encode("https://opencv.org")
# Save or display
cv2.imwrite("qrcode.png", qrcode)
BarcodeDetector
Barcode detector and decoder. Inherits from GraphicalCodeDetector.
Constructor
cv::barcode::BarcodeDetector::BarcodeDetector()
cv::barcode::BarcodeDetector::BarcodeDetector(
const std::string& prototxt_path,
const std::string& model_path
)
Prototxt file path for the super resolution model (optional)
Model file path for the super resolution model (optional)
Methods
decodeWithType
Decodes barcode in image once found by detect().
bool decodeWithType(
InputArray img,
InputArray points,
std::vector<std::string>& decoded_info,
std::vector<std::string>& decoded_type
) const
Grayscale or color (BGR) image containing barcode
Vector of rotated rectangle vertices found by detect(). Order: bottomLeft, topLeft, topRight, bottomRight.
decoded_info
std::vector<std::string>&
UTF8-encoded output vector of strings or empty if codes cannot be decoded
decoded_type
std::vector<std::string>&
Vector of strings specifying the type of barcodes (e.g., “EAN_13”, “CODE_128”)
Returns: true if at least one valid barcode is found
detectAndDecodeWithType
Both detects and decodes barcode.
bool detectAndDecodeWithType(
InputArray img,
std::vector<std::string>& decoded_info,
std::vector<std::string>& decoded_type,
OutputArray points = noArray()
) const
Grayscale or color (BGR) image containing barcode
decoded_info
std::vector<std::string>&
UTF8-encoded output vector of strings
decoded_type
std::vector<std::string>&
Vector of strings specifying the barcode types
Optional output vector of vertices of the found barcode rectangle
Returns: true if at least one valid barcode is found
setDownsamplingThreshold
Sets detector downsampling threshold.
BarcodeDetector& setDownsamplingThreshold(double thresh)
Downsampling limit to apply (default 512). The detect method resizes the input image to this limit if the smallest dimension is greater than the threshold.
Returns: Reference to this BarcodeDetector
getDownsamplingThreshold
Gets detector downsampling threshold.
double getDownsamplingThreshold() const
Returns: Current downsampling threshold
setDetectorScales
Sets detector box filter sizes.
BarcodeDetector& setDetectorScales(const std::vector<float>& sizes)
Box filter sizes relative to minimum dimension of the image (default [0.01, 0.03, 0.06, 0.08])
Filter sizes directly correlate with the expected line widths for a barcode. If the downsampling limit is increased, filter sizes need to be adjusted inversely.
Returns: Reference to this BarcodeDetector
getDetectorScales
Gets detector box filter sizes.
void getDetectorScales(std::vector<float>& sizes) const
Output parameter for returning the sizes
setGradientThreshold
Sets detector gradient magnitude threshold.
BarcodeDetector& setGradientThreshold(double thresh)
Gradient magnitude threshold (default 64). Values between 16 and 1024 generally work.
Returns: Reference to this BarcodeDetector
getGradientThreshold
Gets detector gradient magnitude threshold.
double getGradientThreshold() const
Returns: Current gradient threshold
Example Usage
#include <opencv2/objdetect/barcode.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
// Create barcode detector
cv::barcode::BarcodeDetector detector;
// Optionally adjust parameters
detector.setDownsamplingThreshold(800);
detector.setGradientThreshold(64);
// Detect and decode barcodes
std::vector<std::string> decoded_info;
std::vector<std::string> decoded_type;
std::vector<cv::Point> points;
bool found = detector.detectAndDecodeWithType(
image, decoded_info, decoded_type, points
);
if (found) {
for (size_t i = 0; i < decoded_info.size(); i++) {
std::cout << "Barcode " << i << ": "
<< decoded_info[i] << " (Type: "
<< decoded_type[i] << ")" << std::endl;
}
} else {
std::cout << "No barcodes detected" << std::endl;
}
import cv2
# Create barcode detector
detector = cv2.barcode.BarcodeDetector()
# Optionally adjust parameters
detector.setDownsamplingThreshold(800)
detector.setGradientThreshold(64)
# Detect and decode barcodes
retval, decoded_info, decoded_type, points = \
detector.detectAndDecodeWithType(image)
if retval:
for i, (info, type_) in enumerate(zip(decoded_info, decoded_type)):
print(f"Barcode {i}: {info} (Type: {type_})")
else:
print("No barcodes detected")
Supported Barcode Types
The BarcodeDetector supports various 1D and 2D barcode formats:
- EAN-8, EAN-13
- UPC-A, UPC-E
- Code 39, Code 93, Code 128
- ITF (Interleaved 2 of 5)
- Codabar
- QR Code
- DataMatrix
- PDF417
See Also