def __init__(self, mode):

        if mode not in ['train', 'test']:
            raise ValueError('Mode "{}" not valid.'.format(mode))
        image = Circuit.train_image if mode == 'train' else Circuit.test_image

        self.image = imread(image, mode='RGB')
        self.image_gray = imread(image, mode='L')

        self.reward_map = distance_transform_edt(input=np.uint8(
            self.image_gray == 0))

        self.car = Car()
示例#2
0
def data_generator(path,
                   class_names: Sequence[str],
                   infinite=True) -> DataGenerator:
    while True:
        filelist = list(os.listdir(path))
        shuffle(filelist)
        for filename in filelist:
            filename = os.path.join(path, filename)
            if filename.endswith(".jpg"):
                try:
                    label_filename = filename.replace(".jpg", ".txt")
                    image = imread(filename)
                    boxes = []
                    with open(label_filename, 'r') as f:
                        for line in f.readlines():
                            class_index, center_x, center_y, width, height = map(
                                float, tuple(line.split()))
                            xmin = (center_x - width / 2) * image.shape[1]
                            ymin = (center_y - height / 2) * image.shape[0]
                            xmax = (center_x + width / 2) * image.shape[1]
                            ymax = (center_y + height / 2) * image.shape[0]
                            boxes.append((class_index, xmin, ymin, xmax, ymax))
                        if len(boxes) == 0:
                            raise Exception("no true boxes!")
                    yield image, np.array(boxes)
                except Exception:
                    logging.exception(
                        "exception during reading image or labels for '{}'; ignoring"
                        .format(filename))

        if not infinite:
            return
示例#3
0
    def __init__(self, font_file, buffer_base):
        self.font_file = font_file
        self.buffer_base = buffer_base 

        # prepare glyph atlas
        page_data         = [imread(img_path)[:,:,3] for img_path in font_file.page_paths]
        glypthatlas_width = page_data[0].shape[0]
        glyphatlas_height = page_data[0].shape[1]
        glyphatlas        = np.empty((len(page_data), glypthatlas_width, glyphatlas_height), dtype=np.float32)
        for i, glyphdata in enumerate(page_data):
            if glyphdata.shape[0:2] != (glypthatlas_width,glyphatlas_height):
                raise FontException((
                    'font "{}" corrupt: font page id={} file="{}" image size {}x{}'
                    + ' differs from the first page id=0 file="{}" {}x{}').format(
                        self.font, i, font_file.page_paths[i], glyphdata.shape[0],
                        glyphdata.shape[1], font_file.page_paths[0],
                        page_data[0].shape[0], page_data[0].shape[1]))

            glyphatlas[i] = glyphdata

        # upload glyph information
        glyphdata = np.empty(len(font_file.glyphs), dtype=np.dtype([('glyph', GLYPH_DTYPE)]))
        glyphdata[:] = [(c.dump(),) for c in font_file.glyphs]
        self.glyph_buffer = BufferObject.to_device(glyphdata, target=GL_UNIFORM_BUFFER)
        self.glyph_buffer.bind_buffer_base(self.buffer_base)

        # texture glyph atlas
        self.texture = Texture2D(array=True)
        self.texture.load(glyphatlas)
        self.texture.interpolation_linear()
示例#4
0
def importImage(file):
    im = imageio.imread(file)

    rows = im.shape[0]
    cols = im.shape[1]

    image = Images.MatrixBasedImage(rows, cols)

    for i in range(rows):
        for j in range(cols):
            color = im[i, j]
            image.setColor(i, j, color[0], color[1], color[2])

    return image
示例#5
0
def get_image(name, size = None):
    """
    Get an image by name.
    :param name: A string identifying an image from our dictionary.
    :return:
    """
    assert name in IMAGE_COLLECTION, "We don't have the image '%s' in the gallary" % (name, )
    _, ext = os.path.splitext(IMAGE_COLLECTION[name])
    relative_path = os.path.join('images', name)+ext
    filename = get_file(
        relative_name = relative_path,
        url = IMAGE_COLLECTION[name],
        )
    im_array = imread(filename)
    if im_array.ndim==2:
        im_array = im_array[:, :, None] + [0, 0, 0]
    if size is not None:
        im_array = imresize(im_array, get_new_size(im_array.shape[:2], new_size=size))
    return im_array
