コード例 #1
0
    def center(self, color):
        '''
            This method centers the screen to an specific color payload. It moves the rover
                depending on the position of the payload on the screen.
        :param color: color = {1,2,3}. Color that we want the system to track.
            1 - Blue Range
            2 - Green Range
            3 - Red Range
        :return:
        '''
        colorSelection = self.__colorList[color]  #choose the color from the list
        cvcondition = Tracking.track(colorSelection[0], colorSelection[1]) #getting current state of the target in the frame

        print("Centering")
        while cvcondition != 2: #is going to be trying to center until it is in the middle

            if(cvcondition < 2):#left of center frame
                self.__tracks.turnleft()
                print("Moving left")

            elif(cvcondition > 2):#right of center frame
                self.__tracks.turnright()
                print("Moving Right")

            self.__tracks.stoptracks()
            cvcondition = Tracking.track(colorSelection[0], colorSelection[1])
        print("CENTERED!!!")
        return
コード例 #2
0
def mainLoop(_set, _series, _batch):

    global EMAIL_PACKAGE

    if not START_DATE and not END_DATE:  updateStartAndEndDates()

    print("\n>>> retrieving packages for:")
    print(">>>    CompanyID     =", COMPANY_ID)
    print(">>>    ShippedMethod =", SHIPPED_METHOD)
    print(">>>    StartDate     =", START_DATE)
    print(">>>    EndDate       =", END_DATE)

    carrier = getCarrier()

    packages = getPackages()
    packages = filterMultiTrackingNums(packages)
    print("\n>>> retrieved", len(packages), "packages")

    if not _batch:

        set_format = [_set, _series, COMPANY_ID, SHIPPED_METHOD]
        set_print = "\n>>> set = {} of {} ... {}, {}".format(*set_format)
        for_print = ">>> PackageShipmentID = {} / TrackingNumber = {}"

        for i, (package_shipment_id, tracking_number) in enumerate(packages):

            print(set_print)
            print(">>> package =", i + 1, "of", len(packages))
            print(for_print.format(package_shipment_id, tracking_number))

            if   carrier == 'UPS':      vitals = Tracking.getSingleUpsVitals(tracking_number)
            elif carrier == 'USPS':     vitals = Tracking.getSingleUspsVitals(tracking_number)
            elif carrier == 'DHL':      vitals = Tracking.getSingleDhlVitals(tracking_number)
            elif carrier == 'FedEx':    vitals = Tracking.getSingleFedExVitals(tracking_number)

            if vitals == 'error':
                print(">>>     - BAD RESPONSE ... not updating ... moving on ... \\_(**)_/")
                error_pack = [COMPANY_ID, SHIPPED_METHOD, package_shipment_id, tracking_number]
                EMAIL_PACKAGE['errors'] += [error_pack]
                continue
            print(">>>     - vitals retrieved")

            updateTableArrival(package_shipment_id, tracking_number, vitals)
            print(">>>     - tblArrival updated")

    elif _batch:
        if carrier == 'DHL':

            # Modify 'packages' to fit legacy 'DhlBatching' format.
            batch_packs = { pack[1]: pack[0] for pack in packages }
            DhlBatching.batchProcessing(batch_packs, COMPANY_ID)

            """ NEED TO ...  Append to EMAIL_PACKAGE['errors'] within batch processing as well. """

        elif carrier == 'UPS':  pass
        elif carrier == 'USPS':  pass
        elif carrier == 'FedEx':  pass

    EMAIL_PACKAGE['totals'] += [[str(COMPANY_ID), SHIPPED_METHOD, str(len(packages))]]
コード例 #3
0
ファイル: __init__.py プロジェクト: blinkier/bitHopper
def add_work_unit(content, server, username, password):
    """
    Does wrapping and stores the submission
    """
    __patch()
    try:
        content = json.loads(content)
    except:
        return
    merkle_root = extract_merkle_recieved(content)
    if not merkle_root:
        return
    auth = (server, username, password)
    __store.add(merkle_root, auth)
    Tracking.add_getwork(server, username, password)
コード例 #4
0
ファイル: __init__.py プロジェクト: the-cc-dev/bitHopper
def add_work_unit(content, server, username, password):
    """
    Does wrapping and stores the submission
    """
    __patch()
    try:
        content = json.loads(content)
    except:
        return
    merkle_root = extract_merkle_recieved(content)
    if not merkle_root:
        return
    auth = (server, username, password)
    __store.add(merkle_root, auth)
    Tracking.add_getwork(server, username, password)
