barcode-QRcodeScanner.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <opencv2/opencv.hpp>
  2. #include <zbar.h>
  3. using namespace cv;
  4. using namespace std;
  5. using namespace zbar;
  6. typedef struct
  7. {
  8. string type;
  9. string data;
  10. vector <Point> location;
  11. } decodedObject;
  12. // Find and decode barcodes and QR codes
  13. void decode(Mat &im, vector<decodedObject>&decodedObjects)
  14. {
  15. // Create zbar scanner
  16. ImageScanner scanner;
  17. // Configure scanner
  18. scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);
  19. // Convert image to grayscale
  20. Mat imGray;
  21. cvtColor(im, imGray,COLOR_BGR2GRAY);
  22. // Wrap image data in a zbar image
  23. Image image(im.cols, im.rows, "Y800", (uchar *)imGray.data, im.cols * im.rows);
  24. // Scan the image for barcodes and QRCodes
  25. int n = scanner.scan(image);
  26. // Print results
  27. for(Image::SymbolIterator symbol = image.symbol_begin(); symbol != image.symbol_end(); ++symbol)
  28. {
  29. decodedObject obj;
  30. obj.type = symbol->get_type_name();
  31. obj.data = symbol->get_data();
  32. // Print type and data
  33. cout << "Type : " << obj.type << endl;
  34. cout << "Data : " << obj.data << endl << endl;
  35. // Obtain location
  36. for(int i = 0; i< symbol->get_location_size(); i++)
  37. {
  38. obj.location.push_back(Point(symbol->get_location_x(i),symbol->get_location_y(i)));
  39. }
  40. decodedObjects.push_back(obj);
  41. }
  42. }
  43. // Display barcode and QR code location
  44. void display(Mat &im, vector<decodedObject>&decodedObjects)
  45. {
  46. // Loop over all decoded objects
  47. for(int i = 0; i < decodedObjects.size(); i++)
  48. {
  49. vector<Point> points = decodedObjects[i].location;
  50. vector<Point> hull;
  51. // If the points do not form a quad, find convex hull
  52. if(points.size() > 4)
  53. convexHull(points, hull);
  54. else
  55. hull = points;
  56. // Number of points in the convex hull
  57. int n = hull.size();
  58. for(int j = 0; j < n; j++)
  59. {
  60. line(im, hull[j], hull[ (j+1) % n], Scalar(255,0,0), 3);
  61. }
  62. }
  63. // Display results
  64. imshow("Results", im);
  65. waitKey(0);
  66. }
  67. int main(int argc, char* argv[])
  68. {
  69. // Read image
  70. Mat im = imread("zbar-test.jpg");
  71. // Variable for decoded objects
  72. vector<decodedObject> decodedObjects;
  73. // Find and decode barcodes and QR codes
  74. decode(im, decodedObjects);
  75. // Display location
  76. display(im, decodedObjects);
  77. return EXIT_SUCCESS;
  78. }