Skip to main content
ExpireEye provides barcode and QR code scanning functionality using OpenCV’s computer vision library to quickly identify and add products to your inventory.

QR code scanning

The API includes a dedicated endpoint for scanning QR codes from uploaded images:
POST /api/qr

How it works

1

Upload image

You send an image file containing a QR code to the endpoint:
@app.post("/qr", tags=["QR Code"])
async def decode_qr_code(request: Request, file: UploadFile = File(...)):
    access_token = request.state.user
    user_id = access_token.get("userId")
2

Decode image with OpenCV

The image is converted from bytes to a numpy array and decoded:
image_bytes = await file.read()
np_arr = np.frombuffer(image_bytes, np.uint8)

# Decode image using OpenCV
img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
3

Save uploaded image

The uploaded file is saved to the uploads directory:
filename = (
    str(file.filename)
    if file.filename
    else f"qr_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
)
file_path = os.path.join("uploads", filename)

with open(file_path, "wb") as buffer:
    shutil.copyfileobj(file.file, buffer)
4

Detect and decode QR code

OpenCV’s QRCodeDetector is used to detect and decode the QR code:
# Initialize QRCode detector
detector = cv2.QRCodeDetector()

# Detect and decode
data, bbox, _ = detector.detectAndDecode(img)

if bbox is not None and data:
    return {"message": "QR Scanned successfully", "data": data}
else:
    return {"error": "No QR code found in the image"}

Request format

Send a multipart/form-data request with the image file:
curl -X POST "http://localhost:8000/api/qr" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -F "file=@/path/to/qr-code.jpg"

Response format

{
  "message": "QR Scanned successfully",
  "data": "Product information from QR code"
}

Barcode lookup system

ExpireEye includes a barcode-to-product mapping system for quick product identification:

Get all barcodes

GET /api/product/barcodes
Retrieve all products with their associated barcodes:
@router.get("/barcodes")
def get_products_barcode(db: Session = Depends(get_db)):
    products = db.query(Product).all()
    result = [
        {
            "productName": product.name,
            "barcode": product.barcode,
        }
        for product in products
    ]
    return {"products": result}

Barcode generation

When you add a product to the inventory, a barcode is automatically generated:
def generate_product_barcode(product_name: str) -> str:
    """
    Generates a simple barcode for a product based on its name.
    Uses a predefined mapping for known products. For test purposes.
    """
    product_name = product_name.title()
    return product_barcode_map.get(product_name, "UNKNOWN-20")

Predefined barcode mapping

The system includes barcodes for common products:
product_barcode_map = {
    "Apple": "AP29483",
    "Banana": "BN10375",
    "Lays": "8901491101813",
    "Kurkure": "KK42196",
    "Tomato": "TM77238",
    "Potato": "PT66120",
    "Onion": "ON95742",
    "Mango": "MG33421",
    "Carrot": "CR16027",
    "Cucumber": "CU48290",
    "Milk": "ML12345",
    "Bread": "BR67890",
    "Eggs": "EG54321",
    "Rice": "RC98765",
    # ... additional mappings
}

Reverse barcode lookup

You can look up a product by its barcode:
def get_product_name_from_barcode(barcode: str, db: Session = None) -> str:
    """
    Retrieves the product name from a given barcode.
    """
    product = db.query(Product).filter(Product.barcode == barcode).first()
    
    if product:
        return product.name
    else:
        return None

Image processing with OpenCV

The system uses OpenCV for robust image processing:
import cv2
import numpy as np

# Convert image bytes to numpy array
np_arr = np.frombuffer(image_bytes, np.uint8)

# Decode image
img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)

# Initialize QR detector
detector = cv2.QRCodeDetector()

# Detect and decode
data, bbox, _ = detector.detectAndDecode(img)
OpenCV’s QRCodeDetector can handle various QR code formats and orientations automatically.

Supported image formats

The API accepts the following image formats:
  • JPEG (.jpg, .jpeg)
  • PNG (.png)
  • BMP (.bmp)
  • TIFF (.tiff)
All uploaded images are temporarily stored in the uploads/ directory for processing.

Integration with product detection

QR code scanning can be combined with AI-based product detection for a complete inventory management workflow:
  1. Scan QR code to identify product
  2. Use YOLO detection to verify product visually
  3. Automatically add to user inventory
  4. Track expiry dates and receive notifications
Make sure the uploads/ directory exists and has proper write permissions before using the QR scanning feature.

Error handling

The system handles common scanning errors:
  • No QR code detected: Returns error message with guidance
  • Invalid image format: OpenCV will fail to decode the image
  • Corrupted file: Returns appropriate error response
if bbox is not None and data:
    return {"message": "QR Scanned successfully", "data": data}
else:
    return {"error": "No QR code found in the image"}

Build docs developers (and LLMs) love