class DetectionService(object):
    def __init__(self):
        self.__psql = PostgreSql()
        self.__s3Service = S3Service()

    def get_s3url(self, params):
        imageKey = params.get('imagekey')
        tagType = params.get('tag')

        #Get detection path
        path = self.__get_path(imageKey)

        #For IntrinsicMatrix
        if tagType is not None:

            if (tagType == 'IntrinsicMatrix'):
                path = re.sub('/images.*', '/IntrinsicMatrix.json', path)
            #For json_lane, json_line, json_trafficsign, json_project(spSlam result)
            else:
                path = path.replace('/images', '/' + tagType)
                path = path.replace('.jpg', '.json')

        path = 'map-data/' + path
        url = self.__s3Service.create_presigned_url('momenta-hdmap', path)
        return url

    def get_frame_location(self, imageKey):
        sqlString = """select ST_AsText(keyframes.geom) as point, image_packets.plateno, image_packets.timestamp \
         from keyframes left join image_packets on (keyframes.image_packet_id = image_packets.id) \
          where keyframes.id = {}""".format(imageKey)
        #print(sqlString)
        result = self.__psql.execute(sqlString)[0]
        resultJson = {}
        plateno = result['plateno']
        timestamp = result['timestamp']
        resultJson['packet_name'] = plateno + '-' + 'local_str_time'

        patt = re.compile(r'[0-9][0-9\.\s]+')
        loc = patt.search(result['point']).group()
        resultJson['loc'] = loc
        return resultJson

    def get_packet_location(self, packetName):
        plateno = packetName[:2]
        timestamp = packetName[3:]
        timestamp = time.strftime(
            "%Y-%m-%d %H:%M:%S", time.strptime(timestamp, "%Y-%m-%d-%H-%M-%S"))
        #print(timestamp)
        sqlString = "select ST_AsText(keyframes.geom) \
        as point from keyframes where image_packet_id = (select id from image_packets where plateno = '{}' and timestamp = '{}')  \
        order by id".format(plateno, timestamp)
        prin(sqlString)
        result = self.__psql.execute(sqlString)[0]
        resultJson = {}
        patt = re.compile(r'[0-9][0-9\.\s]+')
        loc = patt.search(result['point']).group()
        resultJson['loc'] = loc
        return resultJson

    def __get_path(self, imageKey):
        conn = None
        imagePath = ''
        sqlString = """select keyframes.filename, image_packets.plateno, image_packets.timestamp from keyframes \
             left join image_packets on (keyframes.image_packet_id = image_packets.id) where keyframes.id = {}""".format(
            imageKey)

        result = self.__psql.execute(sqlString)[0]
        plateno = result['plateno']
        timestamp = result['timestamp']
        filename = result['filename']
        local_str_time = time.strftime(
            "%Y-%m-%d-%H-%M-%S",
            time.strptime(str(timestamp), "%Y-%m-%d %H:%M:%S"))
        imagePath = plateno + '-' + local_str_time + '/keyframes/images/' + filename + '.jpg'
        return imagePath
 def __init__(self):
     self.__psql = PostgreSql()
     self.__s3Service = S3Service()
Exemplo n.º 3
0
 def __init__(self):
     self.__matConvert = np.array([1, 0, 0, 0, 0, 1, 0, -1,
                                   0]).reshape(3, 3)
     self.__psql = PostgreSql()
