cap = cv2.VideoCapture(0)
opencv模块百度百科解释
OpenCV是一个基于Apache2.0许可(开源)发行的跨平台计算机视觉和机器学习软件库,可以运行在Linux、Windows、Android和Mac OS操作系统上。 它轻量级而且高效——由一系列 C 函数和少量 C++ 类构成,同时提供了Python、Ruby、MATLAB等语言的接口,实现了图像处理和计算机视觉方面的很多通用算法。
opencv常用函数
详见csdn博客https://blog.csdn.net/Vici__/article/details/100714822
该句中的VideoCapture函数的作用是开启摄像头或者打开视屏文件,参数0的作用是在只有一个摄像头的时候自动连接该摄像头获取视频数据。
begin=time()
该函数的作用是返回当前的时间戳(1970纪元后经过的浮点秒数)。
fps=cap.get(cv2.CAPPROP_FPS),_print(fps)
返回当前视频的帧速率,并将其打印出来。
while循环中的程序的注释
while cap.isOpened():#当摄像头开启时进入循环ret, frame = cap.read()#返回当前时刻的读取图片的状态和每一帧的图片#ret, frame = cap.read()返回值含义:#参数ret 为True 或者False,代表有没有读取到图片#第二个参数frame表示截取到一帧的图片res = cv2.resize(frame, (160, 120), interpolation=cv2.INTER_CUBIC)#将图片进行尺寸的调整,interpolation=cv2.INTER_CUBIC 表示在图片扩展的时候使用的是INTER_CUBIC这个插值法,不必过度理解res=RotateClockWise180(res)#将图片顺时针旋转180度res=cv2.flip(res,1)#将上面一句翻转过的图片再进行一次水平翻转cv2.imshow("frame", res)#将处理过的图片在名为"frame"的窗口中显示出来cv2.waitKey(1)#waitKey(1)为等待1ms,加上while循环,即为无限等待,窗口在程序运行时不释放frame = np.array(res, dtype=np.float32)#将图片数据转化为数组,并将数据类型转化为float32,在机器学习中一般使用float32这一数据类型。camera_data_array = np.expand_dims(frame, axis=0)#将二维数据拓展成为三维数据,从第一个维度拓展一个维度prediction_array = model.predict(camera_data_array)#将数据输入神经网络模型得到一个预测值value = get_max_prob_num(prediction_array)#得到预测值的最大值print(value)end=time()#返回当前的时间戳
判断语句和运动函数
使用开始和结束时的时间戳和得到的最大值对机器人的运动进行判定。
if value == 0:print("forward")if(end-begin<30):robot.movement.move_forward()if(end-begin>30):robot.movement.move_forward1()elif value == 1:print("left")print(end-begin)if(end-begin>5 and end-begin<17):robot.movement.left_ward2()if(end-begin<30 and end-begin>17 and end-begin>3):robot.movement.left_ward1()if(end-begin<3):robot.movement.turn_left()if(end-begin>30):robot.movement.move_forward2()#robot.movement.left_ward3()if(end-begin>3 and end-begin<5):robot.movement.move_forward()elif value == 2:print(end-begin)print("hit")robot.movement.hit()breakelif value == 3:#print("right")print(end-begin)if(end-begin<8 and end-begin>3):if(end-begin<8):robot.movement.right_ward2()print("ringt1")if(end-begin>8):if(end-begin<30 and end-begin>20):robot.movement.right_ward3()#robot.movement.move_forward1()print("ringt2")if(end-begin<20):robot.movement.turn_right()print("ringt3")if(end-begin<34 and end-begin>30):robot.movement.right_ward3()if(end-begin>34):#robot.movement.right_ward4()robot.movement.move_forward2()if(end-begin<3):robot.movement.turn_right()#robot.movement.right_ward2()print("ringt4")if value == 4:if(end-begin<30):robot.movement.turn_right2()if(end-begin>30):robot.movement.hit()break
