1

I'm working on the webcam using python and opencv, it seems that it lagged between reading the first one and the second one. So I want to use python thread to fix it. Here is my code:

from cv2 import *
from threading import Thread, currentThread, activeCount
import numpy as np
webcam_address0="rtsp://192.168.1.109:6554/stream_0"
webcam_address1="rtsp://192.168.1.106:6554/stream_0"
cap0=VideoCapture(webcam_address0)
cap1=VideoCapture(webcam_address1)
count=0
flag_l=False
flag_r=False
def webcam0_read():
    global frame0
    global flag_l
    while 1:
        print('start reading l')
        ret0, frame0 = cap0.read()
        print('l done')
        flag_l=True
def webcam1_read():
    global frame1
    global flag_r
    while 1:
        print('start reading r')
        ret1, frame1 = cap1.read()
        print('r done')
        flag_r=True
t0=Thread(target=webcam0_read())
t0.setDaemon(True)
t0.start()
t1=Thread(target=webcam1_read())
t1.setDaemon(True)
t1.start()
while 1:
    print('ready to print!')
    if flag_l==True and flag_r==True:
        frame0=resize(frame0,(640,360))
        frame1=resize(frame1,(640,360))
        imshow("Video Stream0", frame0)
        imshow("Video Stream1", frame1)
        if waitKey(5) == 's':
            path0="~/images/"+str(count)+"l.jpg"
            path1="~/images/"+str(count)+"r.jpg"
            imwrite(path0,frame0)
            imwrite(path1,frame1)
        elif waitKey(5)==27:
            break

When I run it, I only got the result like: start reading l

l done

start reading l

l done

start reading l

l done

It seems that the thread t1 is not running. And it never prints "ready to print!".How can I fix it? Thank you a lot!

Strel
  • 21
  • 2
  • Can this not help? https://stackoverflow.com/questions/2846653/how-to-use-threading-in-python. I can not provide the answer but maybe the threads should start right after each other – BioFrank Jun 27 '18 at 12:15
  • 3
    For starters `Thread(target=webcam1_read())` is wrong. The value of the target argument must be a callable object, e.g. a function. What you pass to your threads is the retrun value of a callable, `None` in your case. – shmee Jun 27 '18 at 12:23
  • Possible duplicate of [Creating Threads in python](https://stackoverflow.com/questions/2905965/creating-threads-in-python) – Azat Ibrakov Jun 27 '18 at 12:26

1 Answers1

3

According to the documentation, the target argument to the Thread constructor is

the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

You are passing webcam0_read(), which is not a callable. You are actually calling the webcam0_read function, which is stuck in its while loop and never returning. The rest of the code isn't even executing.

Change your target arguments to webcam0_read and webcam1_read:

t0=Thread(target=webcam0_read)
t0.setDaemon(True)
t0.start()
t1=Thread(target=webcam1_read)
t1.setDaemon(True)
t1.start()
robobrobro
  • 320
  • 2
  • 6