zxing.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * Copyright 2019 Tim Rae
  3. * Copyright 2021 Antoine Humbert
  4. * Copyright 2021 Axel Waggershauser
  5. */
  6. // SPDX-License-Identifier: Apache-2.0
  7. #include "BarcodeFormat.h"
  8. // Reader
  9. #include "ReadBarcode.h"
  10. #include "ZXAlgorithms.h"
  11. // Writer
  12. #ifdef ZXING_EXPERIMENTAL_API
  13. #include "WriteBarcode.h"
  14. #else
  15. #include "BitMatrix.h"
  16. #include "Matrix.h"
  17. #include "MultiFormatWriter.h"
  18. #include <cstring>
  19. #endif
  20. #include <pybind11/pybind11.h>
  21. #include <pybind11/stl.h>
  22. #include <optional>
  23. #include <sstream>
  24. #include <vector>
  25. using namespace ZXing;
  26. namespace py = pybind11;
  27. using namespace pybind11::literals; // to bring in the `_a` literal
  28. std::ostream& operator<<(std::ostream& os, const Position& points) {
  29. for (const auto& p : points)
  30. os << p.x << "x" << p.y << " ";
  31. os.seekp(-1, os.cur);
  32. os << '\0';
  33. return os;
  34. }
  35. auto read_barcodes_impl(py::object _image, const BarcodeFormats& formats, bool try_rotate, bool try_downscale, TextMode text_mode,
  36. Binarizer binarizer, bool is_pure, EanAddOnSymbol ean_add_on_symbol, bool return_errors,
  37. uint8_t max_number_of_symbols = 0xff)
  38. {
  39. const auto opts = ReaderOptions()
  40. .setFormats(formats)
  41. .setTryRotate(try_rotate)
  42. .setTryDownscale(try_downscale)
  43. .setTextMode(text_mode)
  44. .setBinarizer(binarizer)
  45. .setIsPure(is_pure)
  46. .setMaxNumberOfSymbols(max_number_of_symbols)
  47. .setEanAddOnSymbol(ean_add_on_symbol)
  48. .setReturnErrors(return_errors);
  49. const auto _type = std::string(py::str(py::type::of(_image)));
  50. py::buffer_info info;
  51. ImageFormat imgfmt = ImageFormat::None;
  52. try {
  53. if (py::hasattr(_image, "__array_interface__")) {
  54. if (_type.find("PIL.") != std::string::npos) {
  55. _image.attr("load")();
  56. const auto mode = _image.attr("mode").cast<std::string>();
  57. if (mode == "L")
  58. imgfmt = ImageFormat::Lum;
  59. else if (mode == "RGB")
  60. imgfmt = ImageFormat::RGB;
  61. else if (mode == "RGBA")
  62. imgfmt = ImageFormat::RGBA;
  63. else {
  64. // Unsupported mode in ImageFormat. Let's do conversion to L mode with PIL.
  65. _image = _image.attr("convert")("L");
  66. imgfmt = ImageFormat::Lum;
  67. }
  68. }
  69. auto ai = _image.attr("__array_interface__").cast<py::dict>();
  70. auto shape = ai["shape"].cast<std::vector<py::ssize_t>>();
  71. auto typestr = ai["typestr"].cast<std::string>();
  72. if (typestr != "|u1")
  73. throw py::type_error("Incompatible __array_interface__ data type (" + typestr + "): expected a uint8_t array (|u1).");
  74. if (ai.contains("data")) {
  75. auto adata = ai["data"];
  76. if (py::isinstance<py::buffer>(adata)) {
  77. // PIL and our own __array_interface__ passes data as a buffer/bytes object
  78. info = adata.cast<py::buffer>().request();
  79. // PIL's bytes object has wrong dim/shape/strides info
  80. if (info.ndim != Size(shape)) {
  81. info.ndim = Size(shape);
  82. info.shape = shape;
  83. info.strides = py::detail::c_strides(shape, 1);
  84. }
  85. } else if (py::isinstance<py::tuple>(adata)) {
  86. // numpy data is passed as a tuple
  87. auto strides = py::detail::c_strides(shape, 1);
  88. if (ai.contains("strides") && !ai["strides"].is_none())
  89. strides = ai["strides"].cast<std::vector<py::ssize_t>>();
  90. auto data_ptr = reinterpret_cast<void*>(adata.cast<py::tuple>()[0].cast<py::size_t>());
  91. info = py::buffer_info(data_ptr, 1, "B", Size(shape), shape, strides);
  92. } else {
  93. throw py::type_error("No way to get data from __array_interface__");
  94. }
  95. } else {
  96. info = _image.cast<py::buffer>().request();
  97. }
  98. } else {
  99. info = _image.cast<py::buffer>().request();
  100. }
  101. #if PYBIND11_VERSION_HEX > 0x02080000 // py::raise_from is available starting from 2.8.0
  102. } catch (py::error_already_set &e) {
  103. py::raise_from(e, PyExc_TypeError, ("Invalid input: " + _type + " does not support the buffer protocol.").c_str());
  104. throw py::error_already_set();
  105. #endif
  106. } catch (...) {
  107. throw py::type_error("Invalid input: " + _type + " does not support the buffer protocol.");
  108. }
  109. if (info.format != py::format_descriptor<uint8_t>::format())
  110. throw py::type_error("Incompatible buffer format '" + info.format + "': expected a uint8_t array.");
  111. if (info.ndim != 2 && info.ndim != 3)
  112. throw py::type_error("Incompatible buffer dimension " + std::to_string(info.ndim) + " (needs to be 2 or 3).");
  113. const auto height = narrow_cast<int>(info.shape[0]);
  114. const auto width = narrow_cast<int>(info.shape[1]);
  115. const auto channels = info.ndim == 2 ? 1 : narrow_cast<int>(info.shape[2]);
  116. const auto rowStride = narrow_cast<int>(info.strides[0]);
  117. const auto pixStride = narrow_cast<int>(info.strides[1]);
  118. if (imgfmt == ImageFormat::None) {
  119. // Assume grayscale or BGR image depending on channels number
  120. if (channels == 1)
  121. imgfmt = ImageFormat::Lum;
  122. else if (channels == 3)
  123. imgfmt = ImageFormat::BGR;
  124. else
  125. throw py::value_error("Unsupported number of channels for buffer: " + std::to_string(channels));
  126. }
  127. const auto bytes = static_cast<uint8_t*>(info.ptr);
  128. // Disables the GIL during zxing processing (restored automatically upon completion)
  129. py::gil_scoped_release release;
  130. return ReadBarcodes({bytes, width, height, imgfmt, rowStride, pixStride}, opts);
  131. }
  132. std::optional<Barcode> read_barcode(py::object _image, const BarcodeFormats& formats, bool try_rotate, bool try_downscale,
  133. TextMode text_mode, Binarizer binarizer, bool is_pure, EanAddOnSymbol ean_add_on_symbol,
  134. bool return_errors)
  135. {
  136. auto res = read_barcodes_impl(_image, formats, try_rotate, try_downscale, text_mode, binarizer, is_pure, ean_add_on_symbol,
  137. return_errors, 1);
  138. return res.empty() ? std::nullopt : std::optional(res.front());
  139. }
  140. Barcodes read_barcodes(py::object _image, const BarcodeFormats& formats, bool try_rotate, bool try_downscale, TextMode text_mode,
  141. Binarizer binarizer, bool is_pure, EanAddOnSymbol ean_add_on_symbol, bool return_errors)
  142. {
  143. return read_barcodes_impl(_image, formats, try_rotate, try_downscale, text_mode, binarizer, is_pure, ean_add_on_symbol,
  144. return_errors);
  145. }
  146. #ifdef ZXING_EXPERIMENTAL_API
  147. Barcode create_barcode(py::object content, BarcodeFormat format, std::string ec_level)
  148. {
  149. auto cOpts = CreatorOptions(format).ecLevel(ec_level);
  150. auto data = py::cast<std::string>(content);
  151. if (py::isinstance<py::str>(content))
  152. return CreateBarcodeFromText(data, cOpts);
  153. else if (py::isinstance<py::bytes>(content))
  154. return CreateBarcodeFromBytes(data, cOpts);
  155. else
  156. throw py::type_error("Invalid input: only 'str' and 'bytes' supported.");
  157. }
  158. Image write_barcode_to_image(Barcode barcode, int size_hint, bool with_hrt, bool with_quiet_zones)
  159. {
  160. return WriteBarcodeToImage(barcode, WriterOptions().sizeHint(size_hint).withHRT(with_hrt).withQuietZones(with_quiet_zones));
  161. }
  162. std::string write_barcode_to_svg(Barcode barcode, int size_hint, bool with_hrt, bool with_quiet_zones)
  163. {
  164. return WriteBarcodeToSVG(barcode, WriterOptions().sizeHint(size_hint).withHRT(with_hrt).withQuietZones(with_quiet_zones));
  165. }
  166. #endif
  167. Image write_barcode(BarcodeFormat format, py::object content, int width, int height, int quiet_zone, int ec_level)
  168. {
  169. #ifdef ZXING_EXPERIMENTAL_API
  170. auto barcode = create_barcode(content, format, std::to_string(ec_level));
  171. return write_barcode_to_image(barcode, std::max(width, height), false, quiet_zone != 0);
  172. #else
  173. CharacterSet encoding [[maybe_unused]];
  174. if (py::isinstance<py::str>(content))
  175. encoding = CharacterSet::UTF8;
  176. else if (py::isinstance<py::bytes>(content))
  177. encoding = CharacterSet::BINARY;
  178. else
  179. throw py::type_error("Invalid input: only 'str' and 'bytes' supported.");
  180. auto writer = MultiFormatWriter(format).setEncoding(encoding).setMargin(quiet_zone).setEccLevel(ec_level);
  181. auto bits = writer.encode(py::cast<std::string>(content), width, height);
  182. auto bitmap = ToMatrix<uint8_t>(bits);
  183. Image res(bitmap.width(), bitmap.height());
  184. memcpy(const_cast<uint8_t*>(res.data()), bitmap.data(), bitmap.size());
  185. return res;
  186. #endif
  187. }
  188. PYBIND11_MODULE(zxingcpp, m)
  189. {
  190. m.doc() = "python bindings for zxing-cpp";
  191. // forward declaration of BarcodeFormats to fix BarcodeFormat function header typings
  192. // see https://github.com/zxing-cpp/zxing-cpp/pull/271
  193. py::class_<BarcodeFormats> pyBarcodeFormats(m, "BarcodeFormats");
  194. py::enum_<BarcodeFormat>(m, "BarcodeFormat", py::arithmetic{}, "Enumeration of zxing supported barcode formats")
  195. .value("Aztec", BarcodeFormat::Aztec)
  196. .value("Codabar", BarcodeFormat::Codabar)
  197. .value("Code39", BarcodeFormat::Code39)
  198. .value("Code93", BarcodeFormat::Code93)
  199. .value("Code128", BarcodeFormat::Code128)
  200. .value("DataMatrix", BarcodeFormat::DataMatrix)
  201. .value("EAN8", BarcodeFormat::EAN8)
  202. .value("EAN13", BarcodeFormat::EAN13)
  203. .value("ITF", BarcodeFormat::ITF)
  204. .value("MaxiCode", BarcodeFormat::MaxiCode)
  205. .value("PDF417", BarcodeFormat::PDF417)
  206. .value("QRCode", BarcodeFormat::QRCode)
  207. .value("MicroQRCode", BarcodeFormat::MicroQRCode)
  208. .value("RMQRCode", BarcodeFormat::RMQRCode)
  209. .value("DataBar", BarcodeFormat::DataBar)
  210. .value("DataBarExpanded", BarcodeFormat::DataBarExpanded)
  211. .value("DataBarLimited", BarcodeFormat::DataBarLimited)
  212. .value("DXFilmEdge", BarcodeFormat::DXFilmEdge)
  213. .value("UPCA", BarcodeFormat::UPCA)
  214. .value("UPCE", BarcodeFormat::UPCE)
  215. // use upper case 'NONE' because 'None' is a reserved identifier in python
  216. .value("NONE", BarcodeFormat::None)
  217. .value("LinearCodes", BarcodeFormat::LinearCodes)
  218. .value("MatrixCodes", BarcodeFormat::MatrixCodes)
  219. .export_values()
  220. // see https://github.com/pybind/pybind11/issues/2221
  221. .def("__or__", [](BarcodeFormat f1, BarcodeFormat f2){ return f1 | f2; });
  222. pyBarcodeFormats
  223. .def("__repr__", py::overload_cast<BarcodeFormats>(static_cast<std::string(*)(BarcodeFormats)>(ToString)))
  224. .def("__str__", py::overload_cast<BarcodeFormats>(static_cast<std::string(*)(BarcodeFormats)>(ToString)))
  225. .def("__eq__", [](BarcodeFormats f1, BarcodeFormats f2){ return f1 == f2; })
  226. .def("__or__", [](BarcodeFormats fs, BarcodeFormat f){ return fs | f; })
  227. .def(py::init<BarcodeFormat>());
  228. py::implicitly_convertible<BarcodeFormat, BarcodeFormats>();
  229. py::enum_<Binarizer>(m, "Binarizer", "Enumeration of binarizers used before decoding images")
  230. .value("BoolCast", Binarizer::BoolCast)
  231. .value("FixedThreshold", Binarizer::FixedThreshold)
  232. .value("GlobalHistogram", Binarizer::GlobalHistogram)
  233. .value("LocalAverage", Binarizer::LocalAverage)
  234. .export_values();
  235. py::enum_<EanAddOnSymbol>(m, "EanAddOnSymbol", "Enumeration of options for EAN-2/5 add-on symbols check")
  236. .value("Ignore", EanAddOnSymbol::Ignore, "Ignore any Add-On symbol during read/scan")
  237. .value("Read", EanAddOnSymbol::Read, "Read EAN-2/EAN-5 Add-On symbol if found")
  238. .value("Require", EanAddOnSymbol::Require, "Require EAN-2/EAN-5 Add-On symbol to be present")
  239. .export_values();
  240. py::enum_<ContentType>(m, "ContentType", "Enumeration of content types")
  241. .value("Text", ContentType::Text)
  242. .value("Binary", ContentType::Binary)
  243. .value("Mixed", ContentType::Mixed)
  244. .value("GS1", ContentType::GS1)
  245. .value("ISO15434", ContentType::ISO15434)
  246. .value("UnknownECI", ContentType::UnknownECI)
  247. .export_values();
  248. py::enum_<TextMode>(m, "TextMode", "")
  249. .value("Plain", TextMode::Plain, "bytes() transcoded to unicode based on ECI info or guessed charset (the default mode prior to 2.0)")
  250. .value("ECI", TextMode::ECI, "standard content following the ECI protocol with every character set ECI segment transcoded to unicode")
  251. .value("HRI", TextMode::HRI, "Human Readable Interpretation (dependent on the ContentType)")
  252. .value("Hex", TextMode::Hex, "bytes() transcoded to ASCII string of HEX values")
  253. .value("Escaped", TextMode::Escaped, "Use the EscapeNonGraphical() function (e.g. ASCII 29 will be transcoded to '<GS>'")
  254. .export_values();
  255. py::class_<PointI>(m, "Point", "Represents the coordinates of a point in an image")
  256. .def_readonly("x", &PointI::x,
  257. ":return: horizontal coordinate of the point\n"
  258. ":rtype: int")
  259. .def_readonly("y", &PointI::y,
  260. ":return: vertical coordinate of the point\n"
  261. ":rtype: int");
  262. py::class_<Position>(m, "Position", "The position of a decoded symbol")
  263. .def_property_readonly("top_left", &Position::topLeft,
  264. ":return: coordinate of the symbol's top-left corner\n"
  265. ":rtype: zxingcpp.Point")
  266. .def_property_readonly("top_right", &Position::topRight,
  267. ":return: coordinate of the symbol's top-right corner\n"
  268. ":rtype: zxingcpp.Point")
  269. .def_property_readonly("bottom_left", &Position::bottomLeft,
  270. ":return: coordinate of the symbol's bottom-left corner\n"
  271. ":rtype: zxingcpp.Point")
  272. .def_property_readonly("bottom_right", &Position::bottomRight,
  273. ":return: coordinate of the symbol's bottom-right corner\n"
  274. ":rtype: zxingcpp.Point")
  275. .def("__str__", [](Position pos) {
  276. std::ostringstream oss;
  277. oss << pos;
  278. return oss.str();
  279. });
  280. py::enum_<Error::Type>(m, "ErrorType", "")
  281. .value("None", Error::Type::None, "No error")
  282. .value("Format", Error::Type::Format, "Data format error")
  283. .value("Checksum", Error::Type::Checksum, "Checksum error")
  284. .value("Unsupported", Error::Type::Unsupported, "Unsupported content error")
  285. .export_values();
  286. py::class_<Error>(m, "Error", "Barcode reading error")
  287. .def_property_readonly("type", &Error::type,
  288. ":return: Error type\n"
  289. ":rtype: zxingcpp.ErrorType")
  290. .def_property_readonly("message", &Error::msg,
  291. ":return: Error message\n"
  292. ":rtype: str")
  293. .def("__str__", [](Error e) { return ToString(e); });
  294. py::class_<Barcode>(m, "Barcode", "The Barcode class")
  295. .def_property_readonly("valid", &Barcode::isValid,
  296. ":return: whether or not barcode is valid (i.e. a symbol was found and decoded)\n"
  297. ":rtype: bool")
  298. .def_property_readonly("text", [](const Barcode& res) { return res.text(); },
  299. ":return: text of the decoded symbol (see also TextMode parameter)\n"
  300. ":rtype: str")
  301. .def_property_readonly("bytes", [](const Barcode& res) { return py::bytes(res.bytes().asString()); },
  302. ":return: uninterpreted bytes of the decoded symbol\n"
  303. ":rtype: bytes")
  304. .def_property_readonly("format", &Barcode::format,
  305. ":return: decoded symbol format\n"
  306. ":rtype: zxingcpp.BarcodeFormat")
  307. .def_property_readonly("symbology_identifier", &Barcode::symbologyIdentifier,
  308. ":return: decoded symbology idendifier\n"
  309. ":rtype: str")
  310. .def_property_readonly("ec_level", &Barcode::ecLevel,
  311. ":return: error correction level of the symbol (empty string if not applicable)\n"
  312. ":rtype: str")
  313. .def_property_readonly("content_type", &Barcode::contentType,
  314. ":return: content type of symbol\n"
  315. ":rtype: zxingcpp.ContentType")
  316. .def_property_readonly("position", &Barcode::position,
  317. ":return: position of the decoded symbol\n"
  318. ":rtype: zxingcpp.Position")
  319. .def_property_readonly("orientation", &Barcode::orientation,
  320. ":return: orientation (in degree) of the decoded symbol\n"
  321. ":rtype: int")
  322. .def_property_readonly(
  323. "error", [](const Barcode& res) { return res.error() ? std::optional(res.error()) : std::nullopt; },
  324. ":return: Error code or None\n"
  325. ":rtype: zxingcpp.Error")
  326. #ifdef ZXING_EXPERIMENTAL_API
  327. .def("to_image", &write_barcode_to_image,
  328. py::arg("size_hint") = 0,
  329. py::arg("with_hrt") = false,
  330. py::arg("with_quiet_zones") = true)
  331. .def("to_svg", &write_barcode_to_svg,
  332. py::arg("size_hint") = 0,
  333. py::arg("with_hrt") = false,
  334. py::arg("with_quiet_zones") = true)
  335. #endif
  336. ;
  337. m.attr("Result") = m.attr("Barcode"); // alias to deprecated name for the Barcode class
  338. m.def("barcode_format_from_str", &BarcodeFormatFromString,
  339. py::arg("str"),
  340. "Convert string to BarcodeFormat\n\n"
  341. ":type str: str\n"
  342. ":param str: string representing barcode format\n"
  343. ":return: corresponding barcode format\n"
  344. ":rtype: zxingcpp.BarcodeFormat");
  345. m.def("barcode_formats_from_str", &BarcodeFormatsFromString,
  346. py::arg("str"),
  347. "Convert string to BarcodeFormats\n\n"
  348. ":type str: str\n"
  349. ":param str: string representing a list of barcodes formats\n"
  350. ":return: corresponding barcode formats\n"
  351. ":rtype: zxingcpp.BarcodeFormats");
  352. m.def("read_barcode", &read_barcode,
  353. py::arg("image"),
  354. py::arg("formats") = BarcodeFormats{},
  355. py::arg("try_rotate") = true,
  356. py::arg("try_downscale") = true,
  357. py::arg("text_mode") = TextMode::HRI,
  358. py::arg("binarizer") = Binarizer::LocalAverage,
  359. py::arg("is_pure") = false,
  360. py::arg("ean_add_on_symbol") = EanAddOnSymbol::Ignore,
  361. py::arg("return_errors") = false,
  362. "Read (decode) a barcode from a numpy BGR or grayscale image array or from a PIL image.\n\n"
  363. ":type image: buffer|numpy.ndarray|PIL.Image.Image\n"
  364. ":param image: The image object to decode. The image can be either:\n"
  365. " - a buffer with the correct shape, use .cast on memory view to convert\n"
  366. " - a numpy array containing image either in grayscale (1 byte per pixel) or BGR mode (3 bytes per pixel)\n"
  367. " - a PIL Image\n"
  368. ":type formats: zxing.BarcodeFormat|zxing.BarcodeFormats\n"
  369. ":param formats: the format(s) to decode. If ``None``, decode all formats.\n"
  370. ":type try_rotate: bool\n"
  371. ":param try_rotate: if ``True`` (the default), decoder searches for barcodes in any direction; \n"
  372. " if ``False``, it will not search for 90° / 270° rotated barcodes.\n"
  373. ":type try_downscale: bool\n"
  374. ":param try_downscale: if ``True`` (the default), decoder also scans downscaled versions of the input; \n"
  375. " if ``False``, it will only search in the resolution provided.\n"
  376. ":type text_mode: zxing.TextMode\n"
  377. ":param text_mode: specifies the TextMode that governs how the raw bytes content is transcoded to text.\n"
  378. " Defaults to :py:attr:`zxing.TextMode.HRI`."
  379. ":type binarizer: zxing.Binarizer\n"
  380. ":param binarizer: the binarizer used to convert image before decoding barcodes.\n"
  381. " Defaults to :py:attr:`zxing.Binarizer.LocalAverage`."
  382. ":type is_pure: bool\n"
  383. ":param is_pure: Set to True if the input contains nothing but a perfectly aligned barcode (generated image).\n"
  384. " Speeds up detection in that case. Default is False."
  385. ":type ean_add_on_symbol: zxing.EanAddOnSymbol\n"
  386. ":param ean_add_on_symbol: Specify whether to Ignore, Read or Require EAN-2/5 add-on symbols while scanning \n"
  387. " EAN/UPC codes. Default is ``Ignore``.\n"
  388. ":type return_errors: bool\n"
  389. ":param return_errors: Set to True to return the barcodes with errors as well (e.g. checksum errors); see ``Barcode.error``.\n"
  390. " Default is False."
  391. ":rtype: zxingcpp.Barcode\n"
  392. ":return: a Barcode if found, None otherwise"
  393. );
  394. m.def("read_barcodes", &read_barcodes,
  395. py::arg("image"),
  396. py::arg("formats") = BarcodeFormats{},
  397. py::arg("try_rotate") = true,
  398. py::arg("try_downscale") = true,
  399. py::arg("text_mode") = TextMode::HRI,
  400. py::arg("binarizer") = Binarizer::LocalAverage,
  401. py::arg("is_pure") = false,
  402. py::arg("ean_add_on_symbol") = EanAddOnSymbol::Ignore,
  403. py::arg("return_errors") = false,
  404. "Read (decode) multiple barcodes from a numpy BGR or grayscale image array or from a PIL image.\n\n"
  405. ":type image: buffer|numpy.ndarray|PIL.Image.Image\n"
  406. ":param image: The image object to decode. The image can be either:\n"
  407. " - a buffer with the correct shape, use .cast on memory view to convert\n"
  408. " - a numpy array containing image either in grayscale (1 byte per pixel) or BGR mode (3 bytes per pixel)\n"
  409. " - a PIL Image\n"
  410. ":type formats: zxing.BarcodeFormat|zxing.BarcodeFormats\n"
  411. ":param formats: the format(s) to decode. If ``None``, decode all formats.\n"
  412. ":type try_rotate: bool\n"
  413. ":param try_rotate: if ``True`` (the default), decoder searches for barcodes in any direction; \n"
  414. " if ``False``, it will not search for 90° / 270° rotated barcodes.\n"
  415. ":type try_downscale: bool\n"
  416. ":param try_downscale: if ``True`` (the default), decoder also scans downscaled versions of the input; \n"
  417. " if ``False``, it will only search in the resolution provided.\n"
  418. ":type text_mode: zxing.TextMode\n"
  419. ":param text_mode: specifies the TextMode that governs how the raw bytes content is transcoded to text.\n"
  420. " Defaults to :py:attr:`zxing.TextMode.HRI`."
  421. ":type binarizer: zxing.Binarizer\n"
  422. ":param binarizer: the binarizer used to convert image before decoding barcodes.\n"
  423. " Defaults to :py:attr:`zxing.Binarizer.LocalAverage`."
  424. ":type is_pure: bool\n"
  425. ":param is_pure: Set to True if the input contains nothing but a perfectly aligned barcode (generated image).\n"
  426. " Speeds up detection in that case. Default is False."
  427. ":type ean_add_on_symbol: zxing.EanAddOnSymbol\n"
  428. ":param ean_add_on_symbol: Specify whether to Ignore, Read or Require EAN-2/5 add-on symbols while scanning \n"
  429. " EAN/UPC codes. Default is ``Ignore``.\n"
  430. ":type return_errors: bool\n"
  431. ":param return_errors: Set to True to return the barcodes with errors as well (e.g. checksum errors); see ``Barcode.error``.\n"
  432. " Default is False.\n"
  433. ":rtype: list[zxingcpp.Barcode]\n"
  434. ":return: a list of Barcodes, the list is empty if none is found"
  435. );
  436. py::class_<Image>(m, "Image", py::buffer_protocol())
  437. .def_property_readonly(
  438. "__array_interface__",
  439. [](const Image& m) {
  440. return py::dict("version"_a = 3, "data"_a = m, "shape"_a = py::make_tuple(m.height(), m.width()), "typestr"_a = "|u1");
  441. })
  442. .def_property_readonly("shape", [](const Image& m) { return py::make_tuple(m.height(), m.width()); })
  443. .def_buffer([](const Image& m) -> py::buffer_info {
  444. return {
  445. const_cast<uint8_t*>(m.data()), // Pointer to buffer
  446. sizeof(uint8_t), // Size of one scalar
  447. py::format_descriptor<uint8_t>::format(), // Python struct-style format descriptor
  448. 2, // Number of dimensions
  449. {m.height(), m.width()}, // Buffer dimensions
  450. {m.rowStride(), m.pixStride()}, // Strides (in bytes) for each index
  451. true // read-only
  452. };
  453. });
  454. #ifdef ZXING_EXPERIMENTAL_API
  455. m.def("create_barcode", &create_barcode,
  456. py::arg("content"),
  457. py::arg("format"),
  458. py::arg("ec_level") = ""
  459. );
  460. m.def("write_barcode_to_image", &write_barcode_to_image,
  461. py::arg("barcode"),
  462. py::arg("size_hint") = 0,
  463. py::arg("with_hrt") = false,
  464. py::arg("with_quiet_zones") = true
  465. );
  466. m.def("write_barcode_to_svg", &write_barcode_to_svg,
  467. py::arg("barcode"),
  468. py::arg("size_hint") = 0,
  469. py::arg("with_hrt") = false,
  470. py::arg("with_quiet_zones") = true
  471. );
  472. #endif
  473. m.attr("Bitmap") = m.attr("Image"); // alias to deprecated name for the Image class
  474. m.def("write_barcode", &write_barcode,
  475. py::arg("format"),
  476. py::arg("text"),
  477. py::arg("width") = 0,
  478. py::arg("height") = 0,
  479. py::arg("quiet_zone") = -1,
  480. py::arg("ec_level") = -1,
  481. "Write (encode) a text into a barcode and return 8-bit grayscale bitmap buffer\n\n"
  482. ":type format: zxing.BarcodeFormat\n"
  483. ":param format: format of the barcode to create\n"
  484. ":type text: str|bytes\n"
  485. ":param text: the text/content of the barcode. A str is encoded as utf8 text and bytes as binary data\n"
  486. ":type width: int\n"
  487. ":param width: width (in pixels) of the barcode to create. If undefined (or set to 0), barcode will be\n"
  488. " created with the minimum possible width\n"
  489. ":type height: int\n"
  490. ":param height: height (in pixels) of the barcode to create. If undefined (or set to 0), barcode will be\n"
  491. " created with the minimum possible height\n"
  492. ":type quiet_zone: int\n"
  493. ":param quiet_zone: minimum size (in pixels) of the quiet zone around barcode. If undefined (or set to -1), \n"
  494. " the minimum quiet zone of respective barcode is used."
  495. ":type ec_level: int\n"
  496. ":param ec_level: error correction level of the barcode (Used for Aztec, PDF417, and QRCode only).\n"
  497. ":rtype: zxingcpp.Bitmap\n"
  498. );
  499. }