我为一个项目编写了一个Python脚本,其中我在执行任务时记录主题的行为。为此,我在使用Python 2.7的Windows 7计算机上使用openCV
模块。因为我希望以后能够将视频与我在任务期间收集的时间戳对齐,所以两个操作都需要并行运行。因此,我一直在尝试使用multiprocessing
模块。到目前为止,这两个进程并行运行。问题是停止部分。我创建了一个简单的布尔变量,如果实际代码完成,则变为0(False)。我想将此变量传递给进程以退出进程中的代码运行。但是,这似乎不起作用。谁能告诉我如何解决这个问题?
这是应该在流程中运行的代码
def camera(running):
cap = cv2.VideoCapture(0)
valueTime = datetime.datetime.fromtimestamp(time.time())
filename = valueTime.strftime('_%Y-%m-%d_%H-%M-%S.avi')
path = 'C:/Users/csc/Desktop/Videos'
pathname = os.path.join(path,filename)
print "Create video file "+pathname
# Define the codec and create VideoWriter object
fourcc = fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter(pathname,fourcc, 28.0, (640,480))
#out = cv2.VideoWriter('output.avi',-1, 30.0, (640,480))
while running.value==1:
ret, frame = cap.read()
grayImage = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
out.write(grayImage)
cv2.imshow('frame',grayImage)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if running.value==0:
break
cap.release()
out.release()
cv2.destroyAllWindows()
主要代码(一般化示例):
from multiprocessing import Process,Value
running = Value('i', 1)
while timer_for_approx_20_min:
vidrecord = Process(target=camera(running, ), args=(running,))
vidrecord.start()
# Code for the task
running.value = 0