Exemplo n.º 4
0
class ImageService(object):
    def __init__(self):
        self.__matConvert = np.array([1, 0, 0, 0, 0, 1, 0, -1,
                                      0]).reshape(3, 3)
        self.__psql = PostgreSql()

    def get_images(self, params, bbox):

        perPage = params.get('per_page')
        startKey = params.get('start_key')
        image_packet = params.get('image_packet')
        #print(image_packet)
        image_packet_filter = ""
        if (image_packet is None):
            image_packet_filter = ""
        else:
            image_packet_filter = self.__extract_image_packet(image_packet)
        if not startKey:
            startKey = '32533459200'

        perQuery = int(perPage) + 1

        FeatureCollection = {'type': 'FeatureCollection', 'features': []}
        point1 = ", ".join(bbox[0:2])
        point2 = ", ".join(bbox[2:4])
        sql = """SELECT keyframes.image_packet_id, keyframes.filename, ST_AsText(keyframes.geom), image_packets.plateno, \
    image_packets.timestamp, keyframes.qw, keyframes.qx, keyframes.qy, keyframes.qz, keyframes.id, keyframes.ca, keyframes.pose_confidence   \
    from keyframes left join image_packets \
    on (keyframes.image_packet_id = image_packets.id) where keyframes.geom && ST_SetSRID(\
    ST_MakeBox2D(ST_Point({}),ST_Point({})),4326) {} and keyframes.filename <= '{}' order by keyframes.filename desc limit {}\
    """.format(point1, point2, image_packet_filter, startKey, perQuery)

        rows = self.__psql.execute(sql)
        nextStartKey = 0

        if len(rows) == perQuery:
            nextStartKey = rows[-1][1]
            rows = rows[:-1]
        FeatureCollection['next_start_key'] = nextStartKey

        for row in rows:
            FeatureCollection["features"].append(
                copy.deepcopy(self.__extract_feature(row)))

        return FeatureCollection

    def __extract_loc(self, position):
        indexstart = position.find('(')
        indexend = position.find(')')
        loc = position[indexstart + 1:indexend]
        loc = loc.split(' ')[:2]
        return loc

    def __extract_height(self, position):
        indexstart = position.find('(')
        indexend = position.find(')')
        loc = position[indexstart + 1:indexend]
        loc = loc.split(' ')[2:]
        return loc

    def __extract_image_packet(self, image_packets):
        reResult = re.search('^B[0-9]-20[0-9]{2}-', image_packets, re.M | re.I)
        if (not reResult):
            return ""
        else:
            image_packets_arr = image_packets.split(' ')
            plateno = reduce(self.__remove_repeat,
                             map(lambda x: x[0:2], image_packets_arr))
            timestamp_arr = map(
                lambda x: time.strftime(
                    "%Y-%m-%d %H:%M:%S",
                    time.strptime(x[3:], "%Y-%m-%d-%H-%M-%S")),
                image_packets_arr)
            timestamp = reduce(lambda x, y: x + "', '" + y, timestamp_arr)
            return """and plateno in ('{}') and timestamp in ('{}')""".format(
                plateno, timestamp)

    def __remove_repeat(self, x, y):
        if y not in x:
            return x + "', '" + y
        else:
            return x

    #generate feature according to the sql record
    def __extract_feature(self, row):
        loc = self.__extract_loc(row[2])
        filename = row[1]
        timestamp = int(filename)
        local_str_time = time.strftime(
            "%Y-%m-%d-%H-%M-%S", time.strptime(str(row[4]),
                                               "%Y-%m-%d %H:%M:%S"))
        imagekey = row[3] + '-'
        imagekey += local_str_time + '/keyframes/images/' + filename + '.jpg'
        imagekey = row[9]
        quanternion = [float(x) for x in row[5:9]]

        feature["properties"]["ca"] = str(row['ca'])
        feature["properties"]["key"] = imagekey
        feature["properties"]["captured_at"] = row[1]
        feature["properties"]["username"] = row[3] + '-' + local_str_time
        feature["geometry"]["coordinates"] = copy.deepcopy(loc)
        feature["properties"]['campos'] = quanternion
        feature["properties"]['height'] = self.__extract_height(row[2])[0]
        feature['properties']['confidence'] = str(row['pose_confidence'])
        return feature
Exemplo n.º 5
0
 def __init__(self):
     self.__psql = PostgreSql()
