如何单独一次输出色块中心坐标
-
import sensor, image, time
import math
from pyb import UART
import json下面的阈值, 可能需要大家手动调节
thresholds = [(35, 40,55, 62, 20, 51), # 一般情况下的红色阈值
(43, 55, -45, -32, 2, 20), # 一般情况下的绿色阈值
(45, 65, -20, 30, -60, -20)] # 一般情况下的蓝色阈值sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
sensor.set_auto_gain(False) # must be turned off for color tracking
sensor.set_auto_whitebal(False) # must be turned off for color tracking
clock = time.clock()uart = UART(3, 115200)
QVGA: 320x240
WINDOW_CENTER_X = 160
WINDOW_CENTER_Y = 120标记当前识别的颜色
def markCurColor(img, cName, cRgb):
img.draw_string(0, 0, cName, color = cRgb)如果是红色,执行此函数
def doWithRed(img):
markCurColor(img, "RED", (255, 0, 0))如果是绿色,执行此函数
def doWithGreen(img):
markCurColor(img, "GREEN", (0, 255, 0))如果是绿色,执行此函数
def doWithBlue(img):
markCurColor(img, "BLUE", (0, 0, 255))颜色代码与所对应需要执行函数的映射
colorCodeMapFunc = {
1: doWithRed,
2: doWithGreen,
4: doWithBlue
}测算色块的中心与中心的距离
def distanceToCenter(blob):
winCx = WINDOW_CENTER_X
winCy = WINDOW_CENTER_Y
x = blob.x()
y = blob.y()return math.sqrt(math.pow(winCx - x, 2) + math.pow(winCy - y, 2))
比较两个色块距离的函数
def compareBlob(blob1, blob2):
# 这里我们选择了pixels作为指标比对二者的代码
# 你也可以换用其它指标 例如 blob.area()
tmp = distanceToCenter(blob1) - distanceToCenter(blob2)
if tmp == 0:
return 0;
elif tmp > 0:
return 1;
else:
return -1;while(True):
clock.tick()
bigBlob = None #最大的色块
img = sensor.snapshot()blobs = img.find_blobs( thresholds, pixels_threshold=200, area_threshold=200, merge=True) # 判断是否有色块检测到 if len(blobs) == 0: continue bigBlob = blobs[0] for blob in blobs: # 如果此色块比最大的色块还大 if compareBlob(bigBlob, blob) == 1: bigBlob = blob # 标注其他色块 img.draw_rectangle(blob.rect()) # 标记识别到的最大色块 img.draw_cross(bigBlob.cx(), bigBlob.cy()) # 根据最大色块的颜色调用不同的函数 img.draw_cross(WINDOW_CENTER_X, WINDOW_CENTER_Y, color=(255, 0, 0)) img.draw_line((WINDOW_CENTER_X, WINDOW_CENTER_Y, bigBlob.cx(), bigBlob.cy()), color=(255, 0, 0)) if bigBlob.code() in colorCodeMapFunc: colorCodeMapFunc[bigBlob.code()](img) output_str="[%d,%d]" % (bigBlob.cx(),bigBlob.cy()) #方式1 #output_str=json.dumps([bigBlob.cx(),bigBlob.cy()]) #方式2 print('you send:',output_str) uart.write(output_str+'\r\n') else: print("code not match" )
目前是连续输出坐标
-
连续输出,是因为你写在了while死循环里面