跳转到内容
中文(简体)

RGB 摄像头

摄像头会给出它前方景物的图像。你需要用它来寻找和识别墙面标识。入门机器人有一个摄像头,名字是 camera,分辨率为 64 × 40 像素。

图像是由像素组成的网格。每个像素都有红、绿、蓝三个值,范围是 0 到 255,其中 (0, 0, 0) 是黑色,(255, 255, 255) 是白色。

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
camera = robot.getDevice("camera")
camera.enable(timeStep)
width = camera.getWidth()
height = camera.getHeight()
print("The camera has", width, "x", height, "pixels")
while robot.step(timeStep) != -1:
image = camera.getImage()
# The colour of the pixel in the center of the image
r = camera.imageGetRed(image, width, width // 2, height // 2)
g = camera.imageGetGreen(image, width, width // 2, height // 2)
b = camera.imageGetBlue(image, width, width // 2, height // 2)
print("Center:", r, g, b)

OpenCV 是一个图像处理库:可以寻找形状、比较颜色,还能做很多其他事情。Webots 图像的每个像素有 4 个值,顺序为 BGRA,OpenCV 可以直接使用。下面的程序会在两个窗口中分别显示图像和图像中较亮的部分:

from controller import Robot
import cv2
import numpy as np
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
camera = robot.getDevice("camera")
camera.enable(timeStep)
while robot.step(timeStep) != -1:
# Webots images have 4 channels per pixel, in BGRA order
image = np.frombuffer(camera.getImage(), np.uint8).reshape((camera.getHeight(), camera.getWidth(), 4))
frame = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY) # Bright parts in white
cv2.imshow("camera", cv2.resize(frame, None, fx=4, fy=4, interpolation=cv2.INTER_NEAREST))
cv2.imshow("threshold", cv2.resize(thresh, None, fx=4, fy=4, interpolation=cv2.INTER_NEAREST))
cv2.waitKey(1) # Shows the windows

左边是入门机器人在字母受害者前方拍到的摄像头图像,右边是这个程序找出的图像中较亮的部分。

字母受害者的摄像头图像,以及用白色表示的较亮部分

这类窗口只用于在家测试:比赛时请把它们关掉。

分辨率越高,能在越远的地方看到标识,但成本更高,处理时间也更长。你可以在 Robot Customizer 中为每个摄像头选择分辨率。