python做垃圾识别,将拍照和识别整合到一起

怎样将这两段整合到一起,写到try里面


import time
import cv2                                       
capture = cv2.VideoCapture(0)
while(True):
        # 获取一帧
        ret, frame = capture.read()
        # 将这帧转换为灰度图
        # cv2.imshow('frame', frame)
        time.sleep(3)
        cv2.imwrite("./test_image/laji.png", frame) 

if name == "main":
model = init_artificial_neural_network()

# while True:
try:

    img_url = './test_image/laji.png'
    # print('您输入的图片地址为:' + img_url)
    res = prediction_result_from_img(model, img_url)
except Exception as e:
    print('发生了异常:', e)
    capture.release() #释放摄像头
    cv2.destroyAllWindows()#删除建立的全部窗口

整合你还要改下 prediction_result_from_img这个函数,将原来的从硬盘读取图片变成直接使用内存中的图片才行,不然你怎么整合这个函数还是从本地读取,还是没啥用。

import time
import cv2
capture = cv2.VideoCapture(0)
model = init_artificial_neural_network()
while(True):
    try:
    # 获取一帧
        ret, frame = capture.read()
        # 将这帧转换为灰度图
        # cv2.imshow('frame', frame)
        time.sleep(3)
        #cv2.imwrite("./test_image/laji.png", frame)
        res = prediction(model, frame)#这里需要改下获取图片的方式
    except Exception as e:
        print('发生了异常:', e)
        capture.release()  # 释放摄像头
        cv2.destroyAllWindows()  # 删除建立的全部窗口
        break