Spaces:
Sleeping
Sleeping
import gradio as gr | |
import cv2 | |
from pyzbar.pyzbar import decode | |
from PIL import Image | |
import numpy as np | |
import io | |
import base64 | |
def scan_qr_code(image): | |
""" | |
Scan QR code from the uploaded image. | |
Args: | |
image: The uploaded image (can be PIL Image, numpy array, or file path) | |
Returns: | |
str: The decoded QR code data with a descriptive message. | |
""" | |
try: | |
if image is None: | |
return "No image provided" | |
# Convert to PIL Image if needed | |
if isinstance(image, np.ndarray): | |
image = Image.fromarray(image) | |
elif isinstance(image, str): | |
try: | |
if image.startswith('data:image'): | |
# Handle base64 encoded images | |
image_data = base64.b64decode(image.split(',')[1]) | |
image = Image.open(io.BytesIO(image_data)) | |
else: | |
# Handle file paths | |
image = Image.open(image) | |
except Exception as e: | |
return f"Error opening image: {str(e)}" | |
# Convert to OpenCV format | |
open_cv_image = np.array(image) | |
if len(open_cv_image.shape) == 3: # Color image | |
open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2BGR) | |
# Decode QR code | |
decoded_objects = decode(open_cv_image) | |
if decoded_objects: | |
for obj in decoded_objects: | |
decoded_data = obj.data.decode('utf-8') | |
return f"The code contains the following data: {decoded_data}" | |
return "No QR code found" | |
except Exception as e: | |
return f"Error processing image: {str(e)}" | |
# Define the Gradio interface | |
iface = gr.Interface( | |
fn=scan_qr_code, | |
inputs=gr.Image(label="Upload QR Code Image"), # Removed type parameter | |
outputs=gr.Textbox(label="Result"), | |
title="QR Code Scanner", | |
description="Upload an image containing a QR code to decode it.", | |
examples=[], # You can add example images here | |
cache_examples=False | |
) | |
# Launch the Gradio app | |
if __name__ == "__main__": | |
iface.launch(share=True) # Added share=True for public access | |