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
| import cv2 import numpy as np import serial import time
degree = 90
e = 10
def distance(x1, y1, x2, y2): return np.sqrt(np.square(x1 - x2) + np.square(y1 - y2))
def postData(x, name, bpm): ser = serial.Serial(name, bpm) data = str(int(x)) print(f'data = {data}') if len(data) == 2: data = '0' + data elif len(data) == 1: data = '00' + data ser.write(data.encode('utf-8')) time.sleep(0.1) ser.close() pass
def getFace(videoStream): gary = cv2.cvtColor(videoStream, cv2.COLOR_RGB2GRAY)
cent_x = videoStream.shape[1] / 2 cent_y = videoStream.shape[0] / 2 dis = distance(cent_x, cent_y, 0, 0) back_x = cent_x back_y = cent_y
kernel = np.array([ [-1, 1, -1], [1, 1, 1], [-1, 1, -1] ]) gary = cv2.filter2D(gary, -1, kernel) preclass = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
faceRects = preclass.detectMultiScale(gary, scaleFactor=1.3, minNeighbors=3, minSize=(12, 12)) if len(faceRects) > 0: for faceRect in faceRects: x, y, w, h = faceRect if distance(x + w / 2, y + h / 2, cent_x, cent_y) < dis: dis = distance(x + w / 2, y + h / 2, cent_x, cent_y) back_x = x + w / 2 back_y = y + h / 2 pass cv2.rectangle(videoStream, (x, y), (x + w, y + h), (0, 255, 255), 4) pass pass return back_x - cent_x, back_y - cent_y
def getFooter(img): cent_x = img.shape[1] / 2 cent_y = img.shape[0] / 2 dis = distance(cent_x, cent_y, 0, 0) back_x = cent_x back_y = cent_y kernels = np.array([ [1, 0, 1], [0, -3, 0], [1, 0, 1] ]) gary_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) blur_img = cv2.filter2D(gary_img, -1, kernels) hog = cv2.HOGDescriptor() hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) (rects, weights) = hog.detectMultiScale(blur_img, winStride=(4, 4), padding=(8, 8), scale=0.9) print(rects) for (x, y, w, h) in rects: if distance(x + w / 2, y + h / 2, cent_x, cent_y) < dis: dis = distance(x + w / 2, y + h / 2, cent_x, cent_y) back_x = x + w / 2 back_y = y + h / 2 cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 4) pass return cent_x - back_x, cent_y - back_y
if __name__ == "__main__": video = cv2.VideoCapture(1) if video.isOpened(): lastime = 0 while True: ret, frame = video.read() if not ret: print("Video End!") break x, y = getFace(frame) print(f'x:{x}') cv2.imshow("Video", frame) if not -1 * e < x < e and abs(lastime - x) > e+2: if x> 0: degree = degree - e/2 else: degree = degree + e/2 if degree != 90: postData(degree, "COM11", 115200) pass else: lastime = x pass if cv2.waitKey(1) & 0xFF == ord('q'): break pass pass
|