-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCVtest.py
More file actions
304 lines (228 loc) · 9 KB
/
Copy pathCVtest.py
File metadata and controls
304 lines (228 loc) · 9 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#THIS CODE IS NOT MINE, I USED CTRL+C AND CTRL+V A LOT
#THIS WAS TO LEARN AND UNDERSTAND WHY THING DO OR DON'T WORK
#https://developers.google.com/mediapipe/solutions/vision/hand_landmarker/python#video
#https://developers.google.com/mediapipe/solutions/vision/hand_landmarker/index#models
'''
# Importing Libraries
import cv2
import mediapipe as mp
# Used to convert protobuf message to a dictionary.
from google.protobuf.json_format import MessageToDict
# Initializing the Model
mpHands = mp.solutions.hands
hands = mpHands.Hands(static_image_mode=False,model_complexity=1,min_detection_confidence=0.75,min_tracking_confidence=0.75, max_num_hands=2)
# Start capturing video from webcam
cap = cv2.VideoCapture(0)
while True:
# Read video frame by frame
success, img = cap.read()
# Flip the image(frame)
img = cv2.flip(img, 1)
# Convert BGR image to RGB image
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Process the RGB image
results = hands.process(imgRGB)
# If hands are present in image(frame)
if results.multi_hand_landmarks:
# Both Hands are present in image(frame)
if len(results.multi_handedness) == 2:
# Display 'Both Hands' on the image
cv2.putText(img, 'Both Hands', (250, 50),
cv2.FONT_HERSHEY_COMPLEX,
0.9, (0, 255, 0), 2)
# If any hand present
else:
for i in results.multi_handedness:
# Return whether it is Right or Left Hand
label = MessageToDict(i)['classification'][0]['label']
if label == 'Left':
# Display 'Left Hand' on
# left side of window
cv2.putText(img, label+' Hand',
(20, 50),
cv2.FONT_HERSHEY_COMPLEX,
0.9, (0, 255, 0), 2)
if label == 'Right':
# Display 'Left Hand'
# on left side of window
cv2.putText(img, label+' Hand', (460, 50),
cv2.FONT_HERSHEY_COMPLEX,
0.9, (0, 255, 0), 2)
# Display Video and when 'q'
# is entered, destroy the window
cv2.imshow('Image', img)
if cv2.waitKey(1) & 0xff == ord('q'):
break
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
import numpy as np
import cv2
import time
model_path = '/absolute/path/to/hand_landmarker.task'
BaseOptions = mp.tasks.BaseOptions
HandLandmarker = mp.tasks.vision.HandLandmarker
HandLandmarkerOptions = mp.tasks.vision.HandLandmarkerOptions
HandLandmarkerResult = mp.tasks.vision.HandLandmarkerResult
VisionRunningMode = mp.tasks.vision.RunningMode
# Load the frame rate of the video using OpenCV’s CV_CAP_PROP_FPS
# You’ll need it to calculate the timestamp for each frame.
#img.getfield(cv2.CAP_PROP_FPS)
# Loop through each frame in the video using VideoCapture#read()
# Convert the frame received from OpenCV to a MediaPipe’s Image object.
#mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img)
def print_result(result: HandLandmarkerResult, output_image: mp.Image, timestamp_ms: int):
print('hand landmarker result: {}'.format(result))
options = HandLandmarkerOptions(base_options=BaseOptions(model_asset_path='absolute/path/to/hand_landmarker.task'),running_mode=VisionRunningMode.LIVE_STREAM,result_callback=print_result)
with HandLandmarker.create_from_options(options) as landmarker:
cap = cv2.VideoCapture(0)
while True:
# Read video frame by frame
success, img = cap.read()
if not success:
break
cv2.imshow("img", img)
#frame = cap.get(cv2.CAP_PROP_FPS)
timestamp = int(round(time.time() * 1000))
frame_np = np.array(img)
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=frame_np)
landmarker.detect_async(mp_image, timestamp)
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
import cv2
import time
import numpy as np
from mediapipe import solutions
from mediapipe.framework.formats import landmark_pb2
MARGIN = 10 # pixels
FONT_SIZE = 1
FONT_THICKNESS = 1
HANDEDNESS_TEXT_COLOR = (88, 205, 54) # vibrant green
BaseOptions = mp.tasks.BaseOptions
HandLandmarker = mp.tasks.vision.HandLandmarker
HandLandmarkerOptions = mp.tasks.vision.HandLandmarkerOptions
HandLandmarkerResult = mp.tasks.vision.HandLandmarkerResult
VisionRunningMode = mp.tasks.vision.RunningMode
RESULT = None
# Create a hand landmarker instance with the live stream mode:
def print_result(result: mp.tasks.vision.HandLandmarkerResult, output_image: mp.Image, timestamp_ms: int):
# print(result)
global RESULT
RESULT = result
options = HandLandmarkerOptions(
base_options=BaseOptions(model_asset_path='absolute/path/to/hand_landmarker.task'),
running_mode=VisionRunningMode.LIVE_STREAM,
result_callback=print_result)
with HandLandmarker.create_from_options(options) as landmarker:
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
frame_np = np.array(frame)
timestamp = int(round(time.time() * 1000))
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=frame_np)
frame = mp_image.numpy_view()
landmarker.detect_async(mp_image, timestamp)
if type(RESULT) is not type(None):
hand_landmarks_list = RESULT.hand_landmarks
for idx in range(len(hand_landmarks_list)):
hand_landmarks = hand_landmarks_list[idx]
# Draw the hand landmarks.
hand_landmarks_proto = landmark_pb2.NormalizedLandmarkList()
hand_landmarks_proto.landmark.extend([
landmark_pb2.NormalizedLandmark(x=landmark.x, y=landmark.y, z=landmark.z) for landmark in
hand_landmarks
])
solutions.drawing_utils.draw_landmarks(
frame,
hand_landmarks_proto,
solutions.hands.HAND_CONNECTIONS,
solutions.drawing_styles.get_default_hand_landmarks_style(),
solutions.drawing_styles.get_default_hand_connections_style(),True)
else:
print('else')
cv2.imshow('Frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
import mediapipe as mp
BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
FaceDetectorResult = mp.tasks.vision.FaceDetectorResult
VisionRunningMode = mp.tasks.vision.RunningMode
# Create a face detector instance with the live stream mode:
def print_result(result: FaceDetectorResult, output_image: mp.Image, timestamp_ms: int):
print('face detector result: {}'.format(result))
options = FaceDetectorOptions(
base_options=BaseOptions(model_asset_path='/path/to/model.task'),
running_mode=VisionRunningMode.LIVE_STREAM,
result_callback=print_result)
with FaceDetector.create_from_options(options) as detector:
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
detector.detect_async(mp_image, frame_timestamp_ms)
'''
#https://www.geeksforgeeks.org/face-and-hand-landmarks-detection-using-python-mediapipe-opencv/
# Import Libraries
import cv2
import time
import mediapipe as mp
# Grabbing the Holistic Model from Mediapipe and
# Initializing the Model
mp_holistic = mp.solutions.holistic
holistic_model = mp_holistic.Holistic(
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
# Initializing the drawing utils for drawing the facial landmarks on image
mp_drawing = mp.solutions.drawing_utils
# (0) in VideoCapture is used to connect to your computer's default camera
capture = cv2.VideoCapture(0)
# Initializing current time and precious time for calcu lating the FPS
previousTime = 0
currentTime = 0
while capture.isOpened():
# capture frame by frame
ret, frame = capture.read()
# resizing the frame for better view
frame = cv2.resize(frame, (800, 600))
# Converting the from BGR to RGB
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Making predictions using holistic model
# To improve performance, optionally mark the image as not writeable to
# pass by reference.
image.flags.writeable = False
results = holistic_model.process(image)
image.flags.writeable = True
# Converting back the RGB image to BGR
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# Drawing Right hand Land Marks
mp_drawing.draw_landmarks(
image,
results.right_hand_landmarks,
mp_holistic.HAND_CONNECTIONS
)
# Drawing Left hand Land Marks
mp_drawing.draw_landmarks(
image,
results.left_hand_landmarks,
mp_holistic.HAND_CONNECTIONS
)
# Calculating the FPS
currentTime = time.time()
fps = 1 / (currentTime-previousTime)
previousTime = currentTime
# Displaying FPS on the image
cv2.putText(image, str(int(fps))+" FPS", (10, 70), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
# Display the resulting image
cv2.imshow("Hand Landmarks", image)
# Enter key 'q' to break the loop
if cv2.waitKey(5) & 0xFF == ord('q'):
break
# When all the process is done
# Release the capture and destroy all windows
capture.release()
cv2.destroyAllWindows()