Skip to content

Commit dddd038

Browse files
Create virtualpainter.py
1 parent 5b67465 commit dddd038

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
2+
#### File: `virtual_painter.py`
3+
```python
4+
import cv2
5+
import numpy as np
6+
7+
# Set up the color ranges for detection (e.g., blue pen)
8+
lower_blue = np.array([100, 150, 0])
9+
upper_blue = np.array([140, 255, 255])
10+
11+
# Initialize a blank canvas to draw on
12+
canvas = np.zeros((480, 640, 3), dtype="uint8")
13+
14+
# Start video capture
15+
cap = cv2.VideoCapture(0)
16+
17+
while True:
18+
ret, frame = cap.read()
19+
if not ret:
20+
break
21+
22+
# Convert to HSV color space for color detection
23+
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
24+
25+
# Create a mask for detecting the blue color
26+
mask = cv2.inRange(hsv, lower_blue, upper_blue)
27+
28+
# Find contours of the detected blue object
29+
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
30+
31+
if contours:
32+
# Get the largest contour (assuming it's the pen)
33+
max_contour = max(contours, key=cv2.contourArea)
34+
35+
# Get the center of the contour (i.e., the tip of the pen)
36+
(x, y), radius = cv2.minEnclosingCircle(max_contour)
37+
center = (int(x), int(y))
38+
39+
# Draw on the canvas at the detected position
40+
cv2.circle(canvas, center, 5, (255, 0, 0), -1)
41+
42+
# Merge the original frame with the canvas
43+
combined = cv2.add(frame, canvas)
44+
45+
# Display the result
46+
cv2.imshow('Virtual Painter', combined)
47+
48+
if cv2.waitKey(1) & 0xFF == ord('q'):
49+
break
50+
51+
cap.release()
52+
cv2.destroyAllWindows()

0 commit comments

Comments
 (0)