|
1 | 1 | import cv2 as cv |
2 | 2 |
|
3 | | -# Read the image in grayscale |
4 | | -img = cv.imread(r"..\img\hand1.jpg", cv.IMREAD_GRAYSCALE) |
| 3 | +# Read the image |
| 4 | +img = cv.imread(r"..\img\hand1.jpg") |
5 | 5 |
|
6 | | -# Apply thresholding to create a binary image |
7 | | -_, thresholded = cv.threshold(img, 70, 255, cv.THRESH_BINARY) |
| 6 | +# Check if image loaded |
| 7 | +if img is None: |
| 8 | + print("Error: Image not found") |
| 9 | + exit() |
8 | 10 |
|
9 | | -# Find contours in the binary image |
10 | | -contours, _ = cv.findContours(thresholded.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) |
| 11 | +# Convert to grayscale |
| 12 | +gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) |
11 | 13 |
|
12 | | -# Convex Hull for each contour |
13 | | -convex_hulls = [cv.convexHull(contour) for contour in contours] |
| 14 | +# Apply Gaussian Blur to remove noise |
| 15 | +blur = cv.GaussianBlur(gray, (5, 5), 0) |
14 | 16 |
|
15 | | -# Draw contours and convex hulls on the original image |
16 | | -original_with_contours = cv.drawContours(img.copy(), contours, -1, (0, 0, 0), 2) |
17 | | -original_with_convex_hulls = cv.drawContours(img.copy(), convex_hulls, -1, (0, 0, 0), 2) |
| 17 | +# Apply Otsu Thresholding (automatic) |
| 18 | +_, thresh = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU) |
18 | 19 |
|
19 | | -# Display the images |
20 | | -cv.imshow("Original Image", img) |
21 | | -cv.imshow("Thresholded Image", thresholded) |
22 | | -cv.imshow("Contours", original_with_contours) |
23 | | -cv.imshow("Convex Hulls", original_with_convex_hulls) |
| 20 | +# Find contours |
| 21 | +contours, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) |
24 | 22 |
|
25 | | -# Wait for a key press and close windows |
| 23 | +# Get largest contour (assumed as hand) |
| 24 | +largest_contour = max(contours, key=cv.contourArea) |
| 25 | + |
| 26 | +# Convex Hull |
| 27 | +hull = cv.convexHull(largest_contour) |
| 28 | + |
| 29 | +# Create copies for drawing |
| 30 | +contour_img = img.copy() |
| 31 | +hull_img = img.copy() |
| 32 | + |
| 33 | +# Draw largest contour (Green) |
| 34 | +cv.drawContours(contour_img, [largest_contour], -1, (0, 255, 0), 2) |
| 35 | + |
| 36 | +# Draw convex hull (Blue) |
| 37 | +cv.drawContours(hull_img, [hull], -1, (255, 0, 0), 2) |
| 38 | + |
| 39 | +# Show images |
| 40 | +cv.imshow("Original", img) |
| 41 | +cv.imshow("Threshold", thresh) |
| 42 | +cv.imshow("Largest Contour", contour_img) |
| 43 | +cv.imshow("Convex Hull", hull_img) |
| 44 | + |
| 45 | +# Wait & close |
26 | 46 | cv.waitKey(0) |
27 | 47 | cv.destroyAllWindows() |
0 commit comments