我的本意是先寻找最大的红色色块,在判断是不是圆。但是效果是是个圆就会识别,然后还有多个最大色块,这个代码该怎么改呢?
-
import sensor, image, time, pyb from pyb import UART sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QQVGA) 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() red = 0 red_threshold = (9, 51, 29, 95, 20, 51)#red uart = UART(3, 9600) def find_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 while(True): clock.tick() img = sensor.snapshot() blobs = img.find_blobs([red_threshold]) if blobs: max_blob = find_max(blobs) for max_blob in img.find_circles( threshold = 3500, x_margin = 10, y_margin = 10, r_margin =10, r_min = 10, r_max = 60, r_step = 10 ): img.draw_circle(max_blob.x(), max_blob.y(), max_blob.r(), color = (0, 255, 0)) red = red+1 if red == 10: red = 0 pyb.LED(2).on() uart.write("1\r\n") time.sleep_ms(200) pyb.LED(2).off() ![0_1710587934490_1710587710562.jpg](https://fcdn.singtown.com/f21ed488-f5c8-4326-a1f7-3e8ebf1142d1.jpg)
-
这是实际效果
-
你的代码逻辑有问题。
for max_blob in img.find_circles()应该是 for circle in img.find_circles(roi=max_blob.rect())但是,如果判断色块是否为圆,直接判断圆度就行了。
import sensor, image, time, pyb from pyb import UART sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QQVGA) 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() red = 0 red_threshold = (9, 51, 29, 95, 20, 51)#red uart = UART(3, 9600) def find_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 while(True): clock.tick() img = sensor.snapshot() blobs = img.find_blobs([red_threshold]) if blobs: max_blob = find_max(blobs) img.draw_rectangle(max_blob.rect()) print(max_blob.roundness())