Skip to content

Commit eed6458

Browse files
Refactor gesture control for image loading and processing
Updated image processing steps to include error checking and improved contour detection.
1 parent 89f8daa commit eed6458

File tree

1 file changed

+37
-17
lines changed

1 file changed

+37
-17
lines changed
Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,47 @@
11
import cv2 as cv
22

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")
55

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()
810

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)
1113

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)
1416

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)
1819

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)
2422

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
2646
cv.waitKey(0)
2747
cv.destroyAllWindows()

0 commit comments

Comments
 (0)