File size: 1,643 Bytes
fd7a708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cebced8
 
 
 
 
fd7a708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from pathlib import Path

import gradio as gr
from ultralytics import YOLO
from PIL import Image


# Load YOLOv8n model
MODEL = YOLO('weights/best.pt')
IMAGES_PATH = Path("images/")

INF_PARAMETERS = {
    "imgsz": 640,  # image size
    "conf": 0.8,   # confidence threshold
    "max_det": 1   # maximum number of detections
}

EXAMPLES = [path for path in IMAGES_PATH.iterdir()]


# Function to detect objects and crop the image
def detect_and_crop(image: Image.Image) -> Image.Image:
    # Perform object detection
    results = MODEL.predict(image,**INF_PARAMETERS)
    result = results[0]
    for box in result.boxes.xyxy.cpu().numpy():
        if len(box) > 0: 
            cropped_image = image.crop(box=box)
            return cropped_image
        else:
            return image


# Gradio UI
title = "Crop-Detection"
description = """## πŸ‹β€πŸŸ© Automatically crop product pictures! πŸ‹β€πŸŸ©
When contributors use the mobile app, they are asked to take pictures of the product, then to crop it. 
To assist users during the process, we create a crop-detection model desin to detect the product edges.

We fine-tuned Yolov8n on images extracted from the Open Food Facts database.
Check the [model repo page](https://huggingface.co/openfoodfacts/crop-detection) for more information.
"""

# Gradio Interface
demo = gr.Interface(
    fn=detect_and_crop,               
    inputs=gr.Image(type="pil", width=300),    
    outputs=gr.Image(type="pil", width=300),
    title=title,
    description=description,
    allow_flagging="never",
    examples=EXAMPLES
)


# Launch the Gradio app
if __name__ == "__main__":
    demo.launch()