Python matplotlib.pyplot.imread() Examples

The following are 30 code examples of matplotlib.pyplot.imread(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: gridworld.py    From qmap with MIT License 6 votes vote down vote up
def __init__(self, level='level1', scale=1):
        self.level = level
        if not '.' in level: level += '.bmp'
        self.walls = np.logical_not(plt.imread(os.path.join(os.path.dirname(os.path.realpath(__file__)), level)))
        self.height = self.walls.shape[0]
        self.width = 32
        # observations
        self.screen_shape = (self.height, self.width)
        self.padding = self.width // 2 - 1
        self.padded_walls = np.logical_not(np.pad(np.logical_not(self.walls), ((0, 0), (self.padding, self.padding)), 'constant'))
        self.observation_space = spaces.Box(0, 255, (self.height, self.width, 3), dtype=np.float32)
        # coordinates
        self.scale = scale
        self.coords_shape = (self.height // scale, self.width // scale)
        self.available_coords = np.array(np.where(np.logical_not(self.walls))).transpose()
        # actions
        self.action_space = spaces.Discrete(4)
        # miscellaneous
        self.name = 'GridWorld_obs{}x{}x3_qframes{}x{}x4-v0'.format(*self.screen_shape, *self.coords_shape)
        self.viewer = None
        self.seed() 
Example #2
Source File: dataset.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_large_image(img_path):
    """ loading very large images

    .. note:: For the loading we have to use matplotlib while ImageMagic nor other
     lib (opencv, skimage, Pillow) is able to load larger images then 64k or 32k.

    :param str img_path: path to the image
    :return ndarray: image
    """
    assert os.path.isfile(img_path), 'missing image: %s' % img_path
    img = plt.imread(img_path)
    if img.ndim == 3 and img.shape[2] == 4:
        img = cvtColor(img, COLOR_RGBA2RGB)
    if np.max(img) <= 1.5:
        np.clip(img, a_min=0, a_max=1, out=img)
        # this command split should reduce mount of required memory
        np.multiply(img, 255, out=img)
        img = img.astype(np.uint8, copy=False)
    return img 
Example #3
Source File: segmentation_utils.py    From shapestacks with GNU General Public License v3.0 6 votes vote down vote up
def load_segmap_as_matrix(
    map_path: str,
    label_resolution: int = VSEG_LABEL_RESOLUTION):
  """
  Loads a .map file and returns a matrix of the label values (uint8 between 0
  and 255).

  Args:
    map_path: path to the .map file to load
    label_resolution: max. number of labels used in the map's encoding,
      must be a power of 2

  Returns:
    A np.ndarray of the semantic segmentation labels.
  """
  png_map = plt.imread(map_path)
  label_bin_size = MAX_LABELS // label_resolution
  lbl_map = np.copy(png_map[:, :, 0]) # slice of first image layer
  lbl_map = lbl_map / label_bin_size
  return lbl_map 
Example #4
Source File: kMeans.py    From AILearners with Apache License 2.0 6 votes vote down vote up
def clusterClubs(numClust=5):
    datList = []
    for line in open('places.txt').readlines():
        lineArr = line.split('\t')
        datList.append([float(lineArr[4]), float(lineArr[3])])
    datMat = mat(datList)
    myCentroids, clustAssing = biKmeans(datMat, numClust, distMeas=distSLC)
    fig = plt.figure()
    rect=[0.1,0.1,0.8,0.8]
    scatterMarkers=['s', 'o', '^', '8', 'p', \
                    'd', 'v', 'h', '>', '<']
    axprops = dict(xticks=[], yticks=[])
    ax0=fig.add_axes(rect, label='ax0', **axprops)
    imgP = plt.imread('Portland.png')
    ax0.imshow(imgP)
    ax1=fig.add_axes(rect, label='ax1', frameon=False)
    for i in range(numClust):
        ptsInCurrCluster = datMat[nonzero(clustAssing[:,0].A==i)[0],:]
        markerStyle = scatterMarkers[i % len(scatterMarkers)]
        ax1.scatter(ptsInCurrCluster[:,0].flatten().A[0], ptsInCurrCluster[:,1].flatten().A[0], marker=markerStyle, s=90)
    ax1.scatter(myCentroids[:,0].flatten().A[0], myCentroids[:,1].flatten().A[0], marker='+', s=300)
    plt.show() 
Example #5
Source File: segment.py    From COCO-Style-Dataset-Generator-GUI with Apache License 2.0 6 votes vote down vote up
def previous(self, event):

        if (self.index>self.checkpoint):
            self.index-=1
        #print (self.img_paths[self.index][:-3]+'txt')
        os.remove(self.img_paths[self.index][:-3]+'txt')

        self.ax.clear()

        self.ax.set_yticklabels([])
        self.ax.set_xticklabels([])

        image = plt.imread(self.img_paths[self.index])
        self.ax.imshow(image, aspect='auto')

        im = Image.open(self.img_paths[self.index])
        width, height = im.size
        im.close()

        self.reset_all()

        self.text+=str(self.index)+'\n'+os.path.abspath(self.img_paths[self.index])+'\n'+str(width)+' '+str(height)+'\n\n' 
Example #6
Source File: img_utils_demo.py    From Moving-Least-Squares with MIT License 6 votes vote down vote up
def demo2(fun):
    ''' 
        Smiled Monalisa  
    '''
    
    p = np.array([
        [186, 140], [295, 135], [208, 181], [261, 181], [184, 203], [304, 202], [213, 225], 
        [243, 225], [211, 244], [253, 244], [195, 254], [232, 281], [285, 252]
    ])
    q = np.array([
        [186, 140], [295, 135], [208, 181], [261, 181], [184, 203], [304, 202], [213, 225], 
        [243, 225], [207, 238], [261, 237], [199, 253], [232, 281], [279, 249]
    ])
    image = plt.imread(os.path.join(sys.path[0], "monalisa.jpg"))
    plt.subplot(121)
    plt.axis('off')
    plt.imshow(image)
    transformed_image = fun(image, p, q, alpha=1, density=1)
    plt.subplot(122)
    plt.axis('off')
    plt.imshow(transformed_image)
    plt.tight_layout(w_pad=1.0, h_pad=1.0)
    plt.show() 
Example #7
Source File: data_loader.py    From ShuffleNet with Apache License 2.0 6 votes vote down vote up
def load_data(self):
        # This method is an example of loading a dataset. Change it to suit your needs..
        import matplotlib.pyplot as plt
        # For going in the same experiment as the paper. Resizing the input image data to 224x224 is done.
        train_data = np.array([plt.imread('./data/0.jpg')], dtype=np.float32)
        self.X_train = train_data
        self.y_train = np.array([283], dtype=np.int32)

        val_data = np.array([plt.imread('./data/0.jpg')], dtype=np.float32)
        self.X_val = val_data
        self.y_val = np.array([283])

        self.train_data_len = self.X_train.shape[0]
        self.val_data_len = self.X_val.shape[0]
        img_height = 224
        img_width = 224
        num_channels = 3
        return img_height, img_width, num_channels, self.train_data_len, self.val_data_len 
Example #8
Source File: test_html.py    From mapboxgl-jupyter with MIT License 6 votes vote down vote up
def test_display_ImageVizArray(display, data):
    """Assert that show calls the mocked display function
    """

    image_path = os.path.join(os.path.dirname(__file__), 'mosaic.png')
    image = imread(image_path)

    coordinates = [
        [-123.40515640309, 32.08296982365502],
        [-115.92938988349292, 32.08296982365502],
        [-115.92938988349292, 38.534294809274336],
        [-123.40515640309, 38.534294809274336]][::-1]

    viz = ImageViz(image, coordinates, access_token=TOKEN)
    viz.show()
    display.assert_called_once() 
Example #9
Source File: test_png.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example #10
Source File: data_loader.py    From MobileNet with Apache License 2.0 6 votes vote down vote up
def load_data(self):
        # Please make sure to change this function to load your train/validation/test data.
        train_data = np.array([plt.imread('./data/test_images/0.jpg'), plt.imread('./data/test_images/1.jpg'),
                      plt.imread('./data/test_images/2.jpg'), plt.imread('./data/test_images/3.jpg')])
        self.X_train = train_data
        self.y_train = np.array([284, 264, 682, 2])

        val_data = np.array([plt.imread('./data/test_images/0.jpg'), plt.imread('./data/test_images/1.jpg'),
                    plt.imread('./data/test_images/2.jpg'), plt.imread('./data/test_images/3.jpg')])

        self.X_val = val_data
        self.y_val = np.array([284, 264, 682, 2])

        self.train_data_len = self.X_train.shape[0]
        self.val_data_len = self.X_val.shape[0]
        img_height = 224
        img_width = 224
        num_channels = 3
        return img_height, img_width, num_channels, self.train_data_len, self.val_data_len 
Example #11
Source File: test_image.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_imsave_color_alpha():
    # Test that imsave accept arrays with ndim=3 where the third dimension is
    # color and alpha without raising any exceptions, and that the data is
    # acceptably preserved through a save/read roundtrip.
    from numpy import random
    random.seed(1)
    data = random.rand(256, 128, 4)

    buff = io.BytesIO()
    plt.imsave(buff, data)

    buff.seek(0)
    arr_buf = plt.imread(buff)

    # Recreate the float -> uint8 -> float32 conversion of the data
    data = (255*data).astype('uint8').astype('float32')/255
    # Wherever alpha values were rounded down to 0, the rgb values all get set
    # to 0 during imsave (this is reasonable behaviour).
    # Recreate that here:
    for j in range(3):
        data[data[:, :, 3] == 0, j] = 1

    assert_array_equal(data, arr_buf) 
Example #12
Source File: yolo_image.py    From ai-platform with MIT License 6 votes vote down vote up
def draw_boxes(filename, v_boxes, v_labels, v_scores, output_photo_name):
	# load the image
	data = pyplot.imread(filename)
	# plot the image
	pyplot.imshow(data)
	# get the context for drawing boxes
	ax = pyplot.gca()
	# plot each box
	for i in range(len(v_boxes)):
		box = v_boxes[i]
		# get coordinates
		y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax
		# calculate width and height of the box
		width, height = x2 - x1, y2 - y1
		# create the shape
		rect = Rectangle((x1, y1), width, height, fill=False, color='white')
		# draw the box
		ax.add_patch(rect)
		# draw text and score in top left corner
		label = "%s (%.3f)" % (v_labels[i], v_scores[i])
		pyplot.text(x1, y1, label, color='white')
	# show the plot
	#pyplot.show()	
	pyplot.savefig(output_photo_name) 
Example #13
Source File: test_png.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_pngsuite():
    dirname = os.path.join(
        os.path.dirname(__file__),
        'baseline_images',
        'pngsuite')
    files = glob.glob(os.path.join(dirname, 'basn*.png'))
    files.sort()

    fig = plt.figure(figsize=(len(files), 2))

    for i, fname in enumerate(files):
        data = plt.imread(fname)
        cmap = None  # use default colormap
        if data.ndim == 2:
            # keep grayscale images gray
            cmap = cm.gray
        plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)

    plt.gca().patch.set_facecolor("#ddffff")
    plt.gca().set_xlim(0, len(files)) 
Example #14
Source File: ffhq_data_to_torch.py    From DeepPrivacy with MIT License 6 votes vote down vote up
def save_image_batch(idx, image_ids):
    imsizes = [4, 8, 16, 32, 64, 128]
    impaths = [os.path.join(SOURCE_IMG_DIR, get_impath(image_id))
               for image_id in image_ids]
    images = []
    for impath in impaths:
        images.append(plt.imread(impath))

    for imsize in imsizes:
        to_save = torch.zeros((len(impaths), 3, imsize, imsize),
                              dtype=torch.float32)
        for i, im in enumerate(images):
            im = im[:, :, :3]
            im = cv2.resize(im, (imsize, imsize),
                            interpolation=cv2.INTER_AREA)
            im = to_tensor(im)
            assert im.max() <= 1.0
            assert len(im.shape) == 3
            assert im.dtype == torch.float32
            to_save[i] = im
        target_dir = os.path.join(TARGET_IMAGE_DIR, str(imsize))
        target_path = os.path.join(target_dir, "{}.torch".format(str(idx)))
        os.makedirs(target_dir, exist_ok=True)
        torch.save(to_save, target_path)
        del to_save 
Example #15
Source File: massachusetts_road_dataset_utils.py    From Recipes with MIT License 6 votes vote down vote up
def load_data(folder):
    images_sat = [img for img in os.listdir(os.path.join(folder, "sat_img")) if fnmatch.fnmatch(img, "*.tif*")]
    images_map = [img for img in os.listdir(os.path.join(folder, "map")) if fnmatch.fnmatch(img, "*.tif*")]
    assert(len(images_sat) == len(images_map))
    images_sat.sort()
    images_map.sort()
    # images are 1500 by 1500 pixels each
    data = np.zeros((len(images_sat), 3, 1500, 1500), dtype=np.uint8)
    target = np.zeros((len(images_sat), 1, 1500, 1500), dtype=np.uint8)
    ctr = 0
    for sat_im, map_im in zip(images_sat, images_map):
        data[ctr] = plt.imread(os.path.join(folder, "sat_img", sat_im)).transpose((2, 0, 1))
        # target has values 0 and 255. make that 0 and 1
        target[ctr, 0] = plt.imread(os.path.join(folder, "map", map_im))/255
        ctr += 1
    return data, target 
Example #16
Source File: image_utils.py    From keras-ctpn with Apache License 2.0 6 votes vote down vote up
def load_image(image_path):
    """
    加载图像
    :param image_path: 图像路径
    :return: [h,w,3] numpy数组
    """
    image = plt.imread(image_path)
    # 灰度图转为RGB
    if len(image.shape) == 2:
        image = np.expand_dims(image, axis=2)
        image = np.tile(image, (1, 1, 3))
    elif image.shape[-1] == 1:
        image = skimage.color.gray2rgb(image)  # io.imread 报ValueError: Input image expected to be RGB, RGBA or gray
    # 标准化为0~255之间
    if image.dtype == np.float32:
        image *= 255
        image = image.astype(np.uint8)
    # 删除alpha通道
    return image[..., :3] 
Example #17
Source File: example_simple_GUI.py    From PyAbel with MIT License 6 votes vote down vote up
def _getfilename():
    global IM, text
    fn = filedialog.askopenfilename()

    # update what is occurring text box
    text.delete(1.0, tk.END)
    text.insert(tk.END, "reading image file {:s}\n".format(fn))
    canvas.draw()

    # read image file
    if ".txt" in fn:
        IM = np.loadtxt(fn)
    else:
        IM = imread(fn)

    if IM.shape[0] % 2 == 0:
        text.insert(tk.END, "make image odd size")
        IM = shift(IM, (-0.5, -0.5))[:-1, :-1]

    # show the image
    _display() 
Example #18
Source File: calculate_fid_official.py    From DeepPrivacy with MIT License 5 votes vote down vote up
def _handle_path(path, sess, low_profile=False):
    if path.endswith('.npz'):
        f = np.load(path)
        m, s = f['mu'][:], f['sigma'][:]
        f.close()
    else:
        path = pathlib.Path(path)
        files = list(path.glob('*.jpg')) + list(path.glob('*.png'))
        if low_profile:
            m, s = calculate_activation_statistics_from_files(files, sess)
        else:
            x = np.array([imread(str(fn)).astype(np.float32) for fn in files])
            m, s = calculate_activation_statistics(x, sess)
            del x #clean up memory
    return m, s 
Example #19
Source File: event_log.py    From cartpoleplusplus with MIT License 5 votes vote down vote up
def png_to_rgb(png_bytes):
  """convert png (from rgb_to_png) to RGB"""
  # note PNG is always RGBA so we need to slice off A
  rgba = plt.imread(StringIO.StringIO(png_bytes))
  return rgba[:,:,:3] 
Example #20
Source File: calculate_fid_official.py    From DeepPrivacy with MIT License 5 votes vote down vote up
def load_image_batch(files):
    """Convenience method for batch-loading images
    Params:
    -- files    : list of paths to image files. Images need to have same dimensions for all files.
    Returns:
    -- A numpy array of dimensions (num_images,hi, wi, 3) representing the image pixel values.
    """
    return np.array([imread(str(fn)).astype(np.float32) for fn in files]) 
Example #21
Source File: video.py    From phd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_images(self):
        i = 0
        fname = self.get_filename(i)
        while os.path.exists(fname):
            yield plt.imread(self.get_filename(i))
            i += 1
            fname = self.get_filename(i) 
Example #22
Source File: simulator.py    From doom-net-pytorch with MIT License 5 votes vote down vote up
def __init__(self, policy_model):
        map_image = plt.imread('/home/andr/gdrive/research/ml/doom-net-pytorch/environments/cig_map.png')
        map_image = (map_image*255).astype(np.uint8)
        self.map = np.flip(map_image, axis=0)
        map_image = plt.imread('/home/andr/gdrive/research/ml/doom-net-pytorch/environments/cig_map_walls.png')
        map_image = np.flip(map_image, axis=0)
        self.wall_points = np.transpose(np.nonzero(map_image))
        self.y_ratio = self.map.shape[0]/1856
        self.x_ratio = self.map.shape[1]/1824
        self.y_shift = 352
        self.x_shift = 448
        self.theta_shift = 90
        self.policy_model = policy_model 
Example #23
Source File: video.py    From phd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_image(self, index):
        return plt.imread(self.get_filename(index)) 
Example #24
Source File: video.py    From phd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_frame(self, index):
        """
        Read image from file.

        Args:
            index (int).

        Returns:
            Array (HxWx3).
        """
        filename = self.get_filename(index)
        return plt.imread(fname=filename) 
Example #25
Source File: test_png.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_truncated_buffer():
    b = BytesIO()
    plt.savefig(b)
    b.seek(0)
    b2 = BytesIO(b.read(20))
    b2.seek(0)

    with pytest.raises(Exception):
        plt.imread(b2) 
Example #26
Source File: test_png.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_truncated_file(tmpdir):
    d = tmpdir.mkdir('test')
    fname = str(d.join('test.png'))
    fname_t = str(d.join('test_truncated.png'))
    plt.savefig(fname)
    with open(fname, 'rb') as fin:
        buf = fin.read()
    with open(fname_t, 'wb') as fout:
        fout.write(buf[:20])

    with pytest.raises(Exception):
        plt.imread(fname_t) 
Example #27
Source File: matrix_light_printer.py    From crazyflie-lib-python with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, file_name):
        self._image = plt.imread(file_name)

        self.x_pixels = self._image.shape[1]
        self.y_pixels = self._image.shape[0]

        width = 1.0
        height = self.y_pixels * width / self.x_pixels

        self.x_start = -width / 2.0 + 0.5
        self.y_start = 0.7

        self.x_step = width / self.x_pixels
        self.y_step = height / self.y_pixels 