コード例 #5
0
ファイル: __init__.py プロジェクト: blinkier/bitHopper
def add_result(content, server, username, password):
    """
    Does wrapping and stores the result
    """
    __patch()

    try:
        content = json.loads(content)
    except:
        return

    result = extract_result(content)
    if result in [False]:
        Tracking.add_rejected(server, username, password)
    else:
        Tracking.add_accepted(server, username, password)
コード例 #6
0
ファイル: testFromVideo.py プロジェクト: yotamsali/Projecton
def TrackGarbage(im, up, down, left, right, max_index, s):
    counter = 2
    start = 2
    New_Template, Template_XY = im[up:down, left:right], (up, left)
    # save given Garbage
    cv2.imwrite(GARBAGE_PATH + str(1 + max_index) + ".jpg", New_Template)
    # Track loop
    while New_Template.shape[0] <= MAX_SIZE:
        im = s.getNext()
        if counter > start + 50:
            f, arr = matplotlib.pyplot.subplots(1, 1)
            arr.imshow(im, cmap='gray')  #, interpolation='nearest')
            matplotlib.pyplot.show()
            print("up, down, left, right in that order")
            up = int(input())
            down = int(input())
            left = int(input())
            right = int(input())
            New_Template, Template_XY = im[up:down, left:right], (up, left)
            cv2.imwrite(GARBAGE_PATH + str(counter + max_index) + ".jpg",
                        New_Template)
            start = counter
        else:
            New_Template, Template_XY = Tracking.Track(im, New_Template,
                                                       Template_XY)
            cv2.imwrite(GARBAGE_PATH + str(counter + max_index) + ".jpg",
                        New_Template)
        counter += 1
コード例 #7
0
def main():
  args = getArguments()
  camera = None
  if args.videofile:
    camera = Camera.VideoCamera(args.videofile)
  else:
    camera = Camera.getCamera()
  drone = Tracking.Drone()

  cv2.namedWindow('frame')

  def run():
    while True:
      frames = camera.getFrames()
      if frames is None:
        return
      frame = cv2.resize(frames['color'], (0,0), fx=0.5, fy=0.5)
      cv2.imshow('frame', frame)

      key = cv2.waitKey(1)
      if key == ord('q'):
        break
      del frame
      gc.collect()


  try:
    run()
  except Exception as e:
    print e
  finally:
    camera.stop()
コード例 #8
0
ファイル: __init__.py プロジェクト: the-cc-dev/bitHopper
def add_result(content, server, username, password):
    """
    Does wrapping and stores the result
    """
    __patch()
    
    try:
        content = json.loads(content)
    except:
        return
    
    result = extract_result(content)
    if result in [False]:
        Tracking.add_rejected(server, username, password)
    else:
        Tracking.add_accepted(server, username, password)
コード例 #9
0
 def seek(self, color):
     '''
         This method seeks a payload with an specific color. It moves the rover
             until it finds the payload.
     :param color: color = {1,2,3}. Color that we want the system to track.
         1 - Blue Range
         2 - Green Range
         3 - Red Range
     :return:
     '''
     colorSelection = self.__colorList[color]  #choose the color from the list
     cvcondition = Tracking.track(colorSelection[0], colorSelection[1]) #getting current state of the target in the frame
     print("Seeking object")
     while (cvcondition == 0):
         self.__tracks.turnright()
         print("Moving Right")
         cvcondition = Tracking.track(colorSelection[0], colorSelection[1])
     self.__tracks.stoptracks()
     print("Found!!!")
     return 
