Build an interactive CLI or Streamlit tool that allows users to generate/draw basic geometric shapes, apply contour detection with polygon approximation, and view the annotated shapes with labels using OpenCV.
- Ask user:
"Which shape would you like to draw and detect?"
Choose one of the following options:
-
1. Triangle -
2. Square -
3. Rectangle -
4. Pentagon -
5. Hexagon -
6. Circle -
7. Ellipse -
8. Star (5-point) -
9. Regular Polygon (custom N sides)
-
Allow the user to choose:
-
Canvas size (e.g., 256β800 px).
-
Shape-specific parameters:
-
Circle β
radius -
Ellipse β
axis_x,axis_y,rotation -
Rectangle/Square β
width,height,rotation -
Regular Polygon β
sides,radius,rotation -
Star β
outer radius,inner radius,rotation
-
-
-
Generate the binary image with the selected shape drawn in white.
-
Preprocess with:
_, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
-
Find contours:
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
-
Approximate polygon curves:
epsilon = 0.015 * cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, epsilon, True)
-
Classify shape based on:
-
Number of corners (
len(approx)). -
Aspect ratio (square vs rectangle).
-
Circularity & convexity (circle/ellipse vs irregular polygons).
-
-
Annotate results with contours + labels:
cv2.drawContours(annotated, [approx], 0, (0, 255, 0), 2) cv2.putText(annotated, shape_name, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)
-
Display both original drawn shape and detected shape with contours side by side.
-
Offer Download option for results.
-
3 corners β Triangle
-
4 corners β Square or Rectangle (check aspect ratio)
-
5 corners β Pentagon
-
6 corners β Hexagon
-
>6 corners:
-
High circularity β Circle
-
Medium circularity β Ellipse
-
Concave polygon β βConcave Polygon (n)β
-
Else β βPolygon (n sides)β
-
π Note: circularity = (4Ο Γ area) / (perimeterΒ²)
-
Left column: Original drawn grayscale shape.
-
Right column: Annotated image with contours + detected label.