這是在顔色識别的基礎上,通過顔色的位置的判斷,進而控制舵機的旋轉
基本原理就是這樣吧。。。。。
from __future__ import division
import time
import Adafruit_PCA9685
import cv2
import numpy as np
i = 3
pwm = Adafruit_PCA9685.PCA9685()
servo_min = 150
def set_servo_pulse(channel,pulse):
pulse_length = 1000000
pulse_length //= 60
pulse_length //= 4096
pulse *= 1000
pulse //= pulse_length
pwm.set_pwm(channel,0,pulse)
def set_servo_angle(channel,angle):
angle=4096*((angle*11)+500)/20000
pwm.set_pwm(channel,0,int(angle))
pwm.set_pwm_freq(50)
blue_lower = np.array([100,43,46])
blue_upper = np.array([124,255,255])
cap = cv2.VideoCapture(0)
cap.set(3,320)
cap.set(4,240)
def newGetDirection(x): #舵機角度的控制
global i
if i < 2:
i = 2
elif i > 180:
i = 180
if 0 < x < 130:
i = i +5
set_servo_angle(1,i)
elif 130 <= x < 220:
pass
else:
i = i -5
set_servo_angle(1,i)
while 1:
ret,frame = cap.read()
frame = cv2.GaussianBlur(frame,(5,5),0)
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv,blue_lower,blue_upper)
mask = cv2.erode(mask,None,iterations=2)
mask = cv2.GaussianBlur(mask,(3,3),0)
res = cv2.bitwise_and(frame,frame,mask=mask)
cnts = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
if len(cnts) > 0:
cnt = max(cnts,key=cv2.contourArea)
(x,y),radius = cv2.minEnclosingCircle(cnt)
cv2.circle(frame,(int(x),int(y)),int(radius),(255,0,255),2)
print(int(x))
newGetDirection(x)
else:
pass
cv2.imshow("frame",frame)
cv2.imshow("mask",mask)
cv2.imshow("res",res)
if cv2.waitKey(5) & 0xFF == 27:
break
def doSomething(x):
set_servo_angle(1,x)
cap.release()
cv2.destroyAllWindows()