コード例 #10
0
def uploadFile():

    # GET test response
    if request.method == 'GET':
        return 'Successfully pinged server.', 200

    # POST route to accept
    elif request.method == 'POST':

        # Check if POST request has file attached
        if 'file' not in request.files:
            return 'ERROR: No file attached.', 400

        # Get file
        file = request.files['file']

        # Check for empty username
        if file.filename == '':
            return 'ERROR: No file attached.', 400

        # Check if test ID is included in form
        if 'test_id' not in request.form:
            return 'ERROR: Test identifier not specified', 400

        # Get test ID
        testID = request.form['test_id']

        # Check for file overwrite
        folderpath = os.path.join(app.config['UPLOAD_FOLDER'], str(testID))
        filepath = os.path.join(folderpath, file.filename)
        if os.path.exists(filepath):
            return 'ERROR: File already exists with that name.', 403

        # Chcek if directory exists for test ID, and create if not
        if not os.path.exists(folderpath):
            os.makedirs(folderpath)

        # Otherwise save to file
        file.save(filepath)

        try:
            Tracking.ProcessFiles(str(testID))
        except Exception as e:
            # Remove failed file
            os.remove(filepath)

            # Save error message
            errorMsg = traceback.format_exc()
            outputMsg = ('ERROR: Upload accepted but could not process file.\n'
                         'See Python error traceback below:\n\n')
            return outputMsg + errorMsg, 500

        return 'File successfully processed!', 201
コード例 #11
0
    def findRamp(self, colorToFollow, colorToStop):
        glitchfilter = 0
        #While the payload has not yet been detected
        done = False
        colorSelection = self.__colorList[colorToStop]

        while not done:
            self.__tracks.forward()
            print("moving forward")
            self.center(colorToFollow)

            cvcondition = Tracking.track(colorSelection[0], colorSelection[1])
            if(cvcondition != 0):
                done = True

            
        self.__tracks.stoptracks()
        return
コード例 #12
0
ファイル: DhlBatching.py プロジェクト: LangII/TrackingStats
def getDhlData(batch):
    """
    input:  batch =     Dictionary of entries from 'disk_data' dictionary.  Dhl website only allows 10 entries to be
                        submitted at a time.
    output: Return 'dhl_data' as list of dictionaries compiled from dhl website.  Data collected from website includes
            'time_stamp', 'message', 'tracking_num', and 'shipping_id'.  Each dictionary entry (of collected data)
            corresponds to each entry from the 'batch' parameter.
    """
    # Initiate while-loop conditional variable.
    getDhlData_attempts = 0
    # while-loop used to track and limit number of attempts made to connect to dhl website.
    while getDhlData_attempts < 10:
        # Bool variable used to determine direction after while loop (whether connection was success or not).
        success = False

        try:
            # Get 'tracking' keys from parameter dict 'batch'.
            tracking = list(dict.keys(batch))
            # Build output parameters for retrieving dhl data.
            parameters = {'access_token': Tracking.getDhlKey(), 'client_id': DHL_CLIENT_ID, 'number': tracking}
            getDhlData_url = 'https://api.dhlglobalmail.com/v2/mailitems/track'
            # Request data from dhl website.
            response = requests.get(getDhlData_url, params=parameters, timeout=5)
            # Another embedded error catch.  Most common 'status_code' returned is 400:  Bad client request.
            if response.status_code != 200:
                print("  >>>  exception caught ... status_code 400 (bad client request) ...")
                return ('exception', 'status_code 400 (bad client request)')

            # If connection is successful break from loop and proceed with script.
            success = True
            break

        # Series of known reoccuring exceptions.
        except requests.exceptions.ConnectionError:
            print("  >>>  dhl connection error (requests.exceptions.ConnectionError) ...")
        except requests.exceptions.ReadTimeout:
            print("  >>>  dhl connection error (requests.exceptions.ReadTimeout) ...")
        except requests.exceptions.RequestsException:
            print("  >>>  dhl connection error (requests.exceptions.RequestsException) ...")
        # A catch all in case there are any more irregular exceptions (no others have yet to be seen).
        except:
            print("  >>>  dhl connection error (other) ...")

        # Some final procedures before looping again.  Along with an update to 'getDhlData_attempts'.
        getDhlData_attempts += 1
        print("  >>>  attempting to reconnect ...\n")
        time.sleep(3)

    # Bad connection catch.  If there are repeated dhl connection errors, then the while-loop breaks without triggering
    # 'success = True', thereby getting caught here and exiting program.
    if not success:  print("  >>>  having repeated issues with dhl connection ... try again later  :("), exit()

    # Convert 'response' to readable dict through json.  Sometimes dhl returns from request an "Expecting ',' delimiter"
    # error.  If exception is caught return "exception" to collect 'tracking-nums' from bad batch.
    try:  response = response.json()
    except json.decoder.JSONDecodeError:
        print("  >>>  exception caught ... json.decoder.JSONDecodeError ...")
        return ('exception', 'json.decoder.JSONDecodeError')

    # Start the data filter, only need contents from 'mailItems'.
    raw_data = response['data']['mailItems']

    # Initiate return variable 'dhl-data' as list of dictionaries of filtered data.  Then start for-loop to handle each
    # entry of 'raw_data' at a time.
    dhl_data = []
    for each in raw_data:
        # Initiate data collection variable to be appended to return variable 'dhl_data'.
        each_dhl_data = {}

        # ...  Note:  Refering to "['events'][0]" when declaring 'time_stamp' and 'message' because the ['events'] list
        # is in chronological order and we always want the data from the most recent event.

        # Get 'time_stamp' from 'date' and 'time' entries in 'raw_data'.
        each_dhl_data['time_stamp'] = each['events'][0]['date'] + ' ' + each['events'][0]['time']

        # Get 'message' from 'raw_data'.
        each_dhl_data['message'] = each['events'][0]['description']
        # Patch to add 'location' to 'message' per Victoria's request.  DL (2019-09-09)
        location = each['events'][0]['location']
        if location != '':
            location = ''.join( l for l in location if l not in ('"', "'") and ord(l) < 128 )
            each_dhl_data['message'] += ' at ' + location

        # Get 'tracking_num' from 'raw_data'.  Have to test 3 different locations for dhl's storage location of
        # 'tracking_number'.
        if str(each['mail']['dspNumber']) in tracking:
            each_dhl_data['tracking_num'] = str(each['mail']['dspNumber'])
        elif str(each['mail']['customerConfirmationNumber']) in tracking:
            each_dhl_data['tracking_num'] = str(each['mail']['customerConfirmationNumber'])
        elif str(each['mail']['overlabeledDspNumber']) in tracking:
            each_dhl_data['tracking_num'] = str(each['mail']['overlabeledDspNumber'])

        # Get 'shipping_id' from 'raw_data'.
        each_dhl_data['shipping_id'] = batch[each_dhl_data['tracking_num']]

        # BLOCK ...  Patch when implemented into 'TrackingStats'.  DL (2020-02-26)
        # Minor adjustment, remove commas from 'message'.
        each_dhl_data['message'] = each_dhl_data['message'].replace(',', '')
        # Get 'delivered' from 'raw_data'.
        if each['events'][0]['description'] == 'DELIVERED':     each_dhl_data['delivered'] = 'Y'
        else:                                                   each_dhl_data['delivered'] = 'N'

        # print(each_dhl_data)
        # exit()

        dhl_data.append(each_dhl_data)

    return dhl_data
