0

i have a script that recognize plates from camera, and now i need the same script to recognize from other camera so in short it needs to recognize from two cameras at once ,i am using Tensoflow/keras and YOLO object detection , can someone suggest sollution to this , i tried with different threads but i could not start the second thread , i will post what i have tried

import sys, os
import threading
import keras
import cv2
import traceback
import numpy as np
import time
import sqlite3
import pyodbc
import time
from imutils.video import  VideoStream
from pattern import apply_pattern
import darknet.python.darknet as dn
from os.path import splitext, basename
from glob import glob
from darknet.python.darknet import detect
from src.label import dknet_label_conversion
from src.utils import nms
from src.keras_utils import load_model
from glob import glob
from os.path import splitext, basename
from src.utils import im2single
from src.keras_utils import load_model, detect_lp
from src.label import Shape, writeShapes
import imutils
cam_vlez ="rtsp://"
cam_izlez = "rtsp://a"


def adjust_pts(pts,lroi):
     return pts*lroi.wh().reshape((2,1)) + lroi.tl().reshape((2,1))


def start_vlez(cam):
    while True:
        cap = VideoStream(cam).start()
        start_time = time.time()
        sky = cap.read()
        frame = sky[100:700, 300:1800]

        w = frame.shape[0]
        h = frame.shape[1]
        ratio = float(max(frame.shape[:2])) / min(frame.shape[:2])
        side = int(ratio * 288.)
        bound_dim = min(side + (side % (2 ** 4)), 608)

        Llp,LlpImgs,_ = detect_lp(wpod_net,im2single(frame),bound_dim,2**4,(240,80),lp_threshold)
        cv2.imshow('detected_plate', frame)
        if len(LlpImgs):
            Ilp = LlpImgs[0]
            s = Shape(Llp[0].pts)
            for shape in [s]:
                ptsarray = shape.pts.flatten()
                try:
                    frame = cv2.rectangle(frame,(int(ptsarray[0]*h), int(ptsarray[5]*w)),(int(ptsarray[1]*h),int(ptsarray[6]*w)),(0,255,0),3)
                    cv2.imshow('detected_plate', frame)
                except:
                    traceback.print_exc()
                    sys.exit(1)
            Ilp = cv2.cvtColor(Ilp, cv2.COLOR_BGR2GRAY)

            Ilp = cv2.cvtColor(Ilp, cv2.COLOR_GRAY2BGR)
            cv2.imwrite('%s/_lp.png' % (output_dir),Ilp*255.)
            cv2.imshow('lp_bic', Ilp)
            R,(width,height) = detect(ocr_net, ocr_meta, 'lp_images/_lp.png' ,thresh=ocr_threshold, nms=None)
            if len(R):


                L = dknet_label_conversion(R,width,height)
                L = nms(L,.45)

                L.sort(key=lambda x: x.tl()[0])
                lp_str = ''.join([chr(l.cl()) for l in L])


                result =apply_pattern(lp_str)
                write_to_database(result)




                print("License Plate Detected: ", lp_str)
                print("Written in database: ", result)


                print("--- %s seconds ---" % (time.time() - start_time))
                #updateSqliteTable(lp_str)


def start_izlez(cam):
    while True:
        cap = VideoStream(cam).start()
        start_time = time.time()
        sky = cap.read()
        frame = sky[100:700, 300:1800]

        w = frame.shape[0]
        h = frame.shape[1]
        ratio = float(max(frame.shape[:2])) / min(frame.shape[:2])
        side = int(ratio * 288.)
        bound_dim = min(side + (side % (2 ** 4)), 608)

        Llp,LlpImgs,_ = detect_lp(wpod_net,im2single(frame),bound_dim,2**4,(240,80),lp_threshold)
        cv2.imshow('detected_plate1', frame)
        if len(LlpImgs):
            Ilp = LlpImgs[0]
            s = Shape(Llp[0].pts)
            for shape in [s]:
                ptsarray = shape.pts.flatten()
                try:
                    frame = cv2.rectangle(frame,(int(ptsarray[0]*h), int(ptsarray[5]*w)),(int(ptsarray[1]*h),int(ptsarray[6]*w)),(0,255,0),3)
                    cv2.imshow('detected_plate1', frame)
                except:
                    traceback.print_exc()
                    sys.exit(1)
            Ilp = cv2.cvtColor(Ilp, cv2.COLOR_BGR2GRAY)

            Ilp = cv2.cvtColor(Ilp, cv2.COLOR_GRAY2BGR)
            cv2.imwrite('%s/_lp.png' % (output_dir),Ilp*255.)
            cv2.imshow('lp_bic', Ilp)
            R,(width,height) = detect(ocr_net, ocr_meta, 'lp_images/_lp.png'            ,thresh=ocr_threshold, nms=None)
            if len(R):


                L = dknet_label_conversion(R,width,height)
                L = nms(L,.45)

                L.sort(key=lambda x: x.tl()[0])
                lp_str = ''.join([chr(l.cl()) for l in L])

                result =apply_pattern(lp_str)
                write_to_database(result)

                print("License Plate Detected: ", lp_str)
                print("Written in database: ", result)

                print("--- %s seconds ---" % (time.time() - start_time))
                #updateSqliteTable(lp_str)


