python中多线程的替代方法是什么?

2024-05-16 03:40:39 发布

您现在位置:Python中文网/ 问答频道 /正文

一种基于卷积神经网络+opencv的实时图像分类模型,这里是Link to code

我试图运行下面的文件camera_test.py,它实现了多线程处理以提高程序的fps。while循环准备帧,而线程处理它以预测帧内图像的标签

from imagenet_utils import decode_predictions
from imagenet_utils import preprocess_input
from keras.applications.vgg16 import VGG16
import cv2
import numpy as np
import sys
import threading

label = ''
frame = None

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global label
    # Load the VGG16 network
        print("[INFO] loading network...")
        self.model = VGG16(weights="imagenet")

        while (~(frame is None)):
            (inID, label) = self.predict(frame)

    def predict(self, frame):
        image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB).astype(np.float32)
    #image = image.transpose((2, 0, 1))
        image = image.reshape((1,) + image.shape)
        image = preprocess_input(image)
        preds = self.model.predict(image)
        return decode_predictions(preds)[0]

cap = cv2.VideoCapture(0)
if (cap.isOpened()):
    print("Camera OK")
else:
    cap.open()

keras_thread = MyThread()
keras_thread.start()

while (True):
    ret, original = cap.read()

    frame = cv2.resize(original, (224, 224))

# Display the predictions
# print("ImageNet ID: {}, Label: {}".format(inID, label))
    cv2.putText(original, "Label: {}".format(label), (10, 30), 
    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
    cv2.imshow("Classification", original)

    if (cv2.waitKey(1) & 0xFF == ord('q')):
        break;

cap.release()
frame = None
cv2.destroyAllWindows()
sys.exit()

但是,表演是不可预测的。代码有时运行得非常好,而另一次则抛出一个随机的错误。错误当我运行这段代码时,我通常会遇到:ValueError: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 64), dtype=float32) is not an element of this graph。在

我尝试过实现multiprocessing.pool而不是线程,但是程序经常挂起并冻结。还有其他的选择吗?或者有办法修复这个代码吗?在


Tags: fromimageimportselfcv2framelabelkeras