コード例 #13
0
from Mapping import *
from PointCloud import *


def signal_handler(signal, frame):
    print('Ctrl-C pressed')
    sys.exit(0)


signal.signal(signal.SIGINT, signal_handler)
print('Ctrl-C to close program')

# initializations
model = Camera()  # camera model
ds_cam = DatasetCamera()
tr = Tracking()  # tracking module
mp = Mapping()  # mapping module
pc = PointCloud()  # point cloud
rospy.init_node('cloud_stream', anonymous=True)

# video capture object
# cap = cv2.VideoCapture(0)

for im_id in xrange(108):

    im = cv2.imread('./dataset/image_00/data/' + str(im_id).zfill(10) + '.png',
                    0)

    if im_id == 0:
        tr.kp_old = detector.detect(im)
        tr.kp_old = np.array([x.pt for x in tr.kp_old], dtype=np.float32)
コード例 #14
0
ファイル: habitat.py プロジェクト: armandok/pySLAM-D

def pc_input():
    key_ = input()
    if len(key_) > 1:
        key_ = key_[0]
    return key_


def rand_input():
    key_ = np.random.choice(['w', 'a', 'd'])
    return key_


simulator = Simulator()
system = Tracking()

flag_random = False
flag_kbhit = False
plt.figure()

if flag_random:
    input_func = rand_input
elif flag_kbhit:
    kb = KBHit()
    input_func = kb_input
else:
    input_func = pc_input

kf_counter = 0
コード例 #15
0
old_frame = cv.resize(old_frame1, None, fx=ratio, fy=ratio)
# old_frame_c = old_frame.copy()
means = []
pts1 = Drawing.Draw(old_frame)