if __name__ == '__main__':
    try:
        output_dir = 'lp_images/'

        lp_threshold = .5
        wpod_net_path = "./my-trained-model/my-trained-model1_final.json"
        wpod_net = load_model(wpod_net_path)
        ocr_threshold = .6
        ocr_weights = b'data/ocr/ocr-net.weights'
        ocr_netcfg = b'data/ocr/ocr-net.cfg'
        ocr_dataset = b'data/ocr/ocr-net.data'
        ocr_net = dn.load_net(ocr_netcfg, ocr_weights, 0)
        ocr_meta = dn.load_meta(ocr_dataset)

        t = threading.Thread(target=start_vlez(cam_izlez))
        t1 = threading.Thread(target=start_izlez(cam_vlez))

        t.start()
        t1.start()
    except:
     print ("Error: unable to start thread")
Bobs Burgers
  • 761
  • 1
  • 5
  • 26
Ivanh23
  • 17
  • 6
  • What error are you getting when you try to run this code? – Bobs Burgers Aug 23 '20 at 15:52
  • I am just getting could not start thread – Ivanh23 Aug 23 '20 at 16:33
  • you should create `VideoStream(cam)` only once - before `while True` – furas Aug 23 '20 at 19:11
  • `Thread` needs function's name without `()` and arguments - and it will later use `()` to start it. If you have arguments then you need `(target=start_vlez, args=(cam_izlez,))`. In your current code you start function in current thread so it has to wait for the end to run another function. – furas Aug 23 '20 at 19:14

1 Answers1

1

target= in Thread needs function's name without () and arguments - and it will later use () to start it.

Your current code doesn't run functions in threads but it works like

result = start_vlez(cam_izlez)
result1 = start_izlez(cam_vlez)

t = threading.Thread(target=result)
t1 = threading.Thread(target=result1)

t.start()
t2.start()

so it runs first function in main thread and wait for it ends. And next it runs second function also in main thread and wait for it ends. And after that it tries to use Thread

If you have arguments then you need use function's name without () in target=and use tuple with arguments in args=

t = threading.Thread(target=start_vlez, args=(cam_izlez,))

t1 = threading.Thread(target=start_izlez, args=(cam_vlez,))

args= needs tuple even for single argument so I use , in (cam_izlez,) and (cam_vlez,)

furas
  • 134,197
  • 12
  • 106
  • 148
  • Wow , thanks , it really worked ,i managed to call the two fuinctions in threads and thank you for that a lot , but now i am getting an error File "/home/anpr/anaconda3/envs/tf/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 73, in symbolic_fn_wrapper if _SYMBOLIC_SCOPE.value: AttributeError: '_thread._local' object has no attribute 'value' – Ivanh23 Aug 23 '20 at 19:51
  • do you think its because they are using the same model ? – Ivanh23 Aug 23 '20 at 19:52
  • 1
    I don't know - create new question and put FULL error message (starting at word `Traceback`). I would first check how it works only with first thread and later I would check how it works only with second thread. Maybe you have some mistake which has nothing to do with two threads. If both will works correctly then you can try to load model two times. Simply: first try, next ask. – furas Aug 23 '20 at 20:09
  • Okey , Thank youuuu a lot for the help – Ivanh23 Aug 23 '20 at 20:29