コード例 #1
0
        for i, img_path in enumerate(imgs_paths):

            print('\tScanning %s' % img_path)

            bname = basename(splitext(img_path)[0])

            R, (width, height) = detect(ocr_net,
                                        ocr_meta,
                                        bytes(img_path, encoding='utf-8'),
                                        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])

                with open('%s/%s_str.txt' % (output_dir, bname), 'w') as f:
                    f.write(lp_str + '\n')

                print('\t\tLP: %s' % lp_str)

            else:

                print('No characters found')

    except:
        traceback.print_exc()
コード例 #2
0
                f.write(bbox_mess)
                print("\t" + str(bbox_mess).strip())

        print("=> predict result of %s:" % file_name)
        predict_result_path = os.path.join(predicted_dir_path, str(num) + ".txt")
        # need to check the data dims
        image_size = np_rgb_img.shape[:2]
        image_data = utils.image_preprocess(np.copy(np_rgb_img), [INPUT_SIZE, INPUT_SIZE])
        image_data = image_data[np.newaxis, ...].astype(np.float32)
        # need to investigate the following part ---from here
        pred_bbox = model.predict(image_data)
        pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]
        pred_bbox = tf.concat(pred_bbox, axis=0)
        # ---ends here
        bboxes = utils.postprocess_boxes(pred_bbox, image_size, INPUT_SIZE, cfg.TEST.SCORE_THRESHOLD)
        bboxes = utils.nms(bboxes, cfg.TEST.IOU_THRESHOLD, method="nms")

        if cfg.TEST.DETECTED_IMAGE_PATH is not None:
            image = utils.draw_bbox(np_rgb_img, bboxes)
            cv2.imwrite(cfg.TEST.DETECTED_IMAGE_PATH + file_name, image)

        with open(predict_result_path, "w") as f:
            for bbox in bboxes:
                coord = np.array(bbox[:4], dtype=np.int32)
                score = bbox[4]
                class_idx = int(bbox[5])
                class_name = CLASSES[class_idx]
                score = "%.4f" % score
                xmin, ymin, xmax, ymax = list(map(str, coord))
                bbox_mess = " ".join([class_name, score, xmin, ymin, xmax, ymax]) + "\n"
                f.write(bbox_mess)
