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
|
import cv2 from HandTrackingModule import HandDetector from PIL import Image,ImageDraw,ImageFont import numpy
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20): if (isinstance(img, numpy.ndarray)): img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) fontStyle = ImageFont.truetype( "font/simsun.ttc", textSize, encoding="utf-8") draw.text((left, top), text, textColor, font=fontStyle) # 转换回OpenCV格式 return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
class Main: def __init__(self): self.camera = cv2.VideoCapture(0,cv2.CAP_DSHOW) self.camera.set(3, 1280) self.camera.set(4, 720)
def Gesture_recognition(self): while True: self.detector = HandDetector() frame, img = self.camera.read() img = self.detector.findHands(img) lmList, bbox = self.detector.findPosition(img)
if lmList: x_1, y_1 = bbox["bbox"][0], bbox["bbox"][1] x1, x2, x3, x4, x5 = self.detector.fingersUp()
if (x2 == 1 and x3 == 1) and (x4 == 0 and x5 == 0 and x1 == 0): cv2.putText(img, "2_TWO", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3, (0, 0, 255), 3) elif (x2 == 1 and x3 == 1 and x4 == 1) and (x1 == 0 and x5 == 0): cv2.putText(img, "3_THREE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3, (0, 0, 255), 3) elif (x2 == 1 and x3 == 1 and x4 == 1 and x5 == 1) and (x1 == 0): cv2.putText(img, "4_FOUR", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3, (0, 0, 255), 3) elif x1 == 1 and x2 == 1 and x3 == 1 and x4 == 1 and x5 == 1: cv2.putText(img, "5_FIVE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3, (0, 0, 255), 3) elif x2 == 1 and (x1 == 0, x3 == 0, x4 == 0, x5 == 0): cv2.putText(img, "1_ONE", (x_1, y_1), cv2.FONT_HERSHEY_PLAIN, 3, (0, 0, 255), 3) elif x1 == 1 and (x2 == 0, x3 == 0, x4 == 0, x5 == 0): img = cv2ImgAddText(img,'杰哥觉得很赞',left = x_1,top=y_1,textColor=(255,0,0),textSize = 45)
cv2.imshow("camera", img) #if cv2.getWindowProperty('camera', cv2.WND_PROP_VISIBLE) < 1: # break cv2.waitKey(1) if cv2.waitKey(1) & 0xFF == ord("q"): break
if __name__ == '__main__': Solution = Main() Solution.Gesture_recognition()
|