Using opencv images with the Softek barcode reader toolkit

Here’s some C code that shows how to read an opencv cv::Mat image using the barcode reader toolkit. The main points to note are:

  • Read the image using the cv::IMREAD_GRAYSCALE flag
  • Flip the image vertically
  • Align the scan lines to 4 byte boundaries

#include <barcode.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

static void convertBitmapData(unsigned char *in, BITMAP *pBm)
{
int y ;
unsigned char *out;

out = (unsigned char *) pBm->bmBits + (pBm->bmWidthBytes * pBm->bmHeight);

for (y = 0; y < pBm->bmHeight; y++)
{
out -= pBm->bmWidthBytes;
memcpy(out, in, pBm->bmWidth);
in += pBm->bmWidth;
}

}

main()
{
int i ;
int n ;
BITMAP bm ;
char **bar_codes ;
char **bar_codes_type ;
void *hBarcode ;

cv::Mat img = cv::imread(“somefile.tif”, cv::IMREAD_GRAYSCALE);

bm.bmWidth = img.size().width;
bm.bmHeight = img.size().height;
bm.bmBitsPixel = 8; // from IMREAD_GRAYSCALE
bm.bmWidthBytes = bm.bmWidth ;
if (bm.bmWidthBytes % 4) bm.bmWidthBytes += 4 – (bm.bmWidthBytes % 4); // Pad to 4 byte boundary
bm.bmPlanes = 1;
bm.bmType = 1;
bm.bmBits = (void *) malloc (bm.bmWidthBytes * bm.bmHeight);

convertBitmapData((unsigned char *) img.data, &bm);

hBarcode = STCreateBarCodeSession() ;

n = STReadBarCodeFromBitmap(hBarcode, &bm, (float) 200, &bar_codes, &bar_codes_type, 0) ;

for (i = 0; i < n; i++)
std::cout << bar_codes[i] << std::endl;
}