1

I didn't find this solution on the net, had to figure it myself. So, for benefit of others, I'm posing this as a "question":

Can you improve my working interface of OpenCV 2.4+ to the C++ version of Zxing 2.2 1D barcode reader?

Here's my working but perhaps improvable implementation below:

/**
 * Gary Bradski, Reading 1D barcodes
 *   License BSD, (c) 2013
 *
 *   Working example of how to call zxing using OpenCV 2.4+ cv::Mat
 *
 * Calling example, this one for 128 barcodes:
 *
 *   Code128Reader cr; //Instantiate a zxing barcode reader, int this case for 128 barcodes, 
 *                     //  but you can use any of their 1D or multi readers here
 *   ... by magic, I find, rectify and islotate a barcode into cv::Mat barcodeImage
 *   decode_image(&cr, barcodeImage);  //Decode the isolated rectified barcode or fail
 *
 */

#include <string>
#include <fstream>
#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

//////////////ZXING BARCODE READER//////////////////////////////////////////
#include <zxing/LuminanceSource.h>
#include <zxing/MultiFormatReader.h>
#include <zxing/oned/OneDReader.h>
#include <zxing/oned/EAN8Reader.h>
#include <zxing/oned/EAN13Reader.h>
#include <zxing/oned/Code128Reader.h>
#include <zxing/datamatrix/DataMatrixReader.h>
#include <zxing/qrcode/QRCodeReader.h>
#include <zxing/aztec/AztecReader.h>
#include <zxing/common/GlobalHistogramBinarizer.h>
#include <zxing/Exception.h>

using namespace zxing;
using namespace oned;
using namespace datamatrix;
using namespace qrcode;
using namespace aztec;

class OpenCVBitmapSource : public LuminanceSource
{
private:
    cv::Mat m_pImage;

public:
    OpenCVBitmapSource(cv::Mat &image)
    : LuminanceSource(image.cols, image.rows)
    {
        m_pImage = image.clone();
    }

    ~OpenCVBitmapSource(){}

    int getWidth() const { return m_pImage.cols; }    
    int getHeight() const { return m_pImage.rows; }

    ArrayRef<char> getRow(int y, ArrayRef<char> row) const //See Zxing Array.h for ArrayRef def
    {
        int width_ = getWidth();
        if (!row)
            row = ArrayRef<char>(width_);
        const char *p = m_pImage.ptr<char>(y);
        for(int x = 0; x<width_; ++x, ++p)
            row[x] = *p;
        return row;
    }

    ArrayRef<char> getMatrix() const
    {
        int width_ = getWidth();
        int height_ =  getHeight();
        ArrayRef<char> matrix = ArrayRef<char>(width_*height_);
        for (int y = 0; y < height_; ++y)
        {
            const char *p = m_pImage.ptr<char>(y);
            int yoffset = y*width_;
            for(int x = 0; x < width_; ++x, ++p)
            {
                matrix[yoffset + x] = *p;
            }
        }
        return matrix;
    }
    /*
    // The following methods are not supported by this demo (the DataMatrix Reader doesn't call these methods)
    bool isCropSupported() const { return false; }
    Ref<LuminanceSource> crop(int left, int top, int width, int height) {}
    bool isRotateSupported() const { return false; }
    Ref<LuminanceSource> rotateCounterClockwise() {}
    */
};

void decode_image(Reader *reader, cv::Mat &image)
{
    try
    {
        Ref<OpenCVBitmapSource> source(new OpenCVBitmapSource(image));
        Ref<Binarizer> binarizer(new GlobalHistogramBinarizer(source));
        Ref<BinaryBitmap> bitmap(new BinaryBitmap(binarizer));
        Ref<Result> result(reader->decode(bitmap, DecodeHints(DecodeHints::TRYHARDER_HINT)));//+DecodeHints::DEFAULT_HINT)));
        cout << result->getText()->getText() << endl;
            //Export the read barcode here
    }
    catch (zxing::Exception& e)
    {
            //Export your failure to read the code here
        cerr << "Error: " << e.what() << endl;
    }
}

Forgot to attribute what I started with. There is an out of date (will not compile) implementation using IplImages here: http://www.idealsoftware.com/opensource/scan-1d-2d-barcodes-webcam-zxing-opencv-visual-c.html

This updates that solution so that it works with Zxing 2.2 and OpenCV 2.1+

1

1 Answer 1

2

I think you can avoid the matrix copy by replacing

Ref<OpenCVBitmapSource> source(new OpenCVBitmapSource(image));

With

Ref<LuminanceSource> source(new GreyscaleLuminanceSource(image.data, image.step, image.rows, 0, 0, image.cols, image.rows));
4
  • Perhaps. I'm starting to think there needs to be a deeper port so that OpenCV is used throughout. I hate scattered allocations, I like them all out front at once. I also don't like gluing the detector into the reader. I pass it a detected rectified image. I'd like to be able to modularly improve that part. The reader is "meh", on a challenging set, it gets about 50%. I think it could get maybe 80% by eye. May 30, 2013 at 17:28
  • I am not sure I understand what you mean by "deeper". Essentially, the role that OpenCV is playing here is just a data structure wrapped around raw char buffer. Ref<LuminanceSource> source(new GreyscaleLuminanceSource(image.data, image.step, image.rows, 0, 0, image.cols, image.rows)); simply converts cv::Mat to ZXing preferred data structure with only very small memory allocation. You can still pass in a ROI if you want to use your own detect region.
    – cxyzs7
    May 30, 2013 at 17:39
  • Not shown here is my 1D barcode detector, all in a few lines of OpenCV that finds all instances of barcodes in a quite challenging dataset (systematic variations from frontal parallel to more than 60 degree perspective + rotation). I now see an even better way of doing that were you can just reason over polygons. Therefore, I'd like a better separation of detector and reader. For the reader, I'd want to add methods that just reason over polygons and then one that uses pattern recognition (Gallo & Manduchi) that can read patterns even when some of the zero crossings are lost. May 31, 2013 at 0:50
  • Thank to cxyzs7, this is much clearer than what idealsoftware.com used. But directly providing the pointer didn't worked for me (v 2.4.8). I had to provide an ArrayRef: GreyscaleLuminanceSource( ArrayRef<char>( ( char * )image.data, image.step * image.rows ), image.step, image.rows, 0, 0, image.cols, image.rows ). Tanks for advice. Dec 29, 2015 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.