コード例 #3
0
ファイル: license-plate-ocr.py プロジェクト: wjfields/Scout
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print("Received created event - %s." % event.src_path)
            try:
                img_path = event.src_path

                print('\tScanning %s' % img_path)

                bname = basename(splitext(img_path)[0])

                R, (width, height) = detect(ocr_net,
                                            ocr_meta,
                                            img_path,
                                            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])

                    # change line below if you'd like a range (6 OR 7 character LPs, however false readings increase dramatically)
                    if 7 <= len(lp_str) <= 7:

                        print('\t\tLP: %s' % lp_str)
                        # get the timestamp based off of the frameImg filename
                        file_name = os.path.basename(
                            event.src_path).split('.')[0]
                        video_date = file_name.split('_')[0]
                        print(video_date)
                        camera_location = file_name.split('-')[-2]
                        print(camera_location)
                        video_time = '-'.join(
                            file_name.split('_')[1].split('-')[0:3])
                        print(video_time)
                        datetime_string = '{} {}'.format(
                            video_date, video_time)
                        print(datetime_string)
                        video_start_time = datetime.datetime.strptime(
                            datetime_string, '%Y-%m-%d %H-%M-%S').timestamp()
                        print(video_start_time)
                        frame_time_seconds = (round(
                            int(file_name.split('-')[-1].split('_')[0]) / 4) -
                                              1)
                        if frame_time_seconds < 0:
                            frame_time_seconds = 0
                        print(frame_time_seconds)
                        tz = pytz.timezone('America/Los_Angeles')
                        start_time_seconds = datetime.datetime.fromtimestamp(
                            video_start_time, tz)
                        print(start_time_seconds)
                        print(int(start_time_seconds.strftime("%s")))
                        detection_time = (
                            int(start_time_seconds.strftime("%s")) +
                            frame_time_seconds)
                        print(detection_time)

                        matching_poll = db.polls.find_one(
                            {"unixTS": detection_time})
                        if matching_poll:
                            print(matching_poll)
                            existing_plate = db.plates.find_one(
                                {"plateContent": lp_str})
                            if existing_plate:
                                post_data = {
                                    'plateContent':
                                    lp_str,
                                    'ts':
                                    detection_time,
                                    'cameraLocation':
                                    camera_location,
                                    'pollID':
                                    matching_poll['_id'],
                                    'location':
                                    matching_poll['location'],
                                    'driveID':
                                    matching_poll['driveID'] or undefined,
                                    'speed':
                                    matching_poll['speed'],
                                    'power':
                                    matching_poll['power'],
                                    'heading':
                                    matching_poll['heading'],
                                    'status':
                                    matching_poll['status'],
                                    'detectionImgPath':
                                    event.src_path,
                                    'plateID':
                                    existing_plate['_id'],
                                    'vehicleImgPath':
                                    '/tesladrive/detections/vehicles/%s.png' %
                                    '_'.join(file_name.split('_')[:-1]),
                                    'secondsIntoVideo':
                                    frame_time_seconds,
                                    'videoFileName':
                                    '/tesladrive/backups/RecentClips/%s.mp4' %
                                    ('-'.join('_'.join(
                                        file_name.split('_')[:-2]).split('-')
                                              [:-1]))
                                }

                                result = plate_detections.insert_one(post_data)
                                print('One plate detection added: {0}'.format(
                                    result.inserted_id))
                            else:
                                new_plate = {'plateContent': lp_str}
                                plate_id = db.plates.insert_one(
                                    new_plate).inserted_id
                                post_data = {
                                    'plateContent':
                                    lp_str,
                                    'ts':
                                    detection_time,
                                    'cameraLocation':
                                    camera_location,
                                    'pollID':
                                    matching_poll['_id'],
                                    'location':
                                    matching_poll['location'],
                                    'driveID':
                                    matching_poll['driveID'] or undefined,
                                    'speed':
                                    matching_poll['speed'],
                                    'power':
                                    matching_poll['power'],
                                    'heading':
                                    matching_poll['heading'],
                                    'status':
                                    matching_poll['status'],
                                    'detectionImgPath':
                                    event.src_path,
                                    'plateID':
                                    plate_id,
                                    'vehicleImgPath':
                                    '/tesladrive/detections/vehicles/%s.png' %
                                    '_'.join(file_name.split('_')[:-1]),
                                    'secondsIntoVideo':
                                    frame_time_seconds,
                                    'videoFileName':
                                    '/tesladrive/backups/RecentClips/%s.mp4' %
                                    ('-'.join('_'.join(
                                        file_name.split('_')[:-2]).split('-')
                                              [:-1]))
                                }

                                result = plate_detections.insert_one(post_data)
                                print('One detection added: {0}'.format(
                                    result.inserted_id))
                        else:
                            print("no matching poll found")
                    else:
                        print(
                            'plate detected too short, likely false positive: ',
                            lp_str)
                else:
                    print('No characters found')
            except:
                traceback.print_exc()
                sys.exit(1)
