跳转到内容
中文(简体)

颜色传感器

颜色传感器朝向地面,所以它能告诉机器人哪里有坑洞、沼泽和通道。它其实是一个只有一个像素、朝下的摄像头。在入门机器人上,它的名字是 color,位于机器人前部,这样在车轮到达坑洞之前就能看到它。

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
colorSensor = robot.getDevice("color")
colorSensor.enable(timeStep)
while robot.step(timeStep) != -1:
image = colorSensor.getImage() # A single pixel
r = colorSensor.imageGetRed(image, 1, 0, 0)
g = colorSensor.imageGetGreen(image, 1, 0, 0)
b = colorSensor.imageGetBlue(image, 1, 0, 0)
print("r:", r, "g:", g, "b:", b)

这些数值是用入门机器人在 world2.wbt 上测得的:

地面 红 绿 蓝
普通地面 252 252 252
沼泽 245 222 142
区域 1 和 2 之间的通道(蓝色) 91 91 255
区域 2 和 3 之间的通道(紫色) 193 91 251
区域 1 和 4 之间的通道(绿色) 48 255 48
区域 3 和 4 之间的通道(红色) 255 91 91

坑洞有黑色的边缘,所以在坑洞前面,地面会先变暗。对这个传感器来说,检查点看起来和普通地面几乎一样,所以请在你的世界中找一个检查点来校准。

下面的程序让机器人向前行驶,每次地面变化时打印出来,看到坑洞时就停下:

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
colorSensor = robot.getDevice("color")
colorSensor.enable(timeStep)
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
leftWheel.setPosition(float("inf"))
rightWheel.setPosition(float("inf"))
def floorType(r, g, b):
# Tune these ranges for your own robot and worlds
brightness = (r + g + b) / 3
if brightness < 80:
return "hole"
if r > 220 and g > 200 and b < 190:
return "swamp"
if b > 220 and g < 130:
return "purple passage" if r > 150 else "blue passage"
if r > 220 and g < 130 and b < 130:
return "red passage"
if g > 220 and r < 100 and b < 100:
return "green passage"
return "floor"
leftWheel.setVelocity(3.0)
rightWheel.setVelocity(3.0)
last = None
while robot.step(timeStep) != -1:
image = colorSensor.getImage()
floor = floorType(colorSensor.imageGetRed(image, 1, 0, 0),
colorSensor.imageGetGreen(image, 1, 0, 0),
colorSensor.imageGetBlue(image, 1, 0, 0))
if floor != last:
print("Floor:", floor)
last = floor
if floor == "hole": # Stop before falling in
leftWheel.setVelocity(0)
rightWheel.setVelocity(0)
break