### Setup Development Environment and Run Tests Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Commands to initialize a virtual environment, install dependencies, execute tests with coverage, and run the sample script. ```bash python -m venv venv source ./venv/bin/activate pip install -U pip pip install -r requirements.txt python -m pytest --verbose --cov=pylibdmtx --cov-report=term-missing --cov-report=html pylibdmtx python -m pylibdmtx.scripts.read_datamatrix pylibdmtx/tests/datamatrix.png ``` -------------------------------- ### Verify Installation with Scripts Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Uses the installed script to verify functionality. ```bash read_datamatrix --help read_datamatrix ``` -------------------------------- ### Install Package from PyPI Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Installs the package including optional scripts. ```bash pip install pylibdmtx[scripts] ``` -------------------------------- ### Install Dependencies for Testing Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Installs required dependencies and the package from Test PyPI. ```bash pip install enum34 pathlib pip install Pillow pip install --index https://testpypi.python.org/simple pylibdmtx ``` -------------------------------- ### Install pylibdmtx from GitHub Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/README.rst Install the latest version of pylibdmtx directly from its GitHub repository. ```bash pip install git+https://github.com/NaturalHistoryMuseum/pylibdmtx.git ``` -------------------------------- ### Install pylibdmtx and scripts from PyPI Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/README.rst Install the pylibdmtx package and its associated command-line scripts from the Python Package Index. ```bash pip install pylibdmtx pip install pylibdmtx[scripts] ``` -------------------------------- ### Decode Data Matrix barcode from PIL Image Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/README.rst Use the decode function to extract data from a Data Matrix barcode within a PIL Image object. Ensure Pillow is installed. ```python from pylibdmtx.pylibdmtx import decode from PIL import Image decode(Image.open('pylibdmtx/tests/datamatrix.png')) ``` -------------------------------- ### Decode Data Matrix barcode from NumPy ndarray Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/README.rst Decode a Data Matrix barcode directly from a NumPy ndarray, commonly obtained from image processing libraries like OpenCV. Ensure OpenCV is installed. ```python import cv2 from pylibdmtx.pylibdmtx import decode decode(cv2.imread('pylibdmtx/tests/datamatrix.png')) ``` -------------------------------- ### Initialize Test Environment on Windows Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Creates and activates a virtual environment for testing on Windows. ```bash c:\python27\python.exe -m venv test1 test1\scripts\activate ``` -------------------------------- ### Build Source and Wheel Distributions Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Generates source and platform-specific wheel builds for Windows and general environments. ```bash rm -rf build dist MANIFEST.in pylibdmtx.egg-info cp MANIFEST.in.all MANIFEST.in ./setup.py bdist_wheel cat MANIFEST.in.all MANIFEST.in.win32 > MANIFEST.in ./setup.py bdist_wheel --plat-name=win32 # Remove these dirs to prevent win32 DLL from being included in win64 build rm -rf build pylibdmtx.egg-info cat MANIFEST.in.all MANIFEST.in.win64 > MANIFEST.in ./setup.py bdist_wheel --plat-name=win_amd64 rm -rf build MANIFEST.in pylibdmtx.egg-info ``` -------------------------------- ### Upload to Test PyPI Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Uploads the built distributions to the Test PyPI repository. ```bash twine upload -r testpypi dist/* ``` -------------------------------- ### Release to PyPI Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Uploads the final distributions to the production PyPI repository. ```bash twine upload dist/* ``` -------------------------------- ### Integrate pylibdmtx with image processing libraries Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Demonstrates decoding and encoding barcodes using PIL, OpenCV, NumPy, and imageio, as well as handling raw pixel data. ```python from pylibdmtx.pylibdmtx import decode, encode from PIL import Image import numpy as np # PIL/Pillow integration pil_image = Image.open('barcode.png') results = decode(pil_image) # Convert encoded barcode to PIL Image encoded = encode(b'PIL Example') pil_barcode = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) pil_barcode.save('pil_output.png') # OpenCV integration (if cv2 is installed) try: import cv2 # Read with OpenCV, decode directly cv_image = cv2.imread('barcode.png') results = decode(cv_image) # Convert encoded barcode to OpenCV format encoded = encode(b'OpenCV Example') pil_image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) cv_barcode = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR) cv2.imwrite('opencv_output.png', cv_barcode) except ImportError: print("OpenCV not installed") # NumPy array integration numpy_array = np.array(Image.open('barcode.png')) results = decode(numpy_array) # imageio integration (if installed) try: import imageio imageio_image = imageio.imread('barcode.png') results = decode(imageio_image) except ImportError: print("imageio not installed") # Process grayscale images (8-bit) gray_image = Image.open('barcode.png').convert('L') results = decode(gray_image) # Process RGBA images (32-bit) rgba_image = Image.open('barcode.png').convert('RGBA') results = decode(rgba_image) # Working with raw pixel bytes rgb_image = Image.open('barcode.png').convert('RGB') pixels = rgb_image.tobytes() width, height = rgb_image.size results = decode((pixels, width, height)) ``` -------------------------------- ### Run Test Matrix with Tox Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/DEVELOPING.md Cleans existing tox environments and executes the full test matrix. ```bash rm -rf .tox && tox ``` -------------------------------- ### Command-Line Barcode Utilities Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Use command-line scripts to read and write barcodes. Requires the pylibdmtx[scripts] extra. ```bash # Read barcodes from image files read_datamatrix image1.png image2.png # Output: # Stegosaurus # Plesiosaurus # Write barcode to image file write_datamatrix output.png "Hello World" # Write with specific encoding size write_datamatrix --size 36x36 output.png "Product-12345" # Write with specific encoding scheme write_datamatrix --scheme Base256 output.png "Binary data here" # Show version read_datamatrix --version write_datamatrix --version ``` -------------------------------- ### Verify Encoding and Decoding Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Perform a roundtrip test by encoding data into a barcode and immediately decoding it to verify integrity. ```python from pylibdmtx.pylibdmtx import decode encoded = encode(b'Test Data 123') barcode_image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) decoded = decode(barcode_image) assert decoded[0].data == b'Test Data 123' ``` -------------------------------- ### Handle Library Errors Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Catch PyLibDMTXError exceptions to handle invalid image data, unsupported formats, or encoding failures. ```python from pylibdmtx.pylibdmtx import decode, encode from pylibdmtx.pylibdmtx_error import PyLibDMTXError from PIL import Image # Handle decoding errors try: # Invalid pixel data dimensions invalid_data = (bytes([0] * 10), 3, 3) # 10 bytes != 3x3 pixels decode(invalid_data) except PyLibDMTXError as e: print(f"Decode error: {e}") # Output: Inconsistent dimensions: image data of 10 bytes is not # divisible by (width x height = 9) # Handle unsupported bits-per-pixel try: # 40 bits per pixel is not supported invalid_bpp = (bytes([0] * 45), 3, 3) # 45 bytes / 9 pixels = 5 bytes/pixel = 40 bpp decode(invalid_bpp) except PyLibDMTXError as e: print(f"BPP error: {e}") # Output: Unsupported bits-per-pixel: [40] Should be one of [8, 16, 24, 32] # Handle encoding errors try: # Data too large for specified symbol size large_data = b' ' * 50 encode(large_data, size='10x10') except PyLibDMTXError as e: print(f"Encode error: {e}") # Output: Could not encode data, possibly because the image is not # large enough to contain the data # Handle invalid encoding parameters try: encode(b'test', scheme='invalid_scheme') except PyLibDMTXError as e: print(f"Invalid scheme: {e}") # Output: Invalid scheme [invalid_scheme]: should be one of ['Ascii', ...] try: encode(b'test', size='9x9') except PyLibDMTXError as e: print(f"Invalid size: {e}") # Output: Invalid size [9x9]: should be one of ['RectAuto', ...] # Safe decoding with graceful handling def safe_decode(image_path): try: image = Image.open(image_path) results = decode(image, timeout=5000) return [r.data.decode('utf-8', errors='replace') for r in results] except (PyLibDMTXError, IOError) as e: print(f"Failed to decode {image_path}: {e}") return [] ``` -------------------------------- ### Decode Data Matrix Barcodes with Fine-Tuning Parameters Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Reads Data Matrix barcodes using advanced parameters to fine-tune detection sensitivity and accuracy. Adjust parameters like gap_size, shrink, deviation, threshold, and error corrections for optimal results. ```python # Fine-tune detection with optional parameters results = decode( image, timeout=10000, # Max milliseconds to spend decoding gap_size=5, # Scan gap size shrink=1, # Image shrink factor deviation=10, # Square deviation tolerance threshold=50, # Edge detection threshold min_edge=10, # Minimum edge length max_edge=100, # Maximum edge length corrections=5, # Error correction level max_count=10 # Maximum barcodes to find ) ``` -------------------------------- ### Encode Data with Specified Encoding Scheme Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Generates a Data Matrix barcode image using a specific encoding scheme, such as Ascii, C40, Text, Base256, or automatic options. Choose the scheme based on the data type for optimal compression. ```python # Specify encoding scheme # Available schemes: 'Ascii', 'C40', 'Text', 'X12', 'Edifact', 'Base256', 'AutoFast', 'AutoBest' print(f"Available schemes: {ENCODING_SCHEME_NAMES}") encoded = encode(data, scheme='Base256') image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) ``` -------------------------------- ### Encode Data to Data Matrix Barcode Image Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Generates a Data Matrix barcode image from byte data using default settings (Ascii scheme, auto size). The output includes image dimensions and bits per pixel. ```python from pylibdmtx.pylibdmtx import encode, ENCODING_SIZE_NAMES, ENCODING_SCHEME_NAMES from PIL import Image # Basic encoding with default settings (Ascii scheme, auto size) data = b'Hello World' encoded = encode(data) image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) image.save('barcode.png') print(f"Image dimensions: {encoded.width}x{encoded.height}, BPP: {encoded.bpp}") ``` -------------------------------- ### Decode Data Matrix Barcodes from PIL Image Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Reads Data Matrix barcodes from a PIL Image. The results include the decoded data and its location. Ensure the image file exists. ```python from pylibdmtx.pylibdmtx import decode from PIL import Image import cv2 import numpy as np # Decode from PIL Image image = Image.open('barcode.png') results = decode(image) for barcode in results: print(f"Data: {barcode.data}") print(f"Location: left={barcode.rect.left}, top={barcode.rect.top}, width={barcode.rect.width}, height={barcode.rect.height}") ``` -------------------------------- ### Decode Data Matrix Barcodes with Timeout Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Reads Data Matrix barcodes from an image with a specified timeout in milliseconds to limit the processing time. This prevents long-running operations. ```python # Decode with timeout (milliseconds) to limit processing time results = decode(image, timeout=5000) ``` -------------------------------- ### Encode Data with Specified Symbol Size Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Generates a Data Matrix barcode image with a specific symbol size, which affects data capacity and resulting image dimensions. Available sizes include predefined dimensions like '10x10' or automatic options. ```python # Specify symbol size (affects data capacity and image dimensions) # Available sizes: 'ShapeAuto', 'SquareAuto', 'RectAuto', '10x10', '12x12', etc. print(f"Available sizes: {ENCODING_SIZE_NAMES}") encoded = encode(data, size='36x36') image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) # Result: 200x200 pixel image ``` -------------------------------- ### Encode data into a Data Matrix barcode image Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/README.rst Generate an image containing a Data Matrix barcode from input data. The function returns an object with image dimensions and pixel data, which can then be used to create an image file. ```python from pylibdmtx.pylibdmtx import encode encoded = encode('hello world'.encode('utf8')) img = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) img.save('dmtx.png') print(decode(Image.open('dmtx.png'))) ``` -------------------------------- ### Process Decoded and Encoded Data Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Access barcode metadata using named tuples and convert raw pixel data into PIL images. ```python from pylibdmtx.pylibdmtx import decode, encode, Decoded, Rect, Encoded from PIL import Image # Decoded namedtuple structure # Decoded(data=bytes, rect=Rect) # Rect(left=int, top=int, width=int, height=int) image = Image.open('barcode.png') results = decode(image) for result in results: # Access as namedtuple attributes data = result.data # bytes: the decoded barcode content rect = result.rect # Rect: location in image left = result.rect.left # int: x coordinate of left edge top = result.rect.top # int: y coordinate of top edge width = result.rect.width # int: width of barcode region height = result.rect.height # int: height of barcode region # Decode bytes to string if needed text = data.decode('utf-8') print(f"Found '{text}' at ({left}, {top}) size {width}x{height}") # When using return_vertices=True, rect contains Rect_vertices instead # Rect_vertices(P0=(x,y), P1=(x,y), P2=(x,y), P3=(x,y)) results = decode(image, return_vertices=True) for result in results: p0, p1, p2, p3 = result.rect.P0, result.rect.P1, result.rect.P2, result.rect.P3 print(f"Vertices: {p0}, {p1}, {p2}, {p3}") # Encoded namedtuple structure # Encoded(width=int, height=int, bpp=int, pixels=bytes) encoded = encode(b'test data') print(f"Width: {encoded.width}") # int: image width in pixels print(f"Height: {encoded.height}") # int: image height in pixels print(f"BPP: {encoded.bpp}") # int: bits per pixel (typically 24) print(f"Pixels: {len(encoded.pixels)} bytes") # bytes: raw RGB pixel data # Convert to PIL Image pil_image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) ``` -------------------------------- ### Decode Data Matrix Barcodes with Max Count Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Reads a limited number of Data Matrix barcodes from an image. This is useful when you expect a specific number of barcodes or want to optimize performance. ```python # Limit number of barcodes to read results = decode(image, max_count=1) ``` -------------------------------- ### Encode Binary Data to Data Matrix Barcode Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Encodes raw binary data into a Data Matrix barcode image, typically using the Base256 scheme for efficient representation of arbitrary byte sequences. Ensure the data is in bytes format. ```python # Encode binary data binary_data = bytes([0x00, 0x01, 0x02, 0xFF, 0xFE]) encoded = encode(binary_data, scheme='Base256') image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) image.save('binary_barcode.png') ``` -------------------------------- ### Decode Data Matrix Barcodes Returning Vertices Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Reads Data Matrix barcodes and returns their four corner vertices instead of a bounding rectangle. This provides more precise location information. ```python # Get four corner vertices instead of bounding rectangle results = decode(image, return_vertices=True) for barcode in results: # rect_vertices contains P0, P1, P2, P3 coordinates print(f"Data: {barcode.data}, Vertices: {barcode.rect}") ``` -------------------------------- ### Encode Text Data to Data Matrix Barcode Source: https://context7.com/naturalhistorymuseum/pylibdmtx/llms.txt Encodes text data into a Data Matrix barcode image. The text must be converted to bytes using a suitable encoding (e.g., UTF-8) before passing to the encode function. ```python # Encode text data - must convert string to bytes first text = "Product-12345" encoded = encode(text.encode('utf-8')) image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) image.save('product_code.png') ``` -------------------------------- ### Decode Data Matrix barcode from raw pixel data Source: https://github.com/naturalhistorymuseum/pylibdmtx/blob/master/README.rst Decode a Data Matrix barcode by providing raw pixel data along with its width and height. This is useful when working with image data not directly in PIL or OpenCV formats. ```python import cv2 from pylibdmtx.pylibdmtx import decode image = cv2.imread('pylibdmtx/tests/datamatrix.png') height, width = image.shape[:2] decode((image.tobytes(), width, height)) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.