示例#6
0
def load_map(file_name, load_graphics=True):
    """
    Loads map and encodes it as a grid

    :returns map
    """
    map = json.loads(open(file_name, "r").read())

    if not os.path.isabs(map['color_bitmap_file']):
        map['color_bitmap_file'] = os.path.join(os.path.dirname(file_name),
                                                map['color_bitmap_file'])

    try:
        if load_graphics:
            map['color_bitmap'] = imread(map['color_bitmap_file'])
    except IOError:
        print "Warning: Not found color file"

    if not os.path.isabs(map['vector_graphics_file']):
        map['vector_graphics_file'] = os.path.join(os.path.dirname(file_name),
                                                   map['vector_graphics_file'])

    if "title" not in map:
        map["title"] = ""

    if "board" not in map:
        # Map is assumed to be always a simple box with 1-cell width wall around
        # and single start field.
        grid = [[1] * (map["M"])]
        grid += [[1] + [0] * (map["M"] - 2) + [1]]
        grid += [[1, 0] + [0] * (map["M"] - 4) + [0, 1]
                 for _ in xrange(map["N"] - 4)]
        grid += [[1] + [0] * (map["M"] - 2) + [1]]
        grid += [[1] * (map["M"])]
        grid[map['start_field'][0]][map['start_field'][1]] = MAP_START_POSITION
        map['file_name'] = file_name
        map['board'] = grid
    else:
        raise RuntimeError("Not supported custom board parsing")

    return map
示例#7
0
""" Script:
From the designated directory (updir),
finds subdirectories containing the experiments/conditions to analyse.
"""
for dirname in sorted(os.listdir(updir)):
    drpath = updir + dirname
    if os.path.isdir(drpath):
        # print drpath
        print "Folder analyzed: " + dirname
        """ For each .tif image in each directory: """
        for img_file in sorted(os.listdir(drpath)):
            if ("thld.jpg" in img_file) or ("thld.tif" in img_file):
                imgpath = drpath + "/" + img_file
                # print 'image path: ' + imgpath
                img = imread(imgpath).astype(float)
                if img.shape[-1] == 3:
                    img = img.mean(axis=-1)
                print "image analyzed: " + img_file
                # Extracts the threshold value from the title
                thld1 = img_file[:-8]
                thld = thld1[-3:]
                # Trims the 0 at the begining of the value if it is lower than 100
                if thld[:1] is '0':
                    thld = thld[1:]
                """ Runs the segmentation."""
                labelled_regions = Segment_cell_separation(img, threshold=thld)
                print "segmentation done"
                """ Labels of segmented regions, shuffled for visualization."""
                labels = np.unique(labelled_regions)[1:]
                np.random.shuffle(labels)
示例#8
0
def load_map(file_name, load_graphics=True):
    """
    Loads map and encodes it as a grid

    :returns map
    """
    map_ = json.loads(open(file_name, "r").read())

    color_names = ['red', 'green', 'blue']
    for color in color_names:
        if map_.has_key(color) and isinstance(map_[color], list) and len(map_[color]):
            # if the first element is also a list (list of fields notation)
            if isinstance(map_[color][0], list):
                map_[color] = map(tuple, map_[color])

            #if the first element is not a list (single field notation)
            else:
                map_[color] = [tuple(map_[color][0])]
        else:
            print "Warning: no coordinates provided or unsupported type for '{}' fields in the map file. Overwriting with empty list".format(color)
            map_[color] = []

    # convert beeps list to red, green and blue lists
    if map_.has_key('beeps'):
        beeps = map_['beeps']
        print "Warning: beeps is deprecated - use separate red, green and blue field lists in map file"
        assert len(beeps)==3, "The beeps list must have exactly 3 elements."
        for i, color in enumerate(color_names):
            map_[color].append(tuple(beeps[i]))

    fields = sum((map_[color] for color in color_names), [])
    # check for overlapping fields
    assert len(set(fields)) == len(fields), "There are some color fields with the same coordinates"


    if not os.path.isabs(map_['color_bitmap_file']):
        map_['color_bitmap_file'] = os.path.join(os.path.dirname(file_name), map_['color_bitmap_file'])

    try:
        if load_graphics:
            map_['color_bitmap'] = imread(map_['color_bitmap_file'])
    except IOError:
        print "Warning: Not found color file"

    if not os.path.isabs(map_['vector_graphics_file']):
        map_['vector_graphics_file'] = os.path.join(os.path.dirname(file_name), map_['vector_graphics_file'])

    if "title" not in map_:
        map_["title"] = ""

    if "board" not in map_:
        # Map is assumed to be always a simple box with 1-cell width wall around
        # and single start field.
        grid = [[1]*(map_["M"])]
        grid += [[1] + [0]*(map_["M"] - 2) + [1]]
        grid += [[1, 0] + [0]*(map_["M"] - 4) + [0, 1] for _ in xrange(map_["N"] - 4)]
        grid += [[1] + [0]*(map_["M"] - 2) + [1]]
        grid += [[1]*(map_["M"])]
        grid[map_['start_field'][0]][map_['start_field'][1]] = MAP_START_POSITION
        map_['file_name'] = file_name
        map_['board'] = grid
    else:
        raise RuntimeError("Not supported custom board parsing")

    return map_
 def __init__(self, start_pos):
     self.image = imread(Circuit.car_image, mode='RGB')
     self.start