使用轮廓

在使用形态学操作对阈值进行处理并消除了噪声之后,您现在就可以使用OpenCV的“ findContours”方法了。此方法使您可以根据二进制图像生成轮廓。

查找和过滤轮廓

_, contours, _ = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

In cases where there is only one vision target, you can just take the largest contour and assume that is the target you are looking for. When there is more than one vision target, you can use size, shape, fullness, and other properties to filter unwanted contours out.

if len(contours) > 0:
   largest = contours[0]
   for contour in contours:
      if cv2.contourArea(contour) > cv2.contourArea(largest):
         largest = contour

   #
   # Contour processing code
   #

如果绘制刚发现的轮廓,则外观应如下所示:

Retroreflective tape outlined in red by the image processing algorithm.

从轮廓提取信息

现在,您已经找到了所需的轮廓,现在想要获取有关轮廓的信息,例如中心,角和旋转。

中心

rect = cv2.minAreaRect(contour)
center, _, _ = rect
center_x, center_y = center

corners = cv2.convexHull(contour)
corners = cv2.approxPolyDP(corners, 0.1 * cv2.arcLength(contour), True)

旋转

_, _, rotation = cv2.fitEllipse(contour)

有关如何使用这些值的更多信息,请参阅:docs / software / vision-processing / introduction / identification-and-processing-the-targets:Measurements

发布到NetworkTables

您可以使用NetworkTables将这些属性发送到Driver Station和RoboRIO。可以在Raspberry Pi或RoboRIO本身上进行其他处理。

import ntcore

nt = ntcore.NetworkTableInstance.getDefault().getTable('vision')

#
# Initialization code here
#

while True:

   #
   # Image processing code here
   #

   nt.putNumber('center_x', center_x)
   nt.putNumber('center_y', center_y)