MediaPipe
hand-tracking
virtual-keyboard
opencv
gesture-recognition
computer-vision
human-computer-interaction
Instructions to use Noor-Khan/touchless-virtual-keyboard with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MediaPipe
How to use Noor-Khan/touchless-virtual-keyboard with MediaPipe:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Download virtual_keyboard.py from Noor-Khan/touchless-virtual-keyboard: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/Noor-Khan/touchless-virtual-keyboard/resolve/main/virtual_keyboard.py
- Command line
-
hf download hf://Noor-Khan/touchless-virtual-keyboard/virtual_keyboard.py
-
curl -L -o virtual_keyboard.py https://huggingface.co/Noor-Khan/touchless-virtual-keyboard/resolve/main/virtual_keyboard.py
12.4 kB
| """Touchless virtual keyboard — reusable module. | |
| Refactored from Noorullah Zamindar's ``main.py`` (webcam app) in | |
| NoorullahZamindar-007/touchless-virtual-keyboard. The keyboard layout, | |
| key behaviour and press state machine are copied verbatim from that app; | |
| this module just makes them callable without a webcam so they can be | |
| tested and reused. | |
| Two ways to use it: | |
| 1. Headless / tests — drive :class:`KeyboardEngine` with fingertip | |
| coordinates (e.g. from :func:`detect_hands` on a photo) and read | |
| ``engine.final_text``. | |
| 2. Webcam app — run the original ``main.py`` next to this file. | |
| Hand tracking uses MediaPipe's pre-trained HandLandmarker model | |
| (``hand_landmarker.task``, shipped in this repo — Google's model, not | |
| trained by Noorullah). No trained weights of his own exist here: the | |
| "model" is his keyboard logic plus that pre-trained hand tracker. | |
| """ | |
| import math | |
| import os | |
| # --- constants copied from main.py -------------------------------------- | |
| FRAME_WIDTH = 1280 | |
| FRAME_HEIGHT = 720 | |
| PINCH_DISTANCE = 45 | |
| CLICK_COOLDOWN = 0.55 | |
| HOVER_FRAMES_REQUIRED = 6 | |
| MAX_TEXT_LENGTH = 1000 | |
| KEY_ROWS = [ | |
| ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "BKSP"], | |
| ["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "ENTER"], | |
| ["SHIFT", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"], | |
| ["SPACE", "CLEAR"], | |
| ] | |
| KEY_SIZES = { | |
| "BKSP": (180, 85), | |
| "ENTER": (180, 85), | |
| "SHIFT": (180, 85), | |
| "SPACE": (585, 85), | |
| "CLEAR": (185, 85), | |
| } | |
| # MediaPipe hand-landmark indices used by the keyboard. | |
| INDEX_FINGER_TIP = 8 | |
| THUMB_TIP = 4 | |
| DEFAULT_MODEL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), | |
| "hand_landmarker.task") | |
| # --- geometry / key logic (verbatim from main.py) ------------------------ | |
| class Button: | |
| def __init__(self, pos, text, size=(85, 85)): | |
| self.pos = pos | |
| self.text = text | |
| self.size = size | |
| def contains(self, point): | |
| x, y = self.pos | |
| w, h = self.size | |
| return x < point[0] < x + w and y < point[1] < y + h | |
| def build_buttons(): | |
| buttons = [] | |
| for row_index, row in enumerate(KEY_ROWS): | |
| x = 50 | |
| y = 50 + row_index * 100 | |
| for key in row: | |
| size = KEY_SIZES.get(key, (85, 85)) | |
| buttons.append(Button((x, y), key, size)) | |
| x += size[0] + 15 | |
| return buttons | |
| def key_label(key, uppercase): | |
| if len(key) == 1 and key.isalpha(): | |
| return key.upper() if uppercase else key.lower() | |
| return key | |
| def apply_key(final_text, key, uppercase): | |
| if key == "BKSP": | |
| return final_text[:-1], uppercase | |
| if key == "SPACE": | |
| return (final_text + " ")[-MAX_TEXT_LENGTH:], uppercase | |
| if key == "ENTER": | |
| return (final_text + "\n")[-MAX_TEXT_LENGTH:], uppercase | |
| if key == "CLEAR": | |
| return "", uppercase | |
| if key == "SHIFT": | |
| return final_text, not uppercase | |
| if len(key) == 1 and key.isalpha(): | |
| key = key.upper() if uppercase else key.lower() | |
| return (final_text + key)[-MAX_TEXT_LENGTH:], uppercase | |
| def visible_text(final_text): | |
| text = final_text.replace("\n", " ") | |
| return ("..." + text[-32:]) if len(text) > 35 else text | |
| def find_hovered_button(buttons, index_tip): | |
| for button in buttons: | |
| if button.contains(index_tip): | |
| return button | |
| return None | |
| def fingertip_distance(point_a, point_b): | |
| return math.hypot(point_a[0] - point_b[0], point_a[1] - point_b[1]) | |
| def landmark_xy(lm_list, index, img_shape): | |
| y_size, x_size = img_shape[:2] | |
| x, y = lm_list[index][:2] | |
| if 0 <= x <= 1 and 0 <= y <= 1: | |
| return int(x * x_size), int(y * y_size) | |
| return int(x), int(y) | |
| # --- press state machine (the per-frame logic of main.py's loop) --------- | |
| class KeyboardEngine: | |
| """Drives the keyboard from fingertip positions, no camera needed. | |
| ``step(index_tip, thumb_tip, now)`` mirrors one iteration of the | |
| ``while`` loop in ``main.py``: hover the index fingertip over a key, | |
| hold it there for ``HOVER_FRAMES_REQUIRED`` frames, then pinch thumb | |
| and index finger together (distance < ``PINCH_DISTANCE``) to press. | |
| Pass ``index_tip=None`` (and ``thumb_tip=None``) for a frame with no | |
| hand visible. ``now`` is a timestamp in seconds (e.g. ``time.time()``). | |
| """ | |
| def __init__(self, pinch_distance=PINCH_DISTANCE, | |
| click_cooldown=CLICK_COOLDOWN, | |
| hover_frames_required=HOVER_FRAMES_REQUIRED): | |
| self.buttons = build_buttons() | |
| self.pinch_distance = pinch_distance | |
| self.click_cooldown = click_cooldown | |
| self.hover_frames_required = hover_frames_required | |
| self.final_text = "" | |
| self.uppercase = True | |
| self.hover_key = None | |
| self.hover_frames = 0 | |
| self.pressed_key = None | |
| self.last_press_time = 0.0 | |
| def key_center(self, key): | |
| """Pixel centre of a key, e.g. ``engine.key_center("H")``.""" | |
| for button in self.buttons: | |
| if button.text == key: | |
| x, y = button.pos | |
| w, h = button.size | |
| return (x + w // 2, y + h // 2) | |
| raise KeyError(key) | |
| def step(self, index_tip, thumb_tip, now): | |
| selected_button = None | |
| selected_key = None | |
| pinched = False | |
| pinch_distance = None | |
| if index_tip is not None: | |
| selected_button = find_hovered_button(self.buttons, index_tip) | |
| if selected_button: | |
| selected_key = selected_button.text | |
| if selected_key == self.hover_key: | |
| self.hover_frames += 1 | |
| else: | |
| self.hover_key = selected_key | |
| self.hover_frames = 1 | |
| if thumb_tip is not None: | |
| pinch_distance = fingertip_distance(thumb_tip, index_tip) | |
| pinched = pinch_distance < self.pinch_distance | |
| else: | |
| self.hover_key = None | |
| self.hover_frames = 0 | |
| self.pressed_key = None | |
| else: | |
| self.hover_key = None | |
| self.hover_frames = 0 | |
| self.pressed_key = None | |
| if not pinched: | |
| self.pressed_key = None | |
| cooldown_left = max(0, self.click_cooldown - (now - self.last_press_time)) | |
| can_type = ( | |
| selected_button is not None | |
| and pinched | |
| and self.hover_frames >= self.hover_frames_required | |
| and cooldown_left == 0 | |
| and self.pressed_key is None | |
| ) | |
| pressed = None | |
| if can_type: | |
| self.final_text, self.uppercase = apply_key( | |
| self.final_text, selected_key, self.uppercase) | |
| self.pressed_key = selected_key | |
| self.last_press_time = now | |
| cooldown_left = self.click_cooldown | |
| pressed = selected_key | |
| return { | |
| "selected_key": selected_key, | |
| "hover_frames": self.hover_frames, | |
| "pinched": pinched, | |
| "pinch_distance": pinch_distance, | |
| "cooldown_left": cooldown_left, | |
| "pressed_key": pressed, | |
| "text": self.final_text, | |
| } | |
| # --- hand detection (MediaPipe HandLandmarker, headless) ----------------- | |
| class HandDetector: | |
| """HandLandmarker wrapper that loads the model once. | |
| Use as a context manager (``with HandDetector(...) as d:``) or call | |
| :meth:`close` when done. Creating the landmarker takes a few seconds; | |
| each :meth:`detect` call on a 960x720 photo takes well under a second. | |
| """ | |
| def __init__(self, model_path=DEFAULT_MODEL_PATH, num_hands=2, | |
| min_detection_confidence=0.5): | |
| if not os.path.exists(model_path): | |
| raise FileNotFoundError( | |
| f"hand landmark model not found: {model_path}") | |
| import mediapipe as mp | |
| from mediapipe.tasks import python as mp_python | |
| from mediapipe.tasks.python import vision | |
| self._mp = mp | |
| options = vision.HandLandmarkerOptions( | |
| base_options=mp_python.BaseOptions(model_asset_path=model_path), | |
| running_mode=vision.RunningMode.IMAGE, | |
| num_hands=num_hands, | |
| min_hand_detection_confidence=min_detection_confidence, | |
| ) | |
| self._landmarker = vision.HandLandmarker.create_from_options(options) | |
| def detect(self, image_bgr): | |
| """Detect hands in a BGR image (as read by ``cv2.imread``). | |
| Returns a list of ``{"landmarks": [(x, y, z), ...] * 21, | |
| "handedness": "Left"/"Right", "score": float}`` with landmarks | |
| in normalised 0-1 coordinates. | |
| """ | |
| image = self._mp.Image( | |
| image_format=self._mp.ImageFormat.SRGB, data=image_bgr[:, :, ::-1]) | |
| result = self._landmarker.detect(image) | |
| hands = [] | |
| for landmarks, handedness in zip(result.hand_landmarks, result.handedness): | |
| hands.append({ | |
| "landmarks": [(lm.x, lm.y, lm.z) for lm in landmarks], | |
| "handedness": handedness[0].category_name, | |
| "score": float(handedness[0].score), | |
| }) | |
| return hands | |
| def close(self): | |
| self._landmarker.close() | |
| def __enter__(self): | |
| return self | |
| def __exit__(self, *exc): | |
| self.close() | |
| def detect_hands(image_bgr, model_path=DEFAULT_MODEL_PATH, num_hands=2, | |
| min_detection_confidence=0.5): | |
| """Detect hands in a BGR image (as read by ``cv2.imread``). | |
| Convenience wrapper: loads the model, detects once, closes it. For | |
| repeated images use :class:`HandDetector` instead (model loads once). | |
| Returns the same list of dicts as :meth:`HandDetector.detect`. | |
| Raises ``FileNotFoundError`` if the model file is missing. Needs | |
| ``mediapipe`` installed; on Linux the MediaPipe native library also | |
| needs OpenGL ES (``libGLESv2``). | |
| """ | |
| with HandDetector(model_path, num_hands, min_detection_confidence) as detector: | |
| return detector.detect(image_bgr) | |
| def landmarks_to_lmlist(landmarks, img_shape): | |
| """Normalised landmarks -> cvzone-style pixel ``lmList`` (21 x [x, y, z]).""" | |
| height, width = img_shape[:2] | |
| return [[int(x * width), int(y * height), z] for (x, y, z) in landmarks] | |
| # --- rendering (plain OpenCV, mirrors main.py's draw_keyboard) ----------- | |
| def render_keyboard(uppercase=True, frame_width=FRAME_WIDTH, | |
| frame_height=FRAME_HEIGHT): | |
| """Render the keyboard layout to a BGR image (no camera needed).""" | |
| import cv2 | |
| import numpy as np | |
| img = np.full((frame_height, frame_width, 3), 255, dtype=np.uint8) | |
| for button in build_buttons(): | |
| x, y = button.pos | |
| w, h = button.size | |
| cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 0), cv2.FILLED) | |
| label = key_label(button.text, uppercase) | |
| font = cv2.FONT_HERSHEY_PLAIN | |
| scale = 3 | |
| thickness = 3 | |
| while scale > 0.8: | |
| (tw, th), baseline = cv2.getTextSize(label, font, scale, thickness) | |
| if tw <= w - 16: | |
| break | |
| scale -= 0.2 | |
| cv2.putText(img, label, (x + (w - tw) // 2, y + (h + th) // 2 - baseline), | |
| font, scale, (255, 255, 255), thickness) | |
| return img | |
| def _main(): | |
| import argparse | |
| import json | |
| parser = argparse.ArgumentParser(description="Touchless virtual keyboard") | |
| parser.add_argument("--image", help="photo to run hand detection on") | |
| parser.add_argument("--render", help="write a render of the keyboard to this PNG path") | |
| parser.add_argument("--model", default=DEFAULT_MODEL_PATH, | |
| help="path to hand_landmarker.task") | |
| args = parser.parse_args() | |
| if args.render: | |
| import cv2 | |
| cv2.imwrite(args.render, render_keyboard()) | |
| print(f"keyboard rendered to {args.render}") | |
| if args.image: | |
| import cv2 | |
| image = cv2.imread(args.image) | |
| if image is None: | |
| raise SystemExit(f"could not read image: {args.image}") | |
| hands = detect_hands(image, model_path=args.model) | |
| print(json.dumps([{"handedness": h["handedness"], | |
| "score": round(h["score"], 3), | |
| "landmarks": len(h["landmarks"])} for h in hands], | |
| indent=2)) | |
| if __name__ == "__main__": | |
| _main() | |