教程 | OpenCV4.1.2中實時高效的二維碼識別模塊

  • 2019 年 11 月 27 日
  • 筆記

OpenCV4.0發佈了二維碼檢測與解析模塊,但是大家用完以後都吐槽不已,覺得效果太差啦,根本不支持旋轉與傾斜角度下的二維碼檢測與解析,讓大家白高興一場。在OpenCV4.1.2的release發佈中有一部分是關於二維碼模塊精度與速度改善的說明,這麼說OpenCV4.1.2中二維碼檢測與解析效果變好啦,我抱着一絲懷疑的態度,重新測試了一下,先看效果吧:

速度沒問題!傾斜與錯切視角沒有問題,果然是提升了!夠強大!

函數調用

OpenCV4中負責二維碼檢測與解析的類是QRCodeDetector,它有如下幾個方法來實現二維碼的檢測與解析返回。

1.負責從圖像中找到二維碼區域,返回的是二維碼四個頂點的坐標。

detect (InputArray img, OutputArray points) const  img參數是輸入圖像,支持灰度或者彩色  points是vector返回的四個點坐標數組

2.負責解析二維碼,返回utf-8字符串作為解析結果,無法解析返回空

decode (InputArray img, InputArray points, OutputArray straight_qrcode=noArray())  img表示輸入圖像  point表示檢測到四個點坐標  straight_qrcode表示解析的二維碼ROI

3.一步搞定二維碼檢測與解析。

detectAndDecode(  InputArray img, //輸入圖像  OutputArray points=noArray(), // 頂點坐標  OutputArray straight_qrcode=noArray() // ROI  )

代碼演示

最終實現的二維碼實時檢測程序(比較懶,在sample代碼上改改)。主要是分為如下幾個部分:

打開攝像頭

VideoCapture cap(0);  if (!cap.isOpened())  {  cout << "Cannot open a camera" << endl;  return -1;  }

二維碼檢測與解析

cap >> frame;  if (frame.empty())  {  cout << "End of video stream" << endl;  break;  }  // flip(frame, frame, 1);  cvtColor(frame, gray, COLOR_BGR2GRAY);      total.start();  bool result_detection = qrcode.detect(gray, transform);  if (result_detection)  {  printf("detect QR code....n");  decode_info = qrcode.decode(gray, transform, straight_barcode);  cout << decode_info.c_str() << endl;  putText(frame, decode_info.c_str(), Point(50, 50), FONT_HERSHEY_PLAIN, 1.0, Scalar(255, 0, 0), 2, 8);  }

計算FPS與繪製頂點

繪製FPS

ostringstream convert;  convert << cvRound(fps) << " FPS (QR detection)";  putText(color_image, convert.str(), Point(25, 25), FONT_HERSHEY_DUPLEX, 1, Scalar(0, 0, 255), 2);

繪製頂點

void drawQRCodeContour(Mat &color_image, vector<Point> transform)  {    if (!transform.empty())    {      double show_radius = (color_image.rows  > color_image.cols)        ? (2.813 * color_image.rows) / color_image.cols        : (2.813 * color_image.cols) / color_image.rows;      double contour_radius = show_radius * 0.4;          vector< vector<Point> > contours;      contours.push_back(transform);      drawContours(color_image, contours, 0, Scalar(211, 0, 148), cvRound(contour_radius));          RNG rng(1000);      for (size_t i = 0; i < 4; i++)      {        Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));        circle(color_image, transform[i], cvRound(show_radius), color, -1);      }    }  }

總結:

OpenCV3是沒有自帶的二維碼檢測與解析程序的,OpenCV4.1.2自帶的二維碼檢測程序比之前的要好用多了,直接部署到應用場景下速度與性能都沒有問題。只能說OpenCV4 二維碼識別靠譜!

Exit mobile version