如何在python的OpenCv中添加自定义Keras模型

时间:2019-07-18 11:24:22

标签: python opencv keras

我创建了一个用于对两种类型的鞋子进行分类的模型

现在如何在OpenCv(视频对象检测)中部署它?

预先感谢

2 个答案:

答案 0 :(得分:2)

您可以借助OpenCV DNN模块来做​​到这一点:

import cv2

# Load a model imported from Tensorflow
tensorflowNet = cv2.dnn.readNetFromTensorflow('card_graph/frozen_inference_graph.pb', 'exported_pbtxt/output.pbtxt')

# Input image
img = cv2.imread('image.jpg')
rows, cols, channels = img.shape

# Use the given image as input, which needs to be blob(s).
tensorflowNet.setInput(cv2.dnn.blobFromImage(img, size=(300, 300), swapRB=True, crop=False))

# Runs a forward pass to compute the net output
networkOutput = tensorflowNet.forward()

# Loop on the outputs
for detection in networkOutput[0,0]:

    score = float(detection[2])
    if score > 0.9:

        left = detection[3] * cols
        top = detection[4] * rows
        right = detection[5] * cols
        bottom = detection[6] * rows

        #draw a red rectangle around detected objects
        cv2.rectangle(img, (int(left), int(top)), (int(right), int(bottom)), (0, 0, 255), thickness=2)

# Show the image with a rectagle surrounding the detected objects 
cv2.imshow('Image', img)
cv2.waitKey()
cv2.destroyAllWindows()

您需要冻结的推论图和pbtxt文件才能在OpenCV中运行模型

答案 1 :(得分:0)

您将模型保存到H5文件model.save(“ modelname.h5”),然后将其加载到OpenCV代码load_model(“ modelname.h5”)中。然后在循环中检测通过model.predict(ImageROI)找到的对象