コード例 #4
0
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print("Received created event - %s." % event.src_path)
            try:
                img_path = event.src_path

                print('\tScanning %s' % img_path)

                bname = basename(splitext(img_path)[0])

                R, (width, height) = detect(ocr_net,
                                            ocr_meta,
                                            img_path,
                                            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])

                    # with open('%s/%s_str.txt' % (output_dir, bname), 'w') as f:
                    #         f.write(lp_str + '\n')
                    # change line below if you'd like a range (6 OR 7 character LPs, however false readings increase dramatically)
                    if 7 <= len(lp_str) <= 7:

                        print('\t\tLP: %s' % lp_str)
                        # get the timestamp based off of the frameImg filename
                        file_name = os.path.basename(
                            event.src_path).split('.')[0]
                        video_date = file_name.split('_')[0]
                        print(video_date)
                        camera_location = file_name.split('-')[-2]
                        print(camera_location)
                        # pre_video_time = file_name.split('_')[1]
                        video_time = '-'.join(
                            file_name.split('_')[1].split('-')[0:3])
                        print(video_time)
                        datetime_string = '{} {}'.format(
                            video_date, video_time)
                        print(datetime_string)
                        video_start_time = datetime.datetime.strptime(
                            datetime_string, '%Y-%m-%d %H-%M-%S').timestamp()
                        print(video_start_time)
                        frame_time_seconds = (round(
                            int(file_name.split('-')[-1].split('_')[0]) / 4) -
                                              1)
                        if frame_time_seconds < 0:
                            frame_time_seconds = 0
                        print(frame_time_seconds)
                        tz = pytz.timezone('America/Los_Angeles')
                        start_time_seconds = datetime.datetime.fromtimestamp(
                            video_start_time, tz)
                        print(start_time_seconds)
                        print(int(start_time_seconds.strftime("%s")))
                        detection_time = (
                            int(start_time_seconds.strftime("%s")) +
                            frame_time_seconds)
                        print(detection_time)

                        matching_poll = db.polls.find_one(
                            {"unixTS": detection_time})
                        if matching_poll:
                            print(matching_poll)

                            # does the poll have a geocodeID?
                            ####geocode temp fix, for testing. everything in prod will have a street value
                            reqHeaders = {'User-Agent': 'SDScout/0.0.1'}
                            reqGeoCode = requests.get(
                                url=
                                'https://nominatim.openstreetmap.org/reverse?format=json&lat={}&lon={}&zoom=18&addressdetails=1'
                                .format(
                                    matching_poll['location']['coordinates']
                                    [1], matching_poll['location']
                                    ['coordinates'][0]),
                                headers=reqHeaders)
                            print(reqGeoCode.json())
                            geoObject = reqGeoCode.json()
                            # reqGeoCode.json()[0]['year']

                            # now save geocode as it's own document for forward compatibility
                            new_geocode = {
                                'place_id':
                                geoObject['place_id'],
                                'osm_type':
                                geoObject['osm_type'],
                                'osm_id':
                                geoObject['osm_id'],
                                'location': {
                                    'type':
                                    "Point",
                                    'coordinates':
                                    [geoObject['lon'], geoObject['lat']]
                                },
                                'display_name':
                                geoObject['display_name'],
                                'road':
                                geoObject['address']['road'],
                                'city':
                                geoObject['address']['city'],
                                'county':
                                geoObject['address']['county'],
                                'state':
                                geoObject['address']['state'],
                                'postcode':
                                geoObject['address']['postcode'],
                                'country':
                                geoObject['address']['country'],
                                'country_code':
                                geoObject['address']['country_code'],
                                'boundingbox':
                                geoObject['boundingbox']
                            }
                            geocode_id = db.geocodes.insert_one(
                                new_geocode).inserted_id

                            # update the matching poll doc
                            db.Doc.update({"_id": matching_poll["_id"]}, {
                                "$set": {
                                    'street': geoObject['address']['road'],
                                    'city': geoObject['address']['city'],
                                    'geocodeID': geocode_id,
                                }
                            })
                            ####end temp geocode fix

                            existing_plate = db.plates.find_one(
                                {"plateContent": lp_str})

                            if existing_plate:
                                print('plate exists!', existing_plate)
                                post_data = {
                                    'plateContent':
                                    lp_str,
                                    'ts':
                                    detection_time,
                                    'cameraLocation':
                                    camera_location,
                                    'pollID':
                                    matching_poll['_id'],
                                    'location':
                                    matching_poll['location'],
                                    'driveID':
                                    matching_poll['driveID'] or undefined,
                                    'speed':
                                    matching_poll['speed'],
                                    'street':
                                    geoObject['address']['road'],
                                    'city':
                                    geoObject['address']['city'],
                                    'geocodeID':
                                    geocode_id,
                                    'power':
                                    matching_poll['power'],
                                    'heading':
                                    matching_poll['heading'],
                                    'status':
                                    matching_poll['status'],
                                    'detectionImgPath':
                                    event.src_path,
                                    'plateID':
                                    existing_plate['_id'],
                                    'vyear':
                                    existing_plate['vyear'],
                                    'vmake':
                                    existing_plate['vmake'],
                                    'vmodel':
                                    existing_plate['vmodel'],
                                    'vehicleImgPath':
                                    '/tesladrive/detections/vehicles/%s.png' %
                                    '_'.join(file_name.split('_')[:-1]),
                                    'secondsIntoVideo':
                                    frame_time_seconds,
                                    'videoFileName':
                                    '/tesladrive/Videos/%s.mp4' % ('-'.join(
                                        '_'.join(file_name.split('_')
                                                 [:-2]).split('-')[:-1]))
                                }

                                result = plate_detections.insert_one(post_data)
                                print('One plate detection added: {0}'.format(
                                    result.inserted_id))

                            else:
                                # we need to create a doc in PLATES first, get that objectID, then add the plateDetection

                                # but first we need to do the make model lookup
                                session = requests.Session()
                                session.headers.update({
                                    'User-Agent':
                                    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0'
                                })
                                reqMakeModel = session.get(
                                    'https://www.carfax.com/api/mobile-homepage-quickvin-check?plate={}&state={}'
                                    .format(lp_str, homestate))

                                newVyear = '-'
                                newVmake = '-'
                                newVmodel = '-'
                                print(reqMakeModel.json())

                                try:
                                    newVyear = reqMakeModel.json(
                                    )['quickVinResults'][0]['year']
                                    newVmake = reqMakeModel.json(
                                    )['quickVinResults'][0]['make']
                                    newVmodel = reqMakeModel.json(
                                    )['quickVinResults'][0]['model']
                                except:
                                    print('plate not found')

                                new_plate = {
                                    'plateContent': lp_str,
                                    'vyear': newVyear,
                                    'vmake': newVmake,
                                    'vmodel': newVmodel
                                }
                                plate_id = db.plates.insert_one(
                                    new_plate).inserted_id

                                # dont forget to add geocode

                                ####geocode temp fix, for testing. everything in prod will have a street value
                                # this is a parked detection so we need to get geocode
                                reqHeaders = {'User-Agent': 'SDScout/0.0.1'}
                                reqGeoCode = requests.get(
                                    url=
                                    'https://nominatim.openstreetmap.org/reverse?format=json&lat={}&lon={}&zoom=18&addressdetails=1'
                                    .format(
                                        matching_poll['location']
                                        ['coordinates'][1],
                                        matching_poll['location']
                                        ['coordinates'][0]),
                                    headers=reqHeaders)
                                print(reqGeoCode.json())
                                geoObject = reqGeoCode.json()
                                # reqGeoCode.json()[0]['year']

                                # now save geocode as it's own document for forward compatibility
                                new_geocode = {
                                    'place_id':
                                    geoObject['place_id'],
                                    'osm_type':
                                    geoObject['osm_type'],
                                    'osm_id':
                                    geoObject['osm_id'],
                                    'location': {
                                        'type':
                                        "Point",
                                        'coordinates':
                                        [geoObject['lon'], geoObject['lat']]
                                    },
                                    'display_name':
                                    geoObject['display_name'],
                                    'road':
                                    geoObject['address']['road'],
                                    'city':
                                    geoObject['address']['city'],
                                    'county':
                                    geoObject['address']['county'],
                                    'state':
                                    geoObject['address']['state'],
                                    'postcode':
                                    geoObject['address']['postcode'],
                                    'country':
                                    geoObject['address']['country'],
                                    'country_code':
                                    geoObject['address']['country_code'],
                                    'boundingbox':
                                    geoObject['boundingbox']
                                }
                                geocode_id = db.geocodes.insert_one(
                                    new_geocode).inserted_id

                                # now write the actual detection doc
                                print(
                                    'for reference, the filename of the video is '
                                )

                                post_data = {
                                    'plateContent':
                                    lp_str,
                                    'ts':
                                    detection_time,
                                    'cameraLocation':
                                    camera_location,
                                    'pollID':
                                    matching_poll['_id'],
                                    'location':
                                    matching_poll['location'],
                                    'driveID':
                                    matching_poll['driveID'] or undefined,
                                    'speed':
                                    matching_poll['speed'],
                                    'power':
                                    matching_poll['power'],
                                    'vyear':
                                    newVyear,
                                    'vmake':
                                    newVmake,
                                    'vmodel':
                                    newVmodel,
                                    'street':
                                    geoObject['address']['road'],
                                    'city':
                                    geoObject['address']['city'],
                                    'geocodeID':
                                    geocode_id,
                                    'heading':
                                    matching_poll['heading'],
                                    'status':
                                    matching_poll['status'],
                                    'detectionImgPath':
                                    event.src_path,
                                    'plateID':
                                    plate_id,
                                    'vehicleImgPath':
                                    '/tesladrive/detections/vehicles/%s.png' %
                                    '_'.join(file_name.split('_')[:-1]),
                                    'secondsIntoVideo':
                                    frame_time_seconds,
                                    'videoFileName':
                                    '/tesladrive/Videos/%s.mp4' % ('-'.join(
                                        '_'.join(file_name.split('_')
                                                 [:-2]).split('-')[:-1]))
                                }

                                result = plate_detections.insert_one(post_data)
                                print('One detection added: {0}'.format(
                                    result.inserted_id))

                                # update the matching poll doc
                                db.Doc.update({"_id": matching_poll["_id"]}, {
                                    "$set": {
                                        'street': geoObject['address']['road'],
                                        'city': geoObject['address']['city'],
                                        'geocodeID': geocode_id,
                                    }
                                })
                        else:
                            print(
                                "no matching poll found, entering a fake coordinate and marking to review later"
                            )
                            matching_poll = db.polls.find_one(
                                {"_id": ObjectId('5dabb930657f9d3e10178866')})
                            print(matching_poll)

                            # does the poll have a geocodeID?
                            ####geocode temp fix, for testing. everything in prod will have a street value
                            reqHeaders = {'User-Agent': 'SDScout/0.0.1'}
                            reqGeoCode = requests.get(
                                url=
                                'https://nominatim.openstreetmap.org/reverse?format=json&lat={}&lon={}&zoom=18&addressdetails=1'
                                .format(
                                    matching_poll['location']['coordinates']
                                    [1], matching_poll['location']
                                    ['coordinates'][0]),
                                headers=reqHeaders)
                            print(reqGeoCode.json())
                            geoObject = reqGeoCode.json()
                            # reqGeoCode.json()[0]['year']

                            # now save geocode as it's own document for forward compatibility
                            new_geocode = {
                                'place_id':
                                geoObject['place_id'],
                                'osm_type':
                                geoObject['osm_type'],
                                'osm_id':
                                geoObject['osm_id'],
                                'location': {
                                    'type':
                                    "Point",
                                    'coordinates':
                                    [geoObject['lon'], geoObject['lat']]
                                },
                                'display_name':
                                geoObject['display_name'],
                                'road':
                                geoObject['address']['road'],
                                'city':
                                geoObject['address']['city'],
                                'county':
                                geoObject['address']['county'],
                                'state':
                                geoObject['address']['state'],
                                'postcode':
                                geoObject['address']['postcode'],
                                'country':
                                geoObject['address']['country'],
                                'country_code':
                                geoObject['address']['country_code'],
                                'boundingbox':
                                geoObject['boundingbox']
                            }
                            geocode_id = db.geocodes.insert_one(
                                new_geocode).inserted_id

                            # update the matching poll doc
                            db.Doc.update({"_id": matching_poll["_id"]}, {
                                "$set": {
                                    'street': geoObject['address']['road'],
                                    'city': geoObject['address']['city'],
                                    'geocodeID': geocode_id,
                                }
                            })
                            ####end temp geocode fix

                            existing_plate = db.plates.find_one(
                                {"plateContent": lp_str})

                            if existing_plate:
                                print('plate exists!', existing_plate)
                                post_data = {
                                    'plateContent':
                                    lp_str,
                                    'ts':
                                    detection_time,
                                    'cameraLocation':
                                    camera_location,
                                    'pollID':
                                    matching_poll['_id'],
                                    'location':
                                    matching_poll['location'],
                                    'fakePoll':
                                    True,
                                    'driveID':
                                    ObjectId('5d3f848be08cfb4a873092db'),
                                    'speed':
                                    matching_poll['speed'],
                                    'street':
                                    geoObject['address']['road'],
                                    'city':
                                    geoObject['address']['city'],
                                    'geocodeID':
                                    geocode_id,
                                    'power':
                                    matching_poll['power'],
                                    'heading':
                                    matching_poll['heading'],
                                    'status':
                                    matching_poll['status'],
                                    'detectionImgPath':
                                    event.src_path,
                                    'plateID':
                                    existing_plate['_id'],
                                    'vyear':
                                    existing_plate['vyear'],
                                    'vmake':
                                    existing_plate['vmake'],
                                    'vmodel':
                                    existing_plate['vmodel'],
                                    'vehicleImgPath':
                                    '/tesladrive/detections/vehicles/%s.png' %
                                    '_'.join(file_name.split('_')[:-1]),
                                    'secondsIntoVideo':
                                    frame_time_seconds,
                                    'videoFileName':
                                    '/tesladrive/Videos/%s.mp4' % ('-'.join(
                                        '_'.join(file_name.split('_')
                                                 [:-2]).split('-')[:-1]))
                                }

                                result = plate_detections.insert_one(post_data)
                                print('One plate detection added: {0}'.format(
                                    result.inserted_id))

                            else:
                                # we need to create a doc in PLATES first, get that objectID, then add the plateDetection

                                # but first we need to do the make model lookup
                                session = requests.Session()
                                session.headers.update({
                                    'User-Agent':
                                    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0'
                                })
                                reqMakeModel = session.get(
                                    'https://www.carfax.com/api/mobile-homepage-quickvin-check?plate={}&state={}'
                                    .format(lp_str, homestate))

                                newVyear = '-'
                                newVmake = '-'
                                newVmodel = '-'
                                print(reqMakeModel.json())

                                try:
                                    newVyear = reqMakeModel.json(
                                    )['quickVinResults'][0]['year']
                                    newVmake = reqMakeModel.json(
                                    )['quickVinResults'][0]['make']
                                    newVmodel = reqMakeModel.json(
                                    )['quickVinResults'][0]['model']
                                except:
                                    print('plate not found')

                                new_plate = {
                                    'plateContent': lp_str,
                                    'vyear': newVyear,
                                    'vmake': newVmake,
                                    'vmodel': newVmodel
                                }
                                plate_id = db.plates.insert_one(
                                    new_plate).inserted_id

                                # dont forget to add geocode

                                ####geocode temp fix, for testing. everything in prod will have a street value
                                # this is a parked detection so we need to get geocode
                                reqHeaders = {'User-Agent': 'SDScout/0.0.1'}
                                reqGeoCode = requests.get(
                                    url=
                                    'https://nominatim.openstreetmap.org/reverse?format=json&lat={}&lon={}&zoom=18&addressdetails=1'
                                    .format(
                                        matching_poll['location']
                                        ['coordinates'][1],
                                        matching_poll['location']
                                        ['coordinates'][0]),
                                    headers=reqHeaders)
                                print(reqGeoCode.json())
                                geoObject = reqGeoCode.json()
                                # reqGeoCode.json()[0]['year']

                                # now save geocode as it's own document for forward compatibility
                                new_geocode = {
                                    'place_id':
                                    geoObject['place_id'],
                                    'osm_type':
                                    geoObject['osm_type'],
                                    'osm_id':
                                    geoObject['osm_id'],
                                    'location': {
                                        'type':
                                        "Point",
                                        'coordinates':
                                        [geoObject['lon'], geoObject['lat']]
                                    },
                                    'display_name':
                                    geoObject['display_name'],
                                    'road':
                                    geoObject['address']['road'],
                                    'city':
                                    geoObject['address']['city'],
                                    'county':
                                    geoObject['address']['county'],
                                    'state':
                                    geoObject['address']['state'],
                                    'postcode':
                                    geoObject['address']['postcode'],
                                    'country':
                                    geoObject['address']['country'],
                                    'country_code':
                                    geoObject['address']['country_code'],
                                    'boundingbox':
                                    geoObject['boundingbox']
                                }
                                geocode_id = db.geocodes.insert_one(
                                    new_geocode).inserted_id

                                # now write the actual detection doc
                                print(
                                    'for reference, the filename of the video is '
                                )

                                post_data = {
                                    'plateContent':
                                    lp_str,
                                    'ts':
                                    detection_time,
                                    'cameraLocation':
                                    camera_location,
                                    'pollID':
                                    matching_poll['_id'],
                                    'location':
                                    matching_poll['location'],
                                    'driveID':
                                    ObjectId('5d3f848be08cfb4a873092db'),
                                    'speed':
                                    matching_poll['speed'],
                                    'power':
                                    matching_poll['power'],
                                    'vyear':
                                    newVyear,
                                    'vmake':
                                    newVmake,
                                    'vmodel':
                                    newVmodel,
                                    'street':
                                    geoObject['address']['road'],
                                    'city':
                                    geoObject['address']['city'],
                                    'geocodeID':
                                    geocode_id,
                                    'heading':
                                    matching_poll['heading'],
                                    'status':
                                    matching_poll['status'],
                                    'detectionImgPath':
                                    event.src_path,
                                    'plateID':
                                    plate_id,
                                    'vehicleImgPath':
                                    '/tesladrive/detections/vehicles/%s.png' %
                                    '_'.join(file_name.split('_')[:-1]),
                                    'secondsIntoVideo':
                                    frame_time_seconds,
                                    'videoFileName':
                                    '/tesladrive/Videos/%s.mp4' % ('-'.join(
                                        '_'.join(file_name.split('_')
                                                 [:-2]).split('-')[:-1]))
                                }

                                result = plate_detections.insert_one(post_data)
                                print('One detection added: {0}'.format(
                                    result.inserted_id))

                                # update the matching poll doc
                                db.Doc.update({"_id": matching_poll["_id"]}, {
                                    "$set": {
                                        'street': geoObject['address']['road'],
                                        'city': geoObject['address']['city'],
                                        'geocodeID': geocode_id,
                                    }
                                })

                    else:
                        print(
                            'plate detected too short, likely false positive: ',
                            lp_str)
                        if os.path.exists(img_path):
                            os.remove(img_path)
                        # remove vehicle image as well
                        vehicleImgPath = img_path.rsplit('_', 1)[0].replace(
                            "plates", "vehicles") + '.png'
                        if os.path.exists(vehicleImgPath):
                            os.remove(vehicleImgPath)
                        print('removing {} and {}'.format(
                            img_path, vehicleImgPath))

                else:
                    print('No characters found')
                    if os.path.exists(img_path):
                        os.remove(img_path)
                    # remove vehicle image as well
                    vehicleImgPath = img_path.rsplit('_', 1)[0].replace(
                        "plates", "vehicles") + '.png'
                    if os.path.exists(img_path):
                        os.remove(vehicleImgPath)
                    print('removing {} and {}'.format(img_path,
                                                      vehicleImgPath))

            except:
                traceback.print_exc()
                sys.exit(1)

        elif event.event_type == 'modified':
            # Taken any action here when a file is modified.
            print("Received modified event - %s." % event.src_path)