Example #28
Source File: finetune_vgg.py    From crvi with MIT License 5 votes vote down vote up
def load_images(image_paths):
    # Load the images from disk.
    images = [plt.imread(path) for path in image_paths]

    # Convert to a numpy array and return it.
    return np.asarray(images) 
Example #29
Source File: finetune_vgg19.py    From crvi with MIT License 5 votes vote down vote up
def load_images(image_paths):
    # Load the images from disk.
    images = [plt.imread(path) for path in image_paths]

    # Convert to a numpy array and return it.
    return np.asarray(images) 
Example #30
Source File: tests.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def WordCloudAPI(request):
        # ImgInfo.objects.filter(UserInfo_id=text).update(wordcloud=res)
        # print("更新完毕~~")
        # wordlist_after_jieba = jieba.cut(content, cut_all=False)
        # wl_space_split = " ".join(wordlist_after_jieba)
        # backgroud_Image = plt.imread(path.dirname(__file__) + '\color.png')
        # '''设置词云样式'''
        # stopwords = STOPWORDS.copy()
        # stopwords.add("哈哈") #可以加多个屏蔽词
        # wc = WordCloud(
        #     width=770,
        #     height=1200,
        #     background_color='white',# 设置背景颜色
        #     # mask=backgroud_Image,# 设置背景图片
        #     font_path=path.dirname(__file__) + '\simkai.ttf',  # 设置中文字体,若是有中文的话,这句代码必须添加,不然会出现方框,不出现汉字
        #     max_words=600, # 设置最大现实的字数
        #     stopwords=stopwords,# 设置停用词
        #     max_font_size=400,# 设置字体最大值
        #     random_state=50,# 设置有多少种随机生成状态,即有多少种配色方案
        # )
        # wc.generate_from_text(wl_space_split)#开始加载文本
        # img_colors = ImageColorGenerator(backgroud_Image)
        # wc.recolor(color_func=img_colors)#字体颜色为背景图片的颜色
        # d = path.dirname(__file__)
        # wc.to_file(path.join(d, "wc.jpg"))
        # print('生成词云成功!')
        # with open(path.dirname(__file__) + '\wc.jpg', 'rb') as f:
        #     base64_data = base64.b64encode(f.read())
        #     url = base64_data.decode()
        pass