-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataCollection.py
More file actions
85 lines (61 loc) · 1.84 KB
/
DataCollection.py
File metadata and controls
85 lines (61 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import time
import cv2
import numpy as np
import math
import os
from cvzone.HandTrackingModule import HandDetector
# Create folder if not exists
folder = ("Data/L"
)
os.makedirs(folder, exist_ok=True)
# Initialize camera
cap = cv2.VideoCapture(0)
# Initialize hand detector
detector = HandDetector(maxHands=1)
counter = 0
offset = 20
imgSize = 300
while True:
success, img = cap.read()
if not success:
break
hands, img = detector.findHands(img)
imgWhite = np.ones((imgSize, imgSize, 3), np.uint8) * 255
if hands:
hand = hands[0]
x, y, w, h = hand['bbox']
# SAFE cropping (avoid negative index crash)
x1 = max(0, x - offset)
y1 = max(0, y - offset)
x2 = x + w + offset
y2 = y + h + offset
imgCrop = img[y1:y2, x1:x2]
if imgCrop.size != 0:
aspectRatio = h / w
if aspectRatio > 1:
k = imgSize / h
wCal = math.ceil(k * w)
imgResize = cv2.resize(imgCrop, (wCal, imgSize))
wGap = math.ceil((imgSize - wCal) / 2)
imgWhite[:, wGap:wCal + wGap] = imgResize
else:
k = imgSize / w
hCal = math.ceil(k * h)
imgResize = cv2.resize(imgCrop, (imgSize, hCal))
hGap = math.ceil((imgSize - hCal) / 2)
imgWhite[hGap:hCal + hGap, :] = imgResize
cv2.imshow("ImageCrop", imgCrop)
cv2.imshow("ImageWhite", imgWhite)
cv2.imshow("Image", img)
key = cv2.waitKey(1)
# SAVE IMAGE
if key == ord("s") and hands:
counter += 1
filename = f"{folder}/Image_{time.time()}.jpg"
cv2.imwrite(filename, imgWhite)
print("Saved:", counter)
# EXIT
if key == 27: # ESC key
break
cap.release()
cv2.destroyAllWindows()