コード例 #5
0
def iniciar_processamento_frame(img_path, sess, diretorio_saida,
                                diretorio_saida_img_bbox):
    original_image = cv2.imread(img_path)
    original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
    org_img_shape = original_image.shape[:2]
    org_height, org_width = org_img_shape
    image_data = utils.image_preporcess(np.copy(original_image),
                                        [input_size, input_size])
    image_data = image_data[np.newaxis, ...]
    pred_sbbox, pred_mbbox, pred_lbbox = sess.run(
        [return_tensors[1], return_tensors[2], return_tensors[3]],
        feed_dict={return_tensors[0]: image_data})
    pred_bbox = np.concatenate([
        np.reshape(pred_sbbox, (-1, 5 + num_classes)),
        np.reshape(pred_mbbox, (-1, 5 + num_classes)),
        np.reshape(pred_lbbox, (-1, 5 + num_classes))
    ],
                               axis=0)

    bboxes_cars = utils.postprocess_boxes(pred_bbox, org_img_shape, input_size,
                                          0.35)
    # bboxes = utils.nms(bboxes, 0.25, method='nms')
    bboxes_cars = utils.nms(bboxes_cars, 0.45, method='nms')
    # bboxes = utils.nms(bboxes, 0.65, method='nms')
    gt_img_path = img_path.replace('.jpg', '.txt')
    ground_truth_frame = []
    file_ground_truth = open(gt_img_path, 'r')
    lines_gt = file_ground_truth.readlines()
    file_ground_truth.close
    if len(bboxes_cars) > 0:
        for indice_bbox, bbox_car in enumerate(bboxes_cars):
            top_left_car, bottom_right_car = (int(bbox_car[0]), int(
                bbox_car[1])), (int(bbox_car[2]), int(bbox_car[3]))
            bbox_plate_inside, top_left_plate, bottom_right_plate, class_object = get_lp_from_car_bbox(
                top_left_car, bottom_right_car, lines_gt, org_width,
                org_height)
            if bbox_plate_inside:
                filename = os.path.basename(img_path)
                bname_image_file = os.path.splitext(filename)[0]
                nome_arquivo_saida_imagem = bname_image_file + '_' + str(
                    indice_bbox).zfill(6) + '.jpg'
                nome_arquivo_saida_gt = bname_image_file + '_' + str(
                    indice_bbox).zfill(6) + '.txt'
                caminho_completo_saida_imagem = os.path.abspath(
                    os.path.join(diretorio_saida, nome_arquivo_saida_imagem))
                caminho_completo_saida_gt = os.path.abspath(
                    os.path.join(diretorio_saida, nome_arquivo_saida_gt))
                cropped_car_image_ndarray = original_image[
                    top_left_car[1]:bottom_right_car[1],
                    top_left_car[0]:bottom_right_car[0]]
                image = Image.fromarray(cropped_car_image_ndarray)
                image.save(caminho_completo_saida_imagem)
                cropped_img_shape = cropped_car_image_ndarray.shape[:2]
                cropped_car_height, cropped_car_width = cropped_img_shape
                lp_points_relative_car = converter_bbox_placa_crop_carro(
                    top_left_car, bbox_plate_inside, org_width, org_height,
                    cropped_car_width, cropped_car_height, class_object)
                bbox_gt_lp = [lp_points_relative_car]
                with open(caminho_completo_saida_gt, 'w') as f:
                    for item in bbox_gt_lp:
                        f.write("%s\n" % item)
                if diretorio_saida_img_bbox:
                    caminho_completo_saida_imagem_bbox = os.path.abspath(
                        os.path.join(diretorio_saida_img_bbox,
                                     nome_arquivo_saida_imagem))
                    draw_bbox_relative_points(
                        cropped_car_image_ndarray, lp_points_relative_car,
                        cropped_car_width, cropped_car_height,
                        caminho_completo_saida_imagem_bbox)
                return True
    return False