nao机器人通过opencv走黑线,并识别到绿色方块蹲下抓取后继续巡线的python2代码
时间: 2024-02-13 10:02:10 浏览: 121
以下是一个 Python 2 代码,使用 OpenCV 库和 NAOqi SDK,实现了 NAO 机器人通过摄像头识别黑色线条并跟随它,当识别到绿色方块时停下并蹲下抓取,然后继续跟随黑色线条:
```python
import cv2
from naoqi import ALProxy
# NAOqi SDK连接设置
robotIp = "NAO_IP"
port = 9559
videoClient = ALProxy("ALVideoDevice", robotIp, port)
motion = ALProxy("ALMotion", robotIp, port)
# 摄像头设置
nameId = videoClient.subscribeCamera("python_client", 0, 2, 11, 5)
width = 640
height = 480
fps = 10
# 黑色线条识别和跟随
following = True
while following:
# 获取图像
img = videoClient.getImageRemote(nameId)
img = np.fromstring(img[6], dtype=np.uint8)
img = img.reshape((height, width, 3))
# 图像处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 找到最长的轮廓
maxContour = max(contours, key=cv2.contourArea)
moments = cv2.moments(maxContour)
# 计算中心点
if moments['m00'] != 0:
cx = int(moments['m10'] / moments['m00'])
cy = int(moments['m01'] / moments['m00'])
# 跟随线条
if cx > width / 2 + 50:
motion.post.moveTo(0.1, 0, 0)
elif cx < width / 2 - 50:
motion.post.moveTo(-0.1, 0, 0)
else:
motion.post.moveTo(0, 0, 0)
# 绿色方块识别和抓取
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_green = np.array([40, 50, 50])
upper_green = np.array([80, 255, 255])
mask = cv2.inRange(hsv, lower_green, upper_green)
_, greenContours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(greenContours) > 0:
motion.post.stopMove()
motion.post.goToPosture("Crouch", 1.0)
motion.post.openHand("RHand")
motion.post.closeHand("RHand")
motion.post.goToPosture("StandInit", 1.0)
following = True
# 摄像头和连接清理
videoClient.unsubscribe(nameId)
```
这个代码中,我们添加了一个 `following` 标志来控制是否跟随黑色线条。当机器人识别到绿色方块时,它会停下来,蹲下并抓取方块,然后站起来并重新开始跟随黑色线条。
阅读全文