File size: 1,048 Bytes
1166534
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c888cb4
 
 
1166534
 
 
 
 
 
 
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
import cv2
import numpy as np
import gradio as gr
from PIL import Image

def detect_objects(input_image):
    # Convert Gradio input image (PIL Image) to a NumPy array
    input_image = np.array(input_image)

    # Perform object detection on the input image
    gray = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (11, 11), 0)
    canny = cv2.Canny(blur, 30, 150, 3)
    dilated = cv2.dilate(canny, (1, 1), iterations=0)
    (cnt, hierarchy) = cv2.findContours(
        dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    rgb = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB)
    cv2.drawContours(rgb, cnt, -1, (0, 255, 0), 2)

    # Convert the image back to PIL format
    output_image = Image.fromarray(rgb)

    return output_image, f"Objects in the image: {len(cnt)}"

# Define a Gradio interface
input_image = gr.Image()
output_image = gr.Image()
output_text = gr.Text()

gr.Interface(
    fn=detect_objects,
    inputs=input_image,
    outputs=[output_image, output_text],
    live=True,
).launch()