gpt4 book ai didi

python - OpenCV Python跟踪栏回调

转载 作者:行者123 更新时间:2023-12-02 17:39:21 25 4
gpt4 key购买 nike

我目前正在用opencv(3.0)编写一个Python(2.7)边缘检测脚本,到目前为止基本上可以正常工作。

现在,我想在程序运行时在我的笔记本电脑摄像头和第二个网络摄像头之间切换。

因此,我将轨迹栏实现为开关,但是我不知道如何获取轨迹栏已更改的信息。

普通的getTrackbarPos()是不够的,我需要这样的东西:

如果TrackbarHasChanged()->重新启动程序-> cv2.VideoCapture(更改的摄像机)-> while(true)循环

提前致谢

最佳答案

你真幸运。实际上,该行为已经存在于OpenCV跟踪栏中。如果阅读createTrackbar的文档,您将看到python的内容:

cv2.createTrackbar(trackbarName, windowName, value, count, onChange) → None



onChange参数为:

onChange – Pointer to the function to be called every time the slider changes position. This function should be prototyped as void Foo(int,void*); , where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is the NULL pointer, no callbacks are called, but only value is updated.



这基本上意味着您想要做什么。如果有变化,则不要检查pos每个循环,而要进行更改。

对于重新启动程序部分,它有些棘手。据我所知(我可能是错的),它在另一个线程中运行,并且可能会出现某些竞争状况问题...。

这是一些小代码(由于没有网络摄像头,所以我无法完全测试),可以创建跟踪栏,创建回调函数,更改摄像头并避免线程问题(我认为,您可能需要实际使用Lock当使用cameraToUse和cameraChange时,实际上是线程安全的)。如果没有摄像头,它将运行,但是在连接中始终会打印错误。使用相机,它实际上可以工作:)

我添加了很多评论,但是如果您不参与,请随时在评论中提问
import cv2
import numpy as np

# global variables
amountOfCameras = 3 # how many cameras you want to use
cameraToUse = 0 #initial camera
cameraChange = True #starts true to connect at start up
camera = cv2.VideoCapture() # empty placeholder

# callback function for the tracker, x is the position value
# you may put whatever name in here
def trackerCallback(x):
global cameraToUse
global cameraChange
if cameraToUse != x:
print "I change to this camera", x
cameraToUse = x
cameraChange = True

# function to connect to a camera and replace the videoCapture variable
def connectToCamera():
global cameraChange
global camera
print "Connecting to camera", cameraToUse
camera = cv2.VideoCapture(cameraToUse)
# basic check for connection error
if camera.isOpened():
print "Successfully connected"
else:
print "Error connecting to camera", cameraToUse
cameraChange = False

#initial image with the tracker
img = np.zeros((200,600,3), np.uint8)
cv2.namedWindow('image')

cv2.createTrackbar('Camera','image',0,amountOfCameras-1,trackerCallback)

while(1):
#check if it has to connect to something else
if cameraChange:
connectToCamera()
# if no problems with the current camera, grab a frame
if camera.isOpened():
ret, frame = camera.read()
if ret:
img = frame
# displays the frame, in case of none, displays the previous one
cv2.imshow('image',img)
# if esc button exit
k = cv2.waitKey(1) & 0xFF
if k == 27:
break

cv2.destroyAllWindows()

关于python - OpenCV Python跟踪栏回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com