Machine Learning courses with 110+ Real-time projects Start Now!!
#Import the necessary modules
import pyautogui
import numpy as np
import cv2
import math
# Initialize the video capture
video_capture = cv2.VideoCapture(0)
while video_capture.isOpened():
# Captures the frames of the camera
ret, frame = video_capture.read()
# Get hand data from the rectangular window
cv2.rectangle(frame, (100, 100), (300, 300), (0, 255, 0), 0)
cv2.crop_image = frame[100:300, 100:300]
# Appling Blur
blurred_image = cv2.GaussianBlur(cv2.crop_image, (3, 3), 0)
# Converting color-space from BGR to HSV
hsv_image = cv2.cvtColor(blurred_image, cv2.COLOR_BGR2HSV)
# It creates the binary image, where white will be our skin color and others will be black
fg_mask = cv2.inRange(hsv_image, np.array([2, 0, 0]), np.array([20, 255, 255]))
# Kernel for morphological transformations
kernel = np.ones((5, 5))
# Used to filter out the background noise
dilation = cv2.dilate(fg_mask, kernel, iterations=1)
erosion = cv2.erode(dilation, kernel, iterations=1)
# Apply thresholding and blur to create a binary mask
filtered = cv2.GaussianBlur(erosion, (3, 3), 0)
ret, thresh = cv2.threshold(filtered, 127, 255, 0)
# Find contours in the edge-detected image
contours, hierachy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
try:
# Find contours with maximum area
contour = max(contours, key=lambda x: cv2.contourArea(x))
# Draw bounding boxes around the detected objects
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(cv2.crop_image, (x, y), (x + w, y + h), (0, 0, 255), 0)
hull = cv2.convexHull(contour)
drawing = np.zeros(cv2.crop_image.shape, np.uint8)
cv2.drawContours(drawing, [contour], -1, (0, 255, 0), 0)
cv2.drawContours(drawing, [hull], -1, (0, 0, 255), 0)
hull = cv2.convexHull(contour, returnPoints=False)
defects = cv2.convexityDefects(contour, hull)
count_defects = 0
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(contour[s][0])
end = tuple(contour[e][0])
far = tuple(contour[f][0])
a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)
b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)
c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)
angle = (math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 180) / 3.14
if angle <= 90:
count_defects += 1
cv2.circle(cv2.crop_image, far, 1, [0, 0, 255], -1)
cv2.line(cv2.crop_image, start, end, [0, 255, 0], 2)
# If the condition matched press space button
if count_defects >= 4:
pyautogui.press('space')
cv2.putText(frame, "JUMP", (115, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, 2, 2)
except:
pass
# Assign the title on the window
cv2.imshow("Dataflair Dino Game", frame)
# If q button is pressed, shut the camera
if cv2.waitKey(1) == ord('q'):
break
# Release the camera and close the window
video_capture.release()
cv2.destroyAllWindows()
