comparison mupdf-source/thirdparty/zxing-cpp/wrappers/python/zxing.cpp @ 2:b50eed0cc0ef upstream

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