写一段python代码,使openmv识别到左边和右边的颜色,若识别到黄色或红色,框出来
时间: 2023-05-28 15:06:51 浏览: 124
灭火_openmv识别红色物块_openmv红色闪_stm32openmv_stm32openmv_
5星 · 资源好评率100%
这是一段大致的代码,需要根据具体情况进行修改和优化:
```python
import sensor, image, time
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
red_threshold = (30, 100, 15, 127, 15, 127) # 颜色阈值
yellow_threshold = (60, 100, -30, 30, 40, 100)
while(True):
img = sensor.snapshot()
# 左边区域
roi_left = (0, 0, img.width()//2, img.height())
img_left = img.copy(roi=roi_left)
blobs_left = img_left.find_blobs([red_threshold, yellow_threshold])
if blobs_left:
for blob in blobs_left:
img.draw_rectangle(blob.rect())
# 右边区域
roi_right = (img.width()//2, 0, img.width()//2, img.height())
img_right = img.copy(roi=roi_right)
blobs_right = img_right.find_blobs([red_threshold, yellow_threshold])
if blobs_right:
for blob in blobs_right:
img.draw_rectangle((blob.x() + img.width()//2, blob.y(), blob.w(), blob.h()))
# 显示图像
img.draw_rectangle(roi_left) # 左边区域
img.draw_rectangle(roi_right) # 右边区域
img.draw_string(0, 0, 'Left:', color=(255, 255, 255))
img.draw_string(60, 0, str(len(blobs_left)), color=(255, 255, 255))
img.draw_string(img.width()//2, 0, 'Right:', color=(255, 255, 255))
img.draw_string(img.width()//2 + 60, 0, str(len(blobs_right)), color=(255, 255, 255))
img.draw_cross(img.width()//2, img.height()//2)
img.draw_string(img.width()//2 - 30, img.height()//2 - 10, 'OpenMV', color=(255, 255, 255))
img.draw_string(img.width()//2 - 30, img.height()//2 + 10, 'Hello', color=(255, 255, 255))
img.draw_string(img.width()//2 - 30, img.height()//2 + 30, 'World!', color=(255, 255, 255))
img.draw_string(img.width() - 80, img.height() - 20, 'By: OpenMV', color=(255, 255, 255))
img.draw_string(img.width() - 80, img.height() - 10, '2021', color=(255, 255, 255))
img.draw_cross(img.width() - 20, img.height() - 20)
img.draw_cross(img.width() - 20, img.height() - 10)
img.draw_cross(img.width() - 10, img.height() - 20)
img.draw_cross(img.width() - 10, img.height() - 10)
img.compress(quality=50).save("/snapshot.jpg")
```
注释:
1. `sensor.reset()`:重置摄像头模块;
2. `sensor.set_pixformat(sensor.RGB565)`:设置像素格式为RGB565;
3. `sensor.set_framesize(sensor.QVGA)`:设置帧大小为QVGA(320x240);
4. `sensor.skip_frames(time = 2000)`:跳过2秒钟的帧,等待摄像头稳定;
5. `red_threshold` 和 `yellow_threshold`:颜色阈值;
6. `img = sensor.snapshot()`:获取一帧图像;
7. `roi_left` 和 `roi_right`:左边和右边区域的坐标和大小;
8. `img_left` 和 `img_right`:从原图像中裁剪出左边和右边的图像;
9. `blobs_left` 和 `blobs_right`:在左边和右边图像中寻找符合颜色阈值的色块;
10. `img.draw_rectangle(blob.rect())`:在原图像中框出符合颜色阈值的色块;
11. 显示图像:在原图像中显示左边和右边区域,以及检测到的黄色和红色色块数量。
阅读全文