datafreak's picture
main files
5d8c095 verified
import gradio as gr
import cv2
import numpy as np
# Function to process the image and extract contours
def extract_contours(image, min_contour_area=100):
# Convert the uploaded image from RGB to BGR format for OpenCV processing
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# Step 1: Convert to grayscale
gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
# Step 2: Apply Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Step 3: Apply Canny edge detection with low thresholds for finer edges
edges = cv2.Canny(blurred, 30, 100) # Adjust thresholds as needed
# Step 4: Apply morphological operations to refine edges
kernel = np.ones((3, 3), np.uint8)
edges_dilated = cv2.dilate(edges, kernel, iterations=1) # Dilation to emphasize edges
edges_eroded = cv2.erode(edges_dilated, kernel, iterations=1) # Erosion to refine
# Step 5: Find contours
contours, _ = cv2.findContours(edges_eroded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Step 6: Create a blank white background
white_background = np.ones_like(image_bgr) * 255 # White background
# Step 7: Draw contours on the white background, excluding small contours
for contour in contours:
if cv2.contourArea(contour) > min_contour_area:
cv2.drawContours(white_background, [contour], -1, (0, 0, 0), thickness=1) # Thinner lines
# Convert the result back to RGB for displaying
result_rgb = cv2.cvtColor(white_background, cv2.COLOR_BGR2RGB)
return result_rgb
# Gradio interface
interface = gr.Interface(
fn=extract_contours,
inputs=[
gr.Image(type="numpy", label="Upload Image"),
gr.Slider(50, 500, step=10, value=100, label="Minimum Contour Area") # Use 'value' instead of 'default'
],
outputs=gr.Image(type="numpy", label="Processed Image"),
title="Edge Detection and Contour Extraction",
description="Upload an image to extract contours, excluding small areas like text labels. Adjust the minimum contour area using the slider."
)
# Launch the Gradio app
interface.launch()