Exemplo n.º 6
0
class CheckService():
    def __init__(self):
        self.__psql = PostgreSql()

    def __extract_loc(self, position):
        indexstart = position.find('(')
        indexend = position.find(')')
        loc = position[indexstart + 1:indexend]
        loc = loc.split(' ')[:2]
        return loc

    def upload_check_result(self, request):
        user = None
        try:
            user = check_login(request)
            #print(user)
        except Exception as e:
            #print('Exception', e)
            return {'result': 'Login Fail'}
        finally:
            if user is None:
                return {'result': 'Login Fail'}
        requestValues = request.values
        frameId = requestValues.get('image_key')
        packetName = requestValues.get('packetName')
        photoResult = requestValues.get('photoResult')
        detectionResult = requestValues.get('detectionResult')
        spslamResult = requestValues.get('spslamResult')
        commentResult = requestValues.get('commentResult')
        check_time = time.strftime('%Y-%m-%d %H:%M:%S')

        sql = """insert into human_check (keyframe_id, packet_name, photo_result, detection_result, spslam_result, \
            check_time, user_name, work_order, comment ) values ({}, '{}', '{}', '{}', '{}', '{}', '{}', '{}', \
            '{}') returning id""".format(frameId, packetName, photoResult,
                                         detectionResult, spslamResult,
                                         check_time, user, 'test',
                                         commentResult)
        #print(sql)
        self.__psql.execute(sql)
        return {'result': 'OK'}

    def get_check_result(self, packetName, request):
        user = None

        try:
            user = check_login(request)
        except Exception as e:
            #print(e)
            return {'result': 'Login Fail'}
        finally:
            if user is None:
                return {'result': 'Login Fail'}
        packetName = packetName
        sql = """select human_check.keyframe_id, human_check.photo_result, human_check.detection_result, \
        human_check.spslam_result, human_check.comment, ST_AsText(keyframes.geom) \
        from human_check left join keyframes on (human_check.keyframe_id = keyframes.id) \
            where human_check.packet_name = '{}' and human_check.user_name = '{}'""".format(
            packetName, user)
        #print(sql)
        rows = None
        try:
            rows = self.__psql.execute(sql)
        except Exception as e:
            raise
        result = {}
        for row in rows:
            result[row[0]] = {
                'commentResult': row[4],
                'photoResult': row[1],
                'detectionResult': row[2],
                'spslamResult': row[3],
                'loc': self.__extract_loc(row[5])
            }
        return result
class SequenceService(object):
    def __init__(self):
        self.__psql = PostgreSql()
        pass

    def get_sequences(self, params):
        per_page = params.get('per_page')
        start_key = params.get('start_key')
        bbox = params.get('bbox')
        if not bbox:
            raise Exception('No bbox in params')

        bbox = bbox.split(',')
        point1 = ','.join(bbox[0:2])
        point2 = ','.join(bbox[2:4])
        if not start_key:
            start_key = 0

        per_query = int(per_page) + 1
        next_key = 0

        sql = (
            'select id, keyframes_id, ST_ASTEXT(geom) as geom from image_packets '
            'where geom && ST_SetSRID(ST_MakeBox2D(ST_Point({point1}), ST_Point({point2})), 4326) '
            'and image_packets.id >= {start_key} and keyframes_id is not null order by image_packets.id limit {per_page}'
        ).format(point1=point1,
                 point2=point2,
                 start_key=start_key,
                 per_page=per_query)
        packets_result = self.__psql.execute(sql)
        ## per_query number of records are returned at one time. per_query + 1 and result[:-1] is used to panigation
        if len(packets_result) == per_query:
            print('111')
            next_key = packets_result[-1]['id']
            packets_result = packets_result[:-1]
        print('NextKey:      ', next_key)
        final_result = self.__generate_features(packets_result)
        final_result['next_start_key'] = next_key
        # #print features
        return final_result

    def __extract_loc(self, geom):
        indexstart = geom.find('(')
        indexend = geom.find(')')
        loc = geom[indexstart + 1:indexend]
        loc = loc.split(',')
        loc = [i.split(' ')[:-1] for i in loc]
        return loc

    def __generate_features(self, packets_result):
        start_time = time.monotonic()
        result_features = copy.deepcopy(sequence_features.features)
        for packet_info in packets_result:
            temp_feature = copy.deepcopy(sequence_features.feature)
            geom_text = packet_info['geom']
            temp_feature['geometry']['coordinates'] = self.__extract_loc(
                geom_text)
            temp_feature['properties']['coordinateProperties'][
                'image_keys'] = packet_info['keyframes_id']
            temp_feature['properties']['id'] = packet_info['id']
            temp_feature['properties']['key'] = packet_info['id']

            result_features['features'].append(temp_feature)

        print('TotalTime: ', time.monotonic() - start_time)

        return result_features

    def __query_single_packet(self, result, temp_results, packet_id):
        sql = 'select id, image_packet_id, ST_ASTEXT(geom) as geom, qw, qx, qy ,qz from keyframes where image_packet_id = {packet_id} order by filename'.format(
            packet_id=result['id'])
        keyframes_info = self.__psql.execute(sql)
        temp_results.append(keyframes_info)