1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#include <iostream> #include <opencv2/opencv.hpp> #include <zxing/BarcodeFormat.h> #include <zxing/DecodeHints.h> #include <zxing/Reader.h> #include <zxing/MultiFormatReader.h> #include <zxing/BinaryBitmap.h> #include <zxing/HybridBinarizer.h> #include <zxing/BitMatrix.h> #include <zxing/Result.h> using namespace std; using namespace cv; using namespace zxing; int main() { // Load the image containing the barcode string imagePath = "barcode.png"; Mat image = imread(imagePath, IMREAD_GRAYSCALE); if (image.empty()) { cerr << "Error loading image." << endl; return 1; } // Convert Mat image to zxing::BitMatrix int width = image.cols; int height = image.rows; vector<uchar> imgData(image.data, image.data + (width * height)); Ref<BitMatrix> bitMatrix = Ref<BitMatrix>(new BitMatrix(width, height)); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { uchar pixel = imgData[y * width + x]; bitMatrix->set(x, y, pixel < 128); } } // Create a BinaryBitmap from BitMatrix Ref<BinaryBitmap> binaryBitmap = Ref<BinaryBitmap>(new BinaryBitmap(Ref<HybridBinarizer>(new HybridBinarizer(bitMatrix)))); // Create a reader and decode the barcode MultiFormatReader reader; DecodeHints hints; hints.setTryHarder(true); Ref<Result> result = reader.decode(binaryBitmap, hints); // Output the result if (result) { cout << "Barcode text: " << result->getText()->getText() << endl; } else { cout << "No barcode found." << endl; } return 0; } |
Explanation
- Include Libraries:
#include <iostream>
: For input and output operations.#include <opencv2/opencv.hpp>
: For image processing using OpenCV.- ZXing headers for barcode processing.
Advertisement - Load the Image:
Mat image = imread(imagePath, IMREAD_GRAYSCALE);
: Load the image in grayscale mode using OpenCV.
- Convert OpenCV Image to ZXing BitMatrix Advertisement
- Extract pixel data from the
cv::Mat
object and convert it into a ZXingBitMatrix
. - Pixels are converted into a binary format where
pixel < 128
is treated as black, and others as white.
- Extract pixel data from the
- Create BinaryBitmap:
BinaryBitmap
is constructed using aHybridBinarizer
which processes theBitMatrix
.
- Decode the Barcode:
- Create a
MultiFormatReader
to decode the barcode from theBinaryBitmap
. - Set decoding hints to improve recognition.
- Create a
- Output the Result:
- If the barcode is successfully decoded, output the text; otherwise, indicate that no barcode was found.
Advertisement
Notes:
- ZXing Setup: Ensure ZXing and OpenCV libraries are correctly linked and included in your project.
- Image Path: Replace
"barcode.png"
with the path to your barcode image. - Library Dependencies: Ensure ZXing and OpenCV libraries are installed and configured in your build system.