首页 > 解决方案 > 如何在 rasberry pi 中修复 python 中的“多线程问题”

问题描述

我无法找出我在树莓派 3 中用 python 编写的用于对象识别的多线程程序可能有什么问题。

该代码在树莓派 3 模型上运行。我希望做两个线程;一种用于显示实时图像,另一种用于检测对象并找到其中心。我尝试了我在下面编写的代码。当我在笔记本电脑上使用它时它工作正常,但它不起作用(第二个函数;detect() 在树莓派上的 line faces = drop_cascade.detectMultiScale(image, 1.25, 7)) 之后没有响应,但如果我删除该行并遵循 for 循环并替换为简单的代码,例如 print("hello") 它工作正常。

import threading
import cv2
import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
global image, center
center=[]
def capture():
    global image, center
    cv2.namedWindow('image',cv2.WINDOW_NORMAL)
    cv2.moveWindow('image',0,0)
    cv2.resizeWindow('image', 800,608)
    camera=PiCamera()
    camera.resolution=(800,608)
    camera.framerate=50
    rawCapture=PiRGBArray(camera,size=(800,608))
    for frame in camera.capture_continuous(rawCapture,format='bgr',use_video_port=True):
        image=frame.array      
        cv2.imshow('image',image)

        key=cv2.waitKey(1)& 0xFF
        rawCapture.truncate(0)
        if key==ord('q'):
            break    
    cv2.destroyAllWindows()

def detect():
    global image, center
    time.sleep(2)
    drop_cascade = cv2.CascadeClassifier('cascade.xml')
    while True:
        faces = drop_cascade.detectMultiScale(image, 1.25, 7)
        for (x, y, w, h) in faces:
            center.append([x,y,w,h])

if __name__ == '__main__':
    thread1=threading.Thread(target=capture)
    thread2=threading.Thread(target=detect)
    thread1.start()
    thread2.start()

我想同时运行这些线程,以便捕获功能显示的图像顺利运行,并由检测功能完成检测。

标签: pythonmultithreadingraspberry-pi3

解决方案


推荐阅读