Python 3.7 OpenCV - 处理速度慢

问题描述 投票:0回答:2

我正在尝试使用 OpenCV 4.4.0.40 拍照,并且仅在按下由 Arduino 读取的开关时才保存它们。

到目前为止,一切正常,但速度超级慢,大约需要 15 秒才能改变

Switch
值。

Arduino = SerialObject()

if os.path.exists(PathCouleur) and os.path.exists(PathGris):

Images = cv2.VideoCapture(Camera)
Images.set(3, 1920)
Images.set(4, 1080)
Images.set(10, Brightness)

Compte = 0

SwitchNumero = 0

while True:

    Sucess, Video = Images.read()
    cv2.imshow("Camera", Video)
    Video = cv2.resize(Video, (Largeur, Hauteur))

    Switch = Arduino.getData()
    
    try:
        if Switch[0] == "1":
            blur = cv2.Laplacian(Video, cv2.CV_64F).var()

            if blur < MinBlur:
                cv2.imwrite(PathCouleur + ".png", Video)
                cv2.imwrite(PathGris + ".png", cv2.cvtColor(Video, cv2.COLOR_BGR2GRAY))
                Compte += 1
    
    except IndexError as err:
        pass

    if cv2.waitKey(40) == 27:
        break

Images.release()
cv2.destroyAllWindows()

else:
    print("Erreur, aucun Path")

保存的图像宽度为 640,高度为 480,显示图像为 1920x1080,但即使没有显示图像,速度也很慢。

有人可以帮我优化这段代码吗?

python performance opencv
2个回答
0
投票

我想说这段代码是造成延迟的原因,因为有两个主要调用依赖于外部设备来响应(OpenCV 调用和

Arduino.getData()
)。

Sucess, Video = Images.read()
cv2.imshow("Camera", Video)
Video = cv2.resize(Video, (Largeur, Hauteur))

Switch = Arduino.getData()

想到的一个解决方案是使用多线程库并将

Arduino.getData()
调用与主循环周期分开,并在单独的类中使用它在后台运行(您应该在辅助线程上使用睡眠,例如50 或 100 毫秒延迟)。

这样,当 Switch 事件尝试读取主循环上的值时,您应该有更好的响应。


0
投票
cam=cv2.VideoCapture(0,cv2.CAP_DSHOW)

使用 cv2.CAP_DSHOW 它将改善相机的加载时间,因为它会直接为您提供视频源

© www.soinside.com 2019 - 2024. All rights reserved.