logo

我在尝试在彩色图片中识别矩形后并计算识别矩形的灰度值时出现了一个问题,见截图

2018-09-04 11:15
D
_15652391995
import sensor, image, pyb, time, lcd

record_time = 10000 # 10 seconds in milliseconds

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time = 2000)
clock = time.clock()
sensor.set_auto_whitebal(False)
sensor.skip_frames(30) # Let new settings take affect.
sensor.set_gainceiling(8)
lcd.init()

img_writer = image.ImageWriter("/example5.jpg")

# Red LED on means we are capturing frames.
red_led = pyb.LED(1)
red_led.on()
start = pyb.millis()
while pyb.elapsed_millis(start) < record_time:
    clock.tick()
    img = sensor.snapshot()
    for r in img.find_rects(threshold = 10000):
            img.draw_rectangle(r.rect(), color = (255, 0, 0))
            for p in r.corners(): img.draw_circle(p[0], p[1], 5, color = (0, 255, 0))
            print(r)
    roi = rect.rect()
    statistics = img.get_statistics(roi=roi)
    print(statistics.l_mean()) #输出灰度的平均值
    img.draw_string(75,100,'C='+str(statistics.l_mean()),color=(255,255,255))
    lcd.display(img)
    img_writer.add_frame(img)
    print(clock.fps())

img_writer.close()

# Blue LED on means we are done.
red_led.off()
blue_led = pyb.LED(3)
blue_led.on()

print("Done")
while(True):
    pyb.wfi()

以上是代码

1dca1986-c258-4e2a-8119-43904b203130.png

出现了如截图所示的问题,请问下解决办法

I
网红小智智 星瞳科技

很明显,rect没定义。rect这个变量哪来的?

2018-09-04 11:24
D
_15652391995

第25行定义的

即使我换成roi = r.rect() 还是会出现这个同样的问题

2018-09-04 12:06
I
网红小智智 星瞳科技

r在for循环里才能用。每次循环都会改变值。

2018-09-05 09:47
D
_15652391995

那请问下这种情况怎么办

2018-09-05 11:49
I
网红小智智 星瞳科技
roi = []
for r in img.find_rects(threshold = 10000):
    img.draw_rectangle(r.rect(), color = (255, 0, 0))
    for p in r.corners(): 
        img.draw_circle(p[0], p[1], 5, color = (0, 255, 0))
        print(r)
        roi = r.rect()

这个逻辑是roi会赋值为最后一个方块,也许你还需要查找最大的方块。

2018-09-05 22:11
D
_15652391995

谢谢你耐心的回复,但是我又出现了这么个问题

D
_15652391995
ec33a236-8449-4b80-9c7a-221e9230087f.png

我想的是算出我找到的矩形的灰度,但是好像这种for循环没法用,请问下有什么解决办法吗

2018-09-05 22:42
D
_15652391995
ce5ff07c-928c-435d-85ff-e9a3b7f38f1d.png

有时候也会出现这个问题,但是偶尔只有一个正方形的话也能够测算出灰度值,请能说说问题在哪,怎么解决吗