potblog

技術メモとかガジェットレビューとか

opencvとzbarを用いたQRコードの位置表示について

QRコードを検出するライブラリの一つにzbarがあります。
ZBarのインストール方法とQRコードの位置表示のサンプルプログラムを紹介します。

ZBarのインストール方法

ZBarを使ったバーコード読み取りツールとC/C++ から使う場合に必要なヘッダファイルをインストールします。

sudo apt install zbar-tools libzbar-dev

サンプルプログラム

第一引数に入力された画像を読み込み、その画像にQRコードがあれば位置を表示し、円で囲むサンプルプログラムです。

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

using namespace cv;
using namespace std;
using namespace zbar;

void get_qr_location(const Mat& src_, int *qrx, int *qry){
    Mat grey;
    cvtColor(src_,grey,CV_BGR2GRAY);

    int width = src_.cols;  
    int height = src_.rows;  
    uchar *raw = (uchar *)grey.data;  
    // wrap image data  
    Image image(width, height, "Y800", raw, width * height);  
    // scan the image for barcodes  
    ImageScanner scanner;  
    scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);  
    int n = scanner.scan(image);
    // extract results  
    for(Image::SymbolIterator symbol = image.symbol_begin();  
            symbol != image.symbol_end(); ++symbol) {  
        vector<Point> vp;  
        int n = symbol->get_location_size();  
        for(int i=0;i<n;i++){  
            vp.push_back(Point(symbol->get_location_x(i),symbol->get_location_y(i))); 
            *qrx += symbol->get_location_x(i)/n;
            *qry += symbol->get_location_y(i)/n;
        }  
    }  
}

int main(int argc, char* argv[]){
    Mat src = cv::imread(argv[1],1);
    int qr_location_x=0, qr_location_y=0;
    get_qr_location(src,&qr_location_x,&qr_location_y);
    cout<<qr_location_x<<":"<<qr_location_y<<endl;
    cv::circle(src,Point(qr_location_x,qr_location_y),100,cv::Scalar(0,255,0),10,1);

    // resize(src, src, cv::Size(), 0.3, 0.3);
    imshow("show",src);
    waitKey(0);

    return 0;
}

ビルドコマンド

g++ main.cpp -o main `pkg-config opencv` `pkg-config --libs opencv` `pkg-config --cflags zbar``pkg-config --libs zbar`

実行結果 f:id:potblog:20170718235838p:plain