예제 #1
0
def encode_labels(labels: List[List[str]], remove_too_long: bool = True) -> List[List[int]]:
    encoded_labels = list(map(lambda t: [0] + list(map(lambda tt: CLASSES.index(tt), t)) + [0],
                              labels))
    if remove_too_long:
        encoded_labels = list(filter(lambda i: len(i) <= MAX_LEN, encoded_labels))
    encoded_labels = tf.keras.preprocessing.sequence.pad_sequences(encoded_labels,
                                                                   maxlen=MAX_LEN,
                                                                   padding='post',
                                                                   truncating='post',
                                                                   value=0)
    encoded_labels = tf.keras.utils.to_categorical(encoded_labels, len(CLASSES))
    return encoded_labels
예제 #2
0
def read_kitti_label(fpath):
    objs = []
    with open(fpath, 'r') as fin:
        for line in fin:
            cols = line.split(' ')
            if cols[0] == 'DontCare':
                continue
            objs.append({
                'class':
                CLASSES.index(cols[0]),
                'bbox': [
                    float(cols[4]),
                    float(cols[5]),
                    float(cols[6]),
                    float(cols[7])
                ]  # left, top, right, bottom
            })
    return objs
예제 #3
0
def get_legend_color(class_name : int):
    """
    Возвращает цвет ячейки для `pandas.Styler` при создании легенды. 
    Раскарасит ячейку те же цветом, который имеют боксы соотвествующего класс

    Arguments
    ---------
    class_name : int
        название класса согласно списку классов MS COCO

    Returns
    -------
    str
        background-color для ячейки, содержащей class_name
    """  

    index = CLASSES.index(class_name)
    color = rgb_colors[index]
    return 'background-color: rgb({color[0]},{color[1]},{color[2]})'.format(color=color)
예제 #4
0
def read_data(xml_path, img_path):
    tree = ET.parse(xml_path)
    root = tree.getroot()
    objects = root.findall("object")
    names = []
    gtbboxes = np.zeros([len(objects), 4], dtype=np.int32)
    for idx, obj in enumerate(objects):
        names.append(obj.find("name").text)
        xmin = int(obj.find("bndbox").find("xmin").text)
        xmax = int(obj.find("bndbox").find("xmax").text)
        ymin = int(obj.find("bndbox").find("ymin").text)
        ymax = int(obj.find("bndbox").find("ymax").text)
        gtbboxes[idx, 0] = (xmin + xmax) // 2
        gtbboxes[idx, 1] = (ymin + ymax) // 2
        gtbboxes[idx, 2] = xmax - xmin
        gtbboxes[idx, 3] = ymax - ymin
    img = np.array(Image.open(img_path))
    labels = np.zeros([len(objects)])
    for idx, name in enumerate(names):
        labels[idx] = CLASSES.index(name)
    return img, gtbboxes, labels
예제 #5
0
def predict(folder, item):
    """画像の推論."""

    if folder not in ['train', 'test']:
        abort(404)

    filename_list = sorted(
        glob.glob(os.path.join(DATA_PATH, folder, item, '*.jpeg')))

    image_list = []
    for filename in filename_list:

        face = Image.open(filename)
        face = face.resize((IMG_ROWS, IMG_COLS), Image.LANCZOS)
        face = face.convert('L')
        face = np.array(face, dtype=np.float32) / 255.0
        face = np.ravel(face)
        image_list.append(face)

    percent_list = face_deep.predict(image_list, dtype='int')

    rows = []
    for filename, percent in zip(filename_list, percent_list):
        color = CLASSES.index(item) in [
            index for index, value in enumerate(percent)
            if value == max(percent)
        ]
        row = {
            'filename': os.path.basename(filename),
            'percent': percent,
            'color': color
        }
        rows.append(row)

    return render_template('predict.html',
                           folder=folder,
                           item=item,
                           headers=CLASSES,
                           rows=rows)
from serial.tools import list_ports
import numpy as np
import os
from config import CLASSES
from random import choice
import uuid

app = QApplication(sys.argv)

INIT = 0
CONNECTED = 1
STARTED = 2

pixmaps = {
    k: QPixmap(v).scaled(128, 128, QtCore.Qt.KeepAspectRatio)
    for k, v in CLASSES.items()
}


class DataThread:
    def __init__(self):
        self._running = True

    def terminate(self):
        self._running = False

    def run(self, controller, port):
        while self._running:
            if port.in_waiting > 0:
                serialString = port.readline()
                new_data = np.array(
예제 #7
0
    
classes_selector = st.sidebar.multiselect('Select classes', 
                                        CLASSES, default='person')
all_labels_chbox = st.sidebar.checkbox('All classes', value=False)


# Prediction section
# ---------------------------------------------------------

#target labels and their colors
#target_class_ids - индексы выбранных классов согласно списку классов MS COCC
#rgb_colors - rgb-цвета для выбранных классов
if all_labels_chbox:
    target_class_ids = list(range(len(CLASSES)))
elif classes_selector:
    target_class_ids = [CLASSES.index(class_name) for class_name in classes_selector]
else:
    target_class_ids = [0]

rgb_colors = get_colors(target_class_ids)
detected_ids = None


if prediction_mode == 'Single image':

    # добавляет форму для загрузки изображения
    uploaded_file = st.file_uploader(
        "Choose an image",
        type=['png', 'jpg', 'jpeg'])

    # если файл загружен