import cv2
import numpy as np
import pygame
from pygame.locals import *
# 初始化Pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Handwriting with Finger")
# 设置画笔参数
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
brush_size = 5
brush_color = BLACK
drawing = False
# 创建一张空白画布
canvas = np.ones((480, 640, 3), dtype=np.uint8) * 255
# 定义绘制函数
def draw_on_canvas(pos):
pygame.draw.circle(canvas, brush_color, pos, brush_size)
# 开启摄像头
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 1)
frame = cv2.resize(frame, (640, 480))
# 手指移动检测
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
cnt = max(contours, key=cv2.contourArea)
M = cv2.moments(cnt)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
if 0 < cx < 640 and 0 < cy < 480:
draw_on_canvas((cx, cy))
# 显示画布
cv2.imshow("Canvas", canvas)
# 退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()