old_gray, old_gray1, temp, gray_orig = Preprocessing.Track_init(
    old_frame, pts1)
#   old_gray = frame rescaled, processed, with edge mask
#   old_gray1 = frame rescaled, processed, with edge mask and with mask over ROI
#   temp = frame rescaled, processed, cropped over boundingbox of ROI. Template for model
#   gray_orig = frame rescaled, processed
Buffer, Buffer_images = BufferStartUp.start(Buffer, Buffer_images, temp)
# Buffer = buffer data
# Buffer_images = list of model images

p0, pts = Tracking.init(old_gray1, pts1)  # , gray_orig, old_gray, old_frame_c)
# p0 = kaze features found
# pts = input argument of vertices/points of the contour is reshaped and parsed for numpy

totalF = len(
    p0)  # total number of features found/detected at (re-)initialization

Score = 1  # jaccard score of most recent (re-)initialization
threshR = 10  # tracker ransacReprojThreshold
jac = []  # jaccard score history
trackers = []  # list of active trackers
img_array = []  # not used
times = []  # execution times
tracktime = 0

while (1):
コード例 #16
0

if __name__ == '__main__':
    print("Reading file ...")

    X_df, y_df = read_data(filename)

    #no training, use all sample for test:
    skf = ShuffleSplit(len(y_df), n_iter=1, test_size=0.99, random_state=57)
    print("Training file ...")
    for train_is, test_is in skf:
        print '--------------------------'

        # tracker = Tracking.ClusterDBSCAN(eps=0.004, rscale=0.001)
        # use dummy clustering
        tracker = Tracking.HitToTrackAssignment()

        X_train_df = X_df.iloc[train_is].copy()
        y_train_df = y_df.iloc[train_is].copy()
        X_test_df = X_df.iloc[test_is].copy()
        y_test_df = y_df.iloc[test_is].copy()

        # Temporarily bypass splitting (need to avoid shuffling events)
        X_test_df = X_df.copy()
        y_test_df = y_df.copy()

        tracker.fit(X_train_df.values, y_train_df.values)
        y_predicted = tracker.predict(X_test_df.values)

        # Score the result
        total_score = 0.
コード例 #17
0
frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))  #get videos frames count
print(frames)
boxes = []
framess = []
GenderAcc = [0, 0]
RecAcc = [0, 0, 0, 0, 0, 0, 0]
first = 1
for i in range(frames):
    flag, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # convert image to gray
    #if first frame and have faces Create Multi tracking

    if (first == 1):
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        if (len(faces) > 0):
            T.CreateMultiTracking(frame, faces)
            first = 0
    elif (
            i % 30 == 0
    ):  #each 30 frame run Face detection and recognition and clear previous trackers and create new trackers to correct any mistake  in the previous framees
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        T.Multitracker.clear()
        T.colors.clear()
        T.Paths.clear()
        T.CreateMultiTracking(frame, faces)

    for i in range(len(T.Multitracker)):
        success, ObjectBox = T.Multitracker[i].update(frame)
        T.Paths[i].append(ObjectBox)

        if (success):
