66 lines
2.1 KiB
Python
66 lines
2.1 KiB
Python
import sys
|
|
from PIL import Image
|
|
from pyzbar.pyzbar import decode
|
|
|
|
def decode_barcode_from_file(image_path):
|
|
"""
|
|
Decodes all barcodes found in a specified image file.
|
|
|
|
Args:
|
|
image_path (str): The file path to the barcode image.
|
|
|
|
Returns:
|
|
list: A list of decoded strings, or None if an error occurs.
|
|
"""
|
|
try:
|
|
# Open the image file using Pillow (PIL)
|
|
img = Image.open(image_path)
|
|
|
|
# Decode all barcodes found in the image
|
|
barcodes = decode(img)
|
|
|
|
if not barcodes:
|
|
print(f"❌ No barcode found in the image: {image_path}")
|
|
return None
|
|
|
|
print(f"✅ Found {len(barcodes)} barcode(s) in {image_path}:")
|
|
decoded_results = []
|
|
|
|
for i, barcode in enumerate(barcodes):
|
|
# The decoded data is returned as bytes, so we decode it to a string.
|
|
data = barcode.data.decode('utf-8')
|
|
|
|
# Print the details
|
|
print("-" * 30)
|
|
print(f"Barcode #{i + 1}")
|
|
print(f" Type: {barcode.type}")
|
|
print(f" Data: {data}")
|
|
|
|
# The 'rect' and 'polygon' attributes provide location data,
|
|
# useful for images with multiple barcodes.
|
|
# print(f" Location (Rect): {barcode.rect}")
|
|
|
|
decoded_results.append(data)
|
|
|
|
return decoded_results
|
|
|
|
except FileNotFoundError:
|
|
print(f"❌ Error: Image file not found at '{image_path}'")
|
|
return None
|
|
except Exception as e:
|
|
print(f"❌ An error occurred during decoding: {e}")
|
|
return None
|
|
|
|
if __name__ == "__main__":
|
|
# Ensure the script is called with an image file path
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python decode_barcode.py <path_to_barcode_image>")
|
|
print("Example: python decode_barcode.py 20251017_22h35m26s_grim.png")
|
|
sys.exit(1)
|
|
|
|
# Get the image path from command-line arguments
|
|
barcode_image_path = sys.argv[1]
|
|
|
|
# Run the decoder function
|
|
decode_barcode_from_file(barcode_image_path)
|