logo

local variable referenced before assignment

2023-07-22 15:23
J
z1yl

报错Traceback (most recent call last):

File "<stdin>", line 68, in <module>

File "<stdin>", line 29, in find_blob_max

NameError: local variable referenced before assignment

OpenMV v4.4.1; MicroPython d8e38d0; OPENMV4P-STM32H743

Type "help()" for more information.

import sensor, image, time, math, pyb
from pyb import UART, LED
import json
import ustruct

thresholds_black=[(1, 41, -18, 2, -1, 14)]
thresholds_red=[(69, 98, -1, 38, 1, 13)]



sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time = 10)
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)
uart.init(115200, bits=8,parity=None,stop=1)

def find_blob_max(blobs):
    max_size = 0
    for blob in blobs:
        if blob[2]*blob[3]>max_size:
            max_blob = blob
            max_size = blob[2]*blob[3]
    return max_blob


def send_data_packet(x, y, r):        #x = rho_err 偏移的距离;a(angle) = theta_err 偏移的角度
    global uart;

    data = ustruct.pack("<bbbbbb",
                        0x2C,
                        0x12,
                        int(x),     #偏差距离
                        int(y),
                        int(r),
                        0x5B)
    uart.write(data)



def find_CR():
    while(True):
        #iasd=0
        #print(iasd)
        clock.tick()
        img = sensor.snapshot()
        img_black = img.lens_corr(1.1).binary(thresholds_black).dilate(1)
        circlemin = img_black.find_circles(threshold = 7000, x_margin = 10, y_margin = 10, r_margin = 10,r_min = 47, r_max = 50, r_step = 2)
        if circlemin:
            img.draw_circle(circlemin[0].x(), circlemin[0].y(), circlemin[0].r(), color = (255, 0, 0))
            print(circlemin)
            print(circlemin[0].x(), circlemin[0].y(), circlemin[0].r())
            send_data_packet(circlemin[0].x(), circlemin[0].y(), circlemin[0].r())
            break
    #print("FPS %f" % clock.fps())

find_CR()
while(True):
    clock.tick()
    img = sensor.snapshot().lens_corr(1.1).binary(thresholds_red).dilate(2)
    blobs=img.find_blobs([(96, 100, -13, 5, -11, 18)], pixels=5)
    blob_max = find_blob_max(blobs)
    print(blob_max[0:2])
    send_data_packet(blob_max[0],blob_max[1],0)
I
网红小智智 星瞳科技

find_blob_max

上面加一句:if blobs:

你每考虑到没找到色块的情况。