5. 脚本结构¶
现在让我们学习如何编程您的 OpenMV Cam!请注意,本教程假设您知道 python 语言的工作原理。如果您不了解 python 的工作原理,请先学习。有很多关于如何编写 python 代码的网络教程(最后,如果您了解其他类似 C 的编程语言,您可以轻松地学习 python,因为它们非常相似)。
无论如何,您编写的任何脚本都将包含三个不同的部分:
import ...
...
one time setup ...
...
while(True): # Loop
...
您 OpenMV Cam 代码的第一部分应包括一些头部注释、导入语句将模块引入范围,以及最后在代码中定义常量和全局变量。
接下来,您将需要进行一次性设置代码。这包括创建 I/O 引脚对象、设置相机、定义辅助函数等。
最后,您将创建一个 while(True):
循环,在该循环下,您将放置所有需要重复调用的代码在一个循环中,直到关闭电源为止。
以下是一个示例:
### Header comments, import statements, etc.
# Hello World Example
#
# Welcome to the OpenMV IDE! Click on the green run arrow button below to run the script!
import sensor, image, time
### One time setup
sensor.reset() # Reset and initialize the sensor.
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240)
sensor.skip_frames(time = 2000) # Wait for settings take effect.
clock = time.clock() # Create a clock object to track the FPS.
### Infinite loop
while(True):
clock.tick() # Update the FPS clock.
img = sensor.snapshot() # Take a picture and return the image.
print(clock.fps()) # Note: OpenMV Cam runs about half as fast when connected
# to the IDE. The FPS should increase once disconnected.
请注意,如果您的代码中没有无限循环,则一旦您的 OpenMV Cam 完成运行脚本,它将停在那里并且什么都不做。