ZXingOpenCV.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright 2020 Axel Waggershauser
  3. */
  4. // SPDX-License-Identifier: Apache-2.0
  5. #pragma once
  6. #include "ReadBarcode.h"
  7. #include <opencv2/opencv.hpp>
  8. inline ZXing::ImageView ImageViewFromMat(const cv::Mat& image)
  9. {
  10. using ZXing::ImageFormat;
  11. auto fmt = ImageFormat::None;
  12. switch (image.channels()) {
  13. case 1: fmt = ImageFormat::Lum; break;
  14. case 2: fmt = ImageFormat::LumA; break;
  15. case 3: fmt = ImageFormat::BGR; break;
  16. case 4: fmt = ImageFormat::BGRA; break;
  17. }
  18. if (image.depth() != CV_8U || fmt == ImageFormat::None)
  19. return {nullptr, 0, 0, ImageFormat::None};
  20. return {image.data, image.cols, image.rows, fmt};
  21. }
  22. inline ZXing::Barcodes ReadBarcodes(const cv::Mat& image, const ZXing::ReaderOptions& options = {})
  23. {
  24. return ZXing::ReadBarcodes(ImageViewFromMat(image), options);
  25. }
  26. inline void DrawBarcode(cv::Mat& img, ZXing::Barcode barcode)
  27. {
  28. auto pos = barcode.position();
  29. auto zx2cv = [](ZXing::PointI p) { return cv::Point(p.x, p.y); };
  30. auto contour = std::vector<cv::Point>{zx2cv(pos[0]), zx2cv(pos[1]), zx2cv(pos[2]), zx2cv(pos[3])};
  31. const auto* pts = contour.data();
  32. int npts = contour.size();
  33. cv::polylines(img, &pts, &npts, 1, true, CV_RGB(0, 255, 0));
  34. cv::putText(img, barcode.text(), zx2cv(pos[3]) + cv::Point(0, 20), cv::FONT_HERSHEY_DUPLEX, 0.5, CV_RGB(0, 255, 0));
  35. }