コンテンツにスキップ
日本語

RGB カメラ

カメラは、正面にあるものの画像を返します。壁のトークンを見つけて読み取るにはカメラが必要です。スターターロボットには、camera という名前の 64 × 40 ピクセルのカメラが 1 台あります。

画像はピクセルの格子です。各ピクセルは 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 の画像はピクセルごとに BGRA の順で 4 つの値を持ち、OpenCV でそのまま使えます。このプログラムは、画像とその明るい部分を 2 つのウィンドウに表示します。

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 で選びます。