コード例 #18
0
ファイル: main.py プロジェクト: riv5181/VOLDEMORT
#Get PC's IP. Takes few seconds to obtain. Will delay startup of VOLDEMORT.
def getIPAddress(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(
        fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', ifname[:15]))[20:24])


mainIP = str(getIPAddress(device1))

cur.execute("SELECT MAX(cycle_time) FROM cycle")
obtainedcurID = cur.fetchall()
Tracking.setCurrCycleTime(int(obtainedcurID[0][0]) + 1)

try:
    while True:
        timeStart = strftime("%m-%d-%Y %H:%M:%S", localtime())
        packets = Preprocessor.obtainPackets(device1, maxTime1)
        timeEnd = strftime("%m-%d-%Y %H:%M:%S", localtime())

        print('BEFORE FILTER: ' + str(len(packets)))
        blah1 = len(packets)
        packets = Preprocessor.filterObtainedPackets(packets, mainIP, network)
        print('AFTER FILTER: ' + str(len(packets)))
        blah2 = len(packets)
        noFPackets = packets
        print(' ')
コード例 #19
0
    def callback(self,data):
        global initial_flag
        global contour
        #global contour1
        global Buffer
        global Buffer_images
        global old_gray
        global totalF
        global Score
        global p0
        global pts
        global jac
        global trackers
        global threshR
        global pts1
        global temp
        #cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
        old_frame1 = self.bridge.imgmsg_to_cv2(data, "bgr8")
        #plt.imshow(old_frame1)
        #plt.show()
        if not initial_flag:
            
######################################################### REFERENCE FOR TABBING
            
            old_frame = cv.resize(old_frame1, None, fx=ratio, fy=ratio)
            #plt.imshow(old_frame)
            #plt.show()
            #old_frame_c = old_frame.copy()
            means = []
            pts1 = contour #Drawing.Draw(old_frame)
            print("PTS 1 : ")
            #print(pts1)
            print("PTS CONTOUR1 : ")
            #print(contour1)
            #print("=========================================")
            #print(pts1)
            #print("=========================================")

            old_gray, old_gray1, temp, gray_orig = Preprocessing.Track_init(old_frame, contour1)
            #   old_gray = frame rescaled, processed, with edge mask
            #   old_gray1 = frame rescaled, processed, with edge mask and with mask over ROI
            #   temp = frame rescaled, processed, cropped over boundingbox of ROI. Template for model
            #   gray_orig = frame rescaled, processed

            #plt.imshow(old_gray1)
            #plt.show()
            Buffer, Buffer_images = BufferStartUp.start(Buffer, Buffer_images, temp)
            # Buffer = buffer data
            # Buffer_images = list of model images
            
            p0, pts = Tracking.init(old_gray, pts1) # p0 are detected features, pts are vertices of the polygons
            # p0 = kaze features found
            # pts = input argument of vertices/points of the contour is reshaped and parsed for numpy

            #print(p0)
            #print(pts)  
      
            #############   Initialize various variables to be used
            #############################################################################################################


            totalF = len(p0)  # total number of features found/detected at (re-)initialization

            Score = 1  # jaccard score of most recent (re-)initialization
            threshR = 10  # tracker ransacReprojThreshold
            jac = []  # jaccard score history
            trackers = []  # list of active trackers
            img_array = []  # not used
            times = []  # execution times
            initial_flag = True
        else:
            ##########################################   2   ############################################################
            #############   Just a small test to see if the input is an image, and if it is non NULL
    	    

            try:
                frame1 = cv.resize(old_frame1, None, fx=ratio, fy=ratio)
                # resize by predefined ratio
                #frame_orig = frame1.copy()
                # copy
            except:
                print("")

            start = time.time()
            frame_gray, frame_o, frame_proc, temp = Preprocessing.Track(frame1)
            #   frame_gray = frame rescaled, processed, with edge mask
            #   frame_o = original input frame is being sent back
            #   frame_proc = frame rescaled, processed
            #   temp = frame rescaled, processed, cropped over boundingbox of ROI. Template for model. Returned regardless of edge.

            ######### This function called "Tracking.do" does the tracking and reinitialization. There is a LOT of code inside.
            # What Trackers.do returns
            # img = most recent acquired frame with tracked contour drawn on top
            # p0 = kaze features found
            # pts = input argument of vertices/points of the contour is reshaped and parsed for numpy
            # Buffer = buffer data
            # Buffer_images = list of model images
            # TotalF = total number of features found/detected at (re-)initialization
            # Score = jaccard score of most recent (re-)initialization
            # jac = jaccard score history
            # trackers = trackers that are active and have been tracked from last frame to current frame
            img, p0, pts, Buffer, Buffer_images, totalF, Score, jac, trackers = \
                Tracking.do(old_gray, frame_gray, frame_proc, temp, Buffer, Buffer_images, frame_o, totalF, Score, p0, pts,
                            jac, trackers, threshR)
            # Arguments used for Tracking.do
            # old_gray = image/frame from previous loop cycle. It is frame_gray from old loop
            # frame_gray = current mose recent frame rescaled, processed, with edge mask
            # frame_proc = current most recent frame rescaled, processed
            # temp = current most recent frame rescaled, processed, cropped over boundingbox of ROI. Template for model. Returned regardless of edge.
            # Buffer = buffer data
            # Buffer_images = list of model images
            # frame_o = current most recent original input frame is being sent back
            # totalF = total number of features detected at (re-)intialization. Used as reference to see how much of the initial trackers have been lost/found
            # Score = jaccard score of most recent (re-)initialization
            # p0 = kaze features found
            # pts = input argument of vertices/points of the contour is reshaped and parsed for numpy
            # jac = jaccard score history
            # trackers = trackers that have been tracked to the last frame, from the one before it. Active trackers that we want to try to find in this loop
            # threshR = tracker ransacReprojThreshold

    ##########################################   3   ############################################################



    #############################################################################################################

    #############################################################################################################
    ###########     Just computes current fps, and prints it on the image.
            t = 1/(time.time() - start)
            cv.putText(img, 'FPS: ' + str(t), (0, 30), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

            old_gray = frame_gray.copy()

            msg = Int16MultiArray()
            msg.data = np.reshape(pts, len(pts) * len(pts[0][0]))  # , order='F')
            '''
            # preparation of point message to be published

            a1l = len(pts)
            a1l0 = len(pts[0][0])
            a1 = np.reshape(pts, a1l * a1l0)  # , order='F')
            msg.data = a1

            # This is almost always zero there is no empty padding at the start of your data
            msg.layout.data_offset = 0
            # create two dimensions in the dim array
            msg.layout.dim = [MultiArrayDimension(), MultiArrayDimension()]
            # dim[0] is the vertical dimension of your matrix
            msg.layout.dim[0].label = "axes"
            msg.layout.dim[0].size = a1l0
            msg.layout.dim[0].stride = a1l * a1l0
            # dim[1] is the horizontal dimension of your matrix
            msg.layout.dim[1].label = "vertices"
            msg.layout.dim[1].size = a1l
            msg.layout.dim[1].stride = a1l
            '''


        #except CvBridgeError as e:
        #    print(e)



        try:
            self.contour_pub.publish(msg)
            self.image_pub.publish(self.bridge.cv2_to_imgmsg(img, "bgr8"))
        except CvBridgeError as e:
            print(e)
コード例 #20
0
ファイル: main.py プロジェクト: j449li/Scribbler-Police
direction = ""

SPEED_LIMIT = 8

def sweep(direction):
    INNER_MOTOR = 0.57   #constants, test-proven at Nov.24th
    TIME = 3.7
    
    if direction == "RIGHT":
        motors(-1,-1*INNER_MOTOR)
        time.sleep(TIME)
        stop()
    elif direction == "LEFT":
        motors(-1*INNER_MOTOR,-1)
        time.sleep(TIME)
        stop()

while speed < SPEED_LIMIT:
    speed,direction=CalculateSpeed.testSpeed()
    if speed > SPEED_LIMIT:
        print "Speeding car detected at: " + str(speed) + "cm per second."
    else:
        print "Car detected at: " + str(speed) + "cm per second."
    
    
sweep(direction)

Tracking.track()
    
    
コード例 #21
0
ファイル: label_Images.py プロジェクト: yotamsali/Projecton
 cooAr = getNewImageCoo(refPt)
 #these are just the lines from 'g', copied. saves the firest image
 save_twenty_random(cooAr, image)
 diff = [0, 0]
 template = image[cooAr[0][Y]:cooAr[1][Y], cooAr[0][X]:cooAr[1][X]]
 xy = (cooAr[0][Y], cooAr[0][X])
 base = pictures.index(pictureName)
 counter = 1
 #saves the picture so it will be possible to return to it
 oldImage = clone.copy()
 while True:
     #reads the next image in the list
     image = cv2.imread(path + "/" + pictures[base + counter])
     clone = image.copy()
     #delegates to tracking
     useless, xy, template, diff = Tracking.Track(
         image, template, xy, diff)
     #clones so the rectangle will not be saved
     imClone = image[:].copy()
     cv2.rectangle(
         imClone, (xy[1], xy[0]),
         (xy[1] + template.shape[1], xy[0] + template.shape[0]),
         (0, 255, 0), 2)
     cv2.imshow("image", imClone)
     key = cv2.waitKey(100) & 0xFF
     #stops the process and returns to the first image, to choose new stoplight
     if key == ord('s'):
         image = oldImage
         cv2.imshow("image", image)
         break
     #pauses the process to let the user decide on new borders
     elif key == ord('p'):