所以我的老板找我做一个相当雄心勃勃的项目,那就是将末端有屏幕的手臂驱动到用户脸部的高度。我这样做是利用 OpenCV 的面部识别库,在用户面部周围放置一个正方形,然后将“Y”值输出到终端。有了这个值,我将高低信号发送到微控制器,该微控制器控制步进电机,如果用户的高度在“范围内”,该步进电机会向上、向下或保持手臂。
我最初在程序中使用了 haar 级联,但发现它非常滞后。然后我切换到运行速度更快但不准确的 LBP 级联。我发现为了让程序不运行延迟,我需要对我的脚本进行多线程处理。
我是一名研发人员,通常从事电气工程、接线、分配等工作……我不会编程,所以能走到这一步真是个奇迹。我有下面的代码,任何帮助都将不胜感激,因为所有其他关于 Python 多线程的论坛都在我头上,因为我无法完全掌握 Python 的白话。
import cv2
import sys
import RPi.GPIO as GPIO
import time
from threading import Thread
#assigning GPIO to BCM instead of board
GPIO.setmode(GPIO.BCM)
#HIGH and LOW output pins to microcontroller
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
#Limit switch input buttons
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#cascade reference for facial detection
cascPath = "lbpcascade_frontalface.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
try:
while True: #Main loop
#assigning coordinates to variables
x = 0
y = 131
ret, frame = video_capture.read()
gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=25,
minSize=(50, 50)
)
#outputing facial sqaure position to terminal
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 100, 0), 1)
print (x,y,"---",w,h)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imshow('Video', frame)
#output 23 cannot continue further after DownMax is hit. Continues in other
direction until switch isn't engaged anymore
if GPIO.input(27):
print "Down endstop is hit"
y = 132
GPIO.output(23, 0)
GPIO.output(24, 1)
#output 24 cannot continue further after UpMax is hit. " "
if GPIO.input(17):
print "Up endstop is hit"
y =132
GPIO.output(23, 1)
GPIO.output(24, 0)
#If the face Y-value is less than 130, move motor up
if (y < 130):
print "Y is less than 130"
GPIO.output(23, 1)
GPIO.output(24, 0)
del y
#If the face Y-value is more than 170, move motor down
elif (y > 170):
print "Y is more than 170"
GPIO.output(23, 0)
GPIO.output(24, 1)
del y
#If a face is not found, default to 131 so motors don't move
else:
y = 131
print "y is in range"
GPIO.output(23, 1)
GPIO.output(24, 1)
finally:
GPIO.cleanup()
video_capture.release()
cv2.destroyAllWindows()
当限位开关被击中时,无论是一个,它都会在相反的方向向后移动以等待进一步的坐标或等到另一个用户出现在网络摄像头流中。
我只需要它是多线程的,任何评论或提示也非常感谢。
谢谢你的阅读。