Python matplotlib.pyplot.imread() Examples

The following are code examples for showing how to use matplotlib.pyplot.imread(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: ai-platform   Author: produvia   File: yolo_image.py    MIT License 7 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 2
Project: Recipes   Author: Lasagne   File: massachusetts_road_dataset_utils.py    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 3
Project: lattice   Author: tensorflow   File: image_compression.py    Apache License 2.0 6 votes vote down vote up
def visualize(estimator, input_img_path, output_dir):
  """Visualizes trained estimator."""
  # This example pulls one channel, also would make sense to convert to gray
  im = plt.imread(input_img_path)[:, :, 2]
  im_pixels = _pixels(im)

  input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn(
      x={
          'pixel_x': im_pixels[:, 0],
          'pixel_y': im_pixels[:, 1]
      },
      batch_size=10000,
      num_epochs=1,
      shuffle=False)

  y_test = np.array(
      [q['predictions'] for q in estimator.predict(input_fn=input_fn)])
  img = _pixels_to_image(np.c_[im_pixels[:, :2], y_test])

  plt.figure()
  plt.imshow(img, cmap='gray')
  plt.savefig(output_dir + '/image.png')
  return img 
Example 4
Project: mdp   Author: BlackHC   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def render(self, mode='human', close=False):
        if close:
            if self.render_widget:
                self.render_widget.close()
            return

        png_data = graph_to_png(self.to_graph())

        if mode == 'human':
            # TODO: use OpenAI's SimpleImageViewer wrapper when not running in IPython.
            if not self.render_widget:
                from IPython.display import display
                import ipywidgets as widgets

                self.render_widget = widgets.Image()
                display(self.render_widget)

            self.render_widget.value = png_data
        elif mode == 'rgb_array':
            from matplotlib import pyplot
            import io
            return pyplot.imread(io.BytesIO(png_data))
        elif mode == 'png':
            return png_data 
Example 5
Project: keras-ctpn   Author: yizt   File: image_utils.py    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 6
Project: MobileNet   Author: MG2033   File: data_loader.py    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 7
Project: neptune-contrib   Author: neptune-ml   File: data.py    MIT License 6 votes vote down vote up
def _get_collated_image(filepaths, label=None, figsize=(16, 12), title_size=30):
    n = len(filepaths)
    yn = int(np.floor(np.sqrt(n)))
    xn = int(np.ceil(n / yn))

    fig, axs = plt.subplots(yn, xn, figsize=figsize)
    fig.suptitle(label, fontsize=title_size)

    for i, filepath in enumerate(filepaths):
        yi, xi = i // xn, i % xn
        image = plt.imread(filepath)
        axs[yi, xi].imshow(image)
        axs[yi, xi].set_xticks([])
        axs[yi, xi].set_yticks([])
    plt.tight_layout()
    fig.subplots_adjust(top=0.92)

    return fig 
Example 8
Project: ble5-nrf52-mac   Author: tomasero   File: test_png.py    MIT 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 9
Project: ImageCaption   Author: Mic-JasonTang   File: run.py    MIT License 6 votes vote down vote up
def show_images(result_images, filenames, probs, captions=None):
    result_images = list(result_images)
    filenames = list(filenames)
    probs = list(probs)
    #     captions = list(captions)
    nimages = np.array(result_images).shape[0]
    index = 0
    rows = 1 if (nimages < 3) else np.ceil(nimages / 3.0)
    print("rows:", rows)
    fig = plt.figure(figsize=(50, 50))
    for i in range(nimages):
        plt.subplot(rows, 3, i + 1)
        img = plt.imread(result_images[i])
        plt.imshow(img)
        plt.title("prob:" + str(probs[i]), fontsize=45)
        plt.axis("off")
    plt.tight_layout()
    plt.savefig("result.jpg")
    print("The result already in the result.jpg")
    plt.show() 
Example 10
Project: ai-ming3526   Author: xiaoming3526   File: kMeans.py    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 11
Project: BIRL   Author: Borda   File: dataset.py    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 12
Project: subtask-graph-execution   Author: srsohn   File: mazemap.py    MIT License 6 votes vote down vote up
def _load_game_asset(self):
        ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
        object_param_list = self.config.object_param_list
        self.object_image_list, self.obj_img_plt_list = [], []
        img_folder = os.path.join(ROOT_DIR, 'asset', self.gamename, 'Icon')
        for obj in object_param_list:
            image = pygame.image.load(os.path.join(img_folder, obj['imgname']))
            self.object_image_list.append(image)
            image = plt.imread(os.path.join(img_folder, obj['imgname']))
            self.obj_img_plt_list.append(image)
        self.agent_img = pygame.image.load(
            os.path.join(img_folder, 'agent.png'))
        if self.gamename == 'mining':
            self.block_img = pygame.image.load(
                os.path.join(img_folder, 'mountain.png'))
            self.water_img = pygame.image.load(
                os.path.join(img_folder, 'water.png'))
        else:
            self.block_img = pygame.image.load(
                os.path.join(img_folder, 'block.png')) 
Example 13
Project: COCO-Style-Dataset-Generator-GUI   Author: hanskrupakar   File: segment.py    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 14
Project: hfbs   Author: uwsampa   File: hfbs.py    MIT License 6 votes vote down vote up
def prepare_flow(reference, flow_tuple, confidence):
    reference_image = np.array(plt.imread(reference, format='png'), dtype=np.float32)*256
    flow = np.array(plt.imread(flow_tuple[0], format='png'), dtype=np.float32)*65536
    flow = np.subtract(flow, 2**15)
    flow = np.divide(flow, 256)

    weight = np.array(plt.imread(confidence, format='png'), dtype=np.float32)*65536
    weight = np.divide(weight, 65536)

    if VERBOSE:
        print(">>> preparing flow data")
    sz = [reference_image.shape[0], reference_image.shape[1]]

    I_x = np.tile(np.floor(np.divide(np.arange(sz[1]), BILATERAL_SIGMA_SPATIAL)), (sz[0],1))
    I_y = np.tile( np.floor(np.divide(np.arange(sz[0]), BILATERAL_SIGMA_SPATIAL)).reshape(1,-1).T, (1,sz[1]) )
    I_luma = np.floor_divide(utils.rgb2gray(reference_image), float(BILATERAL_SIGMA_LUMA))

    X = np.concatenate((I_x[:,:,None],I_y[:,:,None],I_luma[:,:,None]),axis=2).reshape((-1,3),order='F')
    W0 = np.ravel(weight.T)
    X0 = np.reshape(flow,[-1,1],order='F')
    return X, W0, X0, flow.shape 
Example 15
Project: pose-hg-3d   Author: lxy5513   File: debugger.py    GNU General Public License v3.0 6 votes vote down vote up
def save_3d(self, path):
    max_range = np.array([self.xmax-self.xmin, self.ymax-self.ymin, self.zmax-self.zmin]).max()
    Xb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(self.xmax+self.xmin)
    Yb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(self.ymax+self.ymin)
    Zb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(self.zmax+self.zmin)
    for xb, yb, zb in zip(Xb, Yb, Zb):
      self.ax.plot([xb], [yb], [zb], 'w')

    self.plt.savefig(path, bbox_inches='tight', frameon = False)

    ##################### 图片合并
    #  import pdb;pdb.set_trace()
    img_3d = plt.imread(path)
    figs = plt.figure()
    ax1 = figs.add_subplot(1,2,1)
    ax1.imshow(self.imgs['default'])

    ax2 = figs.add_subplot(1,2,2)
    ax2.imshow(img_3d)
    plt.show()
    cv2.waitKey(1000)
    plt.savefig(path) 
Example 16
Project: pypiv   Author: jr7   File: test_adaptive_piv.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    imgs = glob('images/real_ana_finger*')
    frames = [plt.imread(x) for x in imgs]

    frame_a = frames[0]
    frame_b = frames[1]

    piv = pypiv.DirectPIV(frame_a, frame_b, window_size=32,
                            search_size=32, distance=16)
    u, v = piv.correlate_frames()

    adapt_piv = pypiv.AdaptivePIV(piv, window_size=32,
                                  search_size=32, distance=16,
                                  ipmethod='cubic')
    u, v = adapt_piv.correlate_frames()

    adapt_piv = pypiv.AdaptivePIV(piv, window_size=32,
                                  search_size=32, distance=8,
                                  ipmethod='cubic')
    u, v = adapt_piv.correlate_frames()

    plt.imshow(u)
    plt.clim(-5, 5)
    plt.show() 
Example 17
Project: extract-main-objects-from-images-using-numpy   Author: kareemsuhail   File: code.py    MIT License 5 votes vote down vote up
def cutOff(image,mask,power=0.2):
    # reading both image and mask and converting them into numpy array
    image_np = np.array(plt.imread(image))
    mask_np  = np.array(plt.imread(mask))
    # note that the shape of these arrays will be :
    # ( image height,image width ,3)
    # note that 3 is constant since we are dealing with RGB image
    mask_background = mask_np[1, 1]
    # this is our reference vector  which we will use to measure difference 
    # according to it 
    start_row = image_np.shape[0] - mask_np.shape[0]
    start_col = image_np.shape[1] - mask_np.shape[1]
    # this part is just to define where should we start printing our 
    # mask over the original image ,, here we will use the right coroner as a start 
    #==============================================
    # now we want to iterate over each pixel and measure the difference 
    # then we want to calculate the percentage of difference so it is easy for us 
    # as humans to figure out if we need this pixel or not 
    # as you see we will start iterating over the mask 
    for row in range(start_row, image_np.shape[0]):
        for col in range(start_col, image_np.shape[1]):
            # reading pixel from mask
            temp_RGB_vector = mask_np[row - start_row, col - start_col]
            # measuring distance
            temp_distance = (np.sum(np.absolute(np.subtract(temp_RGB_vector.astype(np.int16), mask_background.astype(np.int16)))))
            # calculating percentage
            percent = temp_distance / sqrt((255) ** 2 + (255) ** 2 + (255) ** 2)
            # if the percent is lower than desired power do not write this pixel over
            # original image
            if percent < power:
                continue
            # if not write is
            for color in range(3):
                image_np[row, col, color] = mask_np[row - start_row, col - start_col, color]
    # Read the image from 3d numpy array it and show it
    plt.imshow(image_np)
    plt.show()
# let us test our code 
Example 18
Project: progressive_growing_of_GANs   Author: preritj   File: utils.py    MIT License 5 votes vote down vote up
def load_batch(self, idx):
        """Loads batch of images and labels
        Arguments:
            idx: List of indices
        Returns:
            (images, labels): images and labels corresponding to indices
        """
        batch_imgs = []
        for index in idx:
            img_file = self.images[index]
            img = plt.imread(img_file)[:,:,:3]  # For png, which have 4 channels
            img = self.preprocess_image(img)
            batch_imgs.append(img)
        return np.array(batch_imgs) 
Example 19
Project: where   Author: kartverket   File: sisre_plot.py    MIT License 5 votes vote down vote up
def _insert_kartverket_logo(fig):
    # TODO: Does not work!!
    logo_path = "/home/dahmic/texmf/tex/figure/kartverket_staende.png"
    img = plt.imread(logo_path)
    fig.figimage(img, xo=100, yo=100, alpha=0.15, origin="upper", zorder=1)  # , extent=[0,0,1,1])


#
# SCATTER SUPPLOTS
# 
Example 20
Project: multilabel-cnn   Author: hollygrimm   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_celeb_imgs(max_images=100):
    """Load the first `max_images` images of the celeb dataset.
    
    Returns
    -------
    imgs : list of np.ndarray
        List of the first 100 images from the celeb dataset
    
    Parameters
    ----------
    max_images : int, optional
        Description
    """
    return [plt.imread(f_i) for f_i in get_celeb_files(max_images=max_images)] 
Example 21
Project: SemanticSegmentationActiveLearning   Author: alfrunesiq   File: inference.py    MIT License 5 votes vote down vote up
def keyboard_callback(self, event):
        if event.key == "left":
            self.idx = (self.idx - 1) % len(self.filepaths)
        elif event.key == "right":
            self.idx = (self.idx + 1) % len(self.filepaths)
        self.img = plt.imread(self.filepaths[self.idx])
        self.ax.imshow(self.img)
        self.ax.set_xlabel(os.path.basename(self.filepaths[self.idx]))
        self.fig.canvas.draw() 
Example 22
Project: SemanticSegmentationActiveLearning   Author: alfrunesiq   File: inference.py    MIT License 5 votes vote down vote up
def __call__(self):
        # Wait for first image to be processed
        while len(self.filepaths) == 0:
            continue

        self.fig.canvas.mpl_connect("key_press_event", self.keyboard_callback)
        self.img = plt.imread(self.filepaths[self.idx])
        self.ax.imshow(self.img)
        self.ax.set_xlabel(os.path.basename(self.filepaths[self.idx]))
        plt.show() 
Example 23
Project: cnn   Author: vaibhavnaagar   File: tsne_img_plot.py    MIT License 5 votes vote down vote up
def get_images(name, num):
    ims = []
    titles = []
    for i in range(num):
        ims += [plt.imread(name + str(i+1) + ".jpeg")]
        t = 'Channel-' + str(i+1)
        titles += [t]
    return ims,  titles 
Example 24
Project: cnn   Author: vaibhavnaagar   File: tsne_img_plot.py    MIT License 5 votes vote down vote up
def get_images(name, num, batch_string):
    ims = []
    titles = []
    for i in range(num):
        ims += [plt.imread(name + str(i+1) + batch_string + ".jpeg")]
        t = 'Channel-' + str(i+1)
        titles += [t]
    return ims,  titles 
Example 25
Project: cnn   Author: vaibhavnaagar   File: tsne_img_plot.py    MIT License 5 votes vote down vote up
def get_images(name, num, batch_string):
    ims = []
    titles = []
    for i in range(num):
        ims += [plt.imread(name + str(i+1) + batch_string + ".jpeg")]
        t = 'Channel-' + str(i+1)
        titles += [t]
    return ims,  titles 
Example 26
Project: e2c   Author: ericjang   File: plane_data2.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, fname, env_file):
    super(PlaneData, self).__init__()
    self.cache=fname
    self.initialized=False
    self.im=plt.imread(env_file) # grayscale
    self.params=(x_dim,u_dim,T) 
Example 27
Project: interactive-deep-colorization   Author: junyanz   File: colorize_image.py    MIT License 5 votes vote down vote up
def load_image(self, input_path):
        # rgb image [CxXdxXd]
        im = cv2.cvtColor(cv2.imread(input_path, 1), cv2.COLOR_BGR2RGB)
        self.img_rgb_fullres = im.copy()
        self._set_img_lab_fullres_()

        im = cv2.resize(im, (self.Xd, self.Xd))
        self.img_rgb = im.copy()
        # self.img_rgb = sp.misc.imresize(plt.imread(input_path),(self.Xd,self.Xd)).transpose((2,0,1))

        self.img_l_set = True

        # convert into lab space
        self._set_img_lab_()
        self._set_img_lab_mc_() 
Example 28
Project: NICE   Author: Lancer555   File: msr_demosaic.py    MIT License 5 votes vote down vote up
def read_pair_imgs(self, id):
        gt = plt.imread(os.path.join(self.dir_path, 'groundtruth', id + '.png'))[:, :, :3] - 0.5 # to check the mean ~0.17, std ~0.104   ,np.mean( np.resize( np.transpose(  plt.imread(os.path.join(self.dir_path, 'groundtruth', id + '.png'))[:, :, :3]  , (2,0,1) ) ,(3,290040) ) , axis=1 )
        gt = np.transpose(gt, (2, 0, 1))

        mosaiced = plt.imread(os.path.join(self.dir_path, 'input', id + '.png'))
        image = utils.mosaic_then_demosaic(mosaiced, 'rggb') - 0.5
        return image, gt 
Example 29
Project: nmc_met_graphics   Author: nmcdev   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def add_logo(fig, x=10, y=10, zorder=100,
             which='nmc', size='medium', **kwargs):
    """

    :param fig: `matplotlib.figure`, The `figure` instance used for plotting
    :param x: x position padding in pixels
    :param y: y position padding in pixels
    :param zorder: The zorder of the logo
    :param which: Which logo to plot 'nmc', 'cmc'
    :param size: Size of logo to be used. Can be:
                 'small' for 40 px square
                 'medium' for 75 px square
                 'large' for 150 px square.
    :param kwargs:
    :return: `matplotlib.image.FigureImage`
             The `matplotlib.image.FigureImage` instance created.
    """
    fname_suffix = {
        'small': '_small.png', 'medium': '_medium.png',
        'large': '_large.png'}
    fname_prefix = {'nmc': 'nmc', 'cma': 'cma'}
    try:
        fname = fname_prefix[which] + fname_suffix[size]
        fpath = "resources/logo/" + fname
    except KeyError:
        raise ValueError('Unknown logo size or selection')

    logo = plt.imread(pkg_resources.resource_filename(
        'nmc_met_graphics', fpath))
    return fig.figimage(logo, x, y, zorder=zorder, **kwargs) 
Example 30
Project: SDCND_Behavioral_Cloning   Author: andrewraharjo   File: preprocess.py    MIT License 5 votes vote down vote up
def load_image(data_line, j):
    img = plt.imread(data_line[j].strip())[65:135:4,0:-1:4,0]
    lis = img.flatten().tolist()
    return lis 
Example 31
Project: Mask-R-CNN-sports-action-fine-tuing   Author: adelmassimo   File: actionCLSS_dataset_partitioned.py    MIT License 5 votes vote down vote up
def load_image(self, image_id):

        info = self.image_info[image_id]
        image = plt.imread(info['path'])

        return image 
Example 32
Project: Mask-R-CNN-sports-action-fine-tuing   Author: adelmassimo   File: actionCLSS_dataset.py    MIT License 5 votes vote down vote up
def load_image(self, image_id):

        info = self.image_info[image_id]
        image = plt.imread(info['path'])

        return image 
Example 33
Project: social-lstm-tf   Author: fjhheras   File: create_obstacle_map.py    GNU General Public License v3.0 5 votes vote down vote up
def convert_to_obstacle_map(img):
    '''
    Function to create an obstacle map from the annotaetd image
    params:
    img : Image file path
    '''
    im = plt.imread(img)
    # im is a numpy array of shape (w, h, 4)
    w = im.shape[0]
    h = im.shape[1]

    obs_map = np.ones((w, h))

    for i in range(w):
        for j in range(h):
            # rgba is a 4-dimensional vector
            rgba = im[i, j]
            # obstacle
            if rgba[0] == 0 and rgba[1] == 0 and rgba[2] == 0:
                # print "Obstacle found"
                obs_map[i, j] = 0
            # Partially traversable
            elif rgba[0] == 0 and rgba[1] == 0:
                # print "Partially traversable found"
                obs_map[i, j] = 0.5

    return obs_map 
Example 34
Project: crappy   Author: LaboratoireMecaniqueLille   File: drawing.py    GNU General Public License v2.0 5 votes vote down vote up
def prepare(self):
    plt.switch_backend(self.backend)
    self.fig, self.ax = plt.subplots(figsize=self.window_size)
    image = self.ax.imshow(plt.imread(self.image), cmap=cm.coolwarm)
    image.set_clim(-0.5, 1)
    cbar = self.fig.colorbar(image, ticks=[-0.5, 1], fraction=0.061,
        orientation='horizontal', pad=0.04)
    cbar.set_label('Temperatures(C)')
    cbar.ax.set_xticklabels(self.crange)
    self.ax.set_title(self.title)
    self.ax.set_axis_off()

    self.elements = []
    for d in self.draw:
      self.elements.append(elements[d['type']](self,**d)) 
Example 35
Project: csgm   Author: AshishBora   File: view_estimated_celebA.py    MIT License 5 votes vote down vote up
def view(xs_dict, patterns, images_nums, hparams, **kws):
    """View the images"""
    x_hats_dict = {}
    for model_type, pattern in zip(hparams.model_types, patterns):
        outfiles = [pattern.format(i) for i in images_nums]
        x_hats_dict[model_type] = {i: 2*plt.imread(outfile)-1 for i, outfile in enumerate(outfiles)}
    xs_dict_temp = {i : xs_dict[i] for i in images_nums}
    utils.image_matrix(xs_dict_temp, x_hats_dict, view_image, hparams, **kws) 
Example 36
Project: csgm   Author: AshishBora   File: view_estimated_mnist.py    MIT License 5 votes vote down vote up
def view(xs_dict, patterns, images_nums, hparams, **kws):
    """View the images"""
    x_hats_dict = {}
    for model_type, pattern in zip(hparams.model_types, patterns):
        outfiles = [pattern.format(i) for i in images_nums]
        x_hats_dict[model_type] = {i: plt.imread(outfile) for i, outfile in enumerate(outfiles)}
    xs_dict_temp = {i : xs_dict[i] for i in images_nums}
    utils.image_matrix(xs_dict_temp, x_hats_dict, view_image, hparams, **kws) 
Example 37
Project: deblur-devil   Author: visinf   File: matlab.py    Apache License 2.0 5 votes vote down vote up
def imread(filename):
    return plt.imread(filename) 
Example 38
Project: deblur-devil   Author: visinf   File: common.py    Apache License 2.0 5 votes vote down vote up
def read_image_as_float32(filename):
    return plt.imread(filename).astype(np.float32) / np.float32(255.0) 
Example 39
Project: deblur-devil   Author: visinf   File: common.py    Apache License 2.0 5 votes vote down vote up
def read_image_as_byte(filename):
    return plt.imread(filename) 
Example 40
Project: Quality-Control-using-Deep-Learning-   Author: Tandon-A   File: prepdatalist.py    MIT License 5 votes vote down vote up
def getpatches_sub(imgpath,imgsetx,imgno,gw,gh,nw,nh):
  img = Image.open(imgpath)
  img = np.array(img,dtype=np.float32)
  img = np.divide(img,255.0)
  img = np.reshape(img,(gw,gh,1))
  pltimg = plt.imread(imgpath)
  ax = plt.gca()
  fig = plt.gcf()
  ax.imshow(pltimg,cmap="gray")
  text_count = ax.text(0,0,"count= 0")
  #creating a mouse click listener
  fig.canvas.mpl_connect('button_press_event', lambda event: onclick(event,ax,text_count,imgno,imgsetx,gw,gh,nw,nh))
  plt.show()
  return fig 
Example 41
Project: gm-cml   Author: wangyida   File: linearae.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_myown_imgs(direc):
    scan=ScanFile(direc)
    files_img=scan.scan_files()
    return [plt.imread(f_i) for f_i in files_img]

# Write a function to preprocess/normalize an image, given its dataset object
# (which stores the mean and standard deviation!) 
Example 42
Project: gm-cml   Author: wangyida   File: train_linearae.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_myown_imgs(direc):
    scan=ScanFile(direc)
    files_img=scan.scan_files()
    return [plt.imread(f_i) for f_i in files_img]

# Write a function to preprocess/normalize an image, given its dataset object
# (which stores the mean and standard deviation!) 
Example 43
Project: gm-cml   Author: wangyida   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_celeb_imgs(max_images=100):
    """Load the first `max_images` images of the celeb dataset.

    Returns
    -------
    imgs : list of np.ndarray
        List of the first 100 images from the celeb dataset
    """
    return [plt.imread(f_i) for f_i in get_celeb_files(max_images=max_images)] 
Example 44
Project: TecoGAN   Author: zhusiling   File: util.py    Apache License 2.0 5 votes vote down vote up
def load_image(path):
    if(path[-3:] == 'dng'):
        import rawpy
        with rawpy.imread(path) as raw:
            img = raw.postprocess()
        # img = plt.imread(path)
    elif(path[-3:]=='bmp' or path[-3:]=='jpg' or path[-3:]=='png'):
        import cv2
        return cv2.imread(path)[:,:,::-1]
    else:
        img = (255*plt.imread(path)[:,:,:3]).astype('uint8')

    return img 
Example 45
Project: Text-Recognition   Author: mayank-git-hub   File: meta_own.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def calc_average(self, train):

		image_average = [np.zeros(3), 0]
		image_std = [np.zeros(3), 0]

		random_images = np.random.choice(train, min(1000, len(train)), replace=False)

		for i in random_images:

			image = plt.imread(self.config['metadata']['OWN']['image']+'/'+i)
			if len(image.shape) == 2:
				continue
			image_average[0] += np.sum(image, axis=(0, 1))
			image_average[1] += image.shape[0]*image.shape[1]

		image_average[0] = image_average[0]/image_average[1]

		for i in random_images:

			image = plt.imread(self.config['metadata']['OWN']['image']+'/'+i)
			if len(image.shape) == 2:
				continue
			image_std[0] += np.sum(np.square(image - image_average[0]), axis=(0, 1))
			image_std[1] += image.shape[0]*image.shape[1]

		image_std[0] = image_std[0]/image_std[1]

		with open(self.config['metadata']['OWN']['meta']+'/normalisation_'+str(train_ratio)+'.pkl', 'wb') as f:
			pickle.dump({'average': image_average, 'std': image_std}, f) 
Example 46
Project: Text-Recognition   Author: mayank-git-hub   File: meta_ic15.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def calc_average(self, train):

		image_average = [np.zeros(3), 0]
		image_std = [np.zeros(3), 0]

		random_images = np.random.choice(train, min(1000, len(train)), replace=False)

		for i in random_images:

			image = plt.imread(self.config['metadata']['IC15']['image']+'/'+i)
			if len(image.shape) == 2:
				continue
			image_average[0] += np.sum(image, axis=(0, 1))
			image_average[1] += image.shape[0]*image.shape[1]

		image_average[0] = image_average[0]/image_average[1]

		for i in random_images:

			image = plt.imread(self.config['metadata']['IC15']['image']+'/'+i)
			if len(image.shape) == 2:
				continue
			image_std[0] += np.sum(np.square(image - image_average[0]), axis=(0, 1))
			image_std[1] += image.shape[0]*image.shape[1]

		image_std[0] = image_std[0]/image_std[1]

		with open(self.config['metadata']['IC15']['meta']+'/normalisation_'+str(train_ratio)+'.pkl', 'wb') as f:
			pickle.dump({'average': image_average, 'std': image_std}, f) 
Example 47
Project: Text-Recognition   Author: mayank-git-hub   File: meta_coco.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def calc_average(self, train):

		image_average = [np.zeros(3), 0]
		image_std = [np.zeros(3), 0]

		random_images = np.random.choice(train, min(1000, len(train)), replace=False)

		for i in random_images:

			image = plt.imread(self.config['metadata']['COCO']['image']+'/'+i)
			if len(image.shape) == 2:
				continue
			image_average[0] += np.sum(image, axis=(0, 1))
			image_average[1] += image.shape[0]*image.shape[1]

		image_average[0] = image_average[0]/image_average[1]

		for i in random_images:

			image = plt.imread(self.config['metadata']['COCO']['image']+'/'+i)
			if len(image.shape) == 2:
				continue
			image_std[0] += np.sum(np.square(image - image_average[0]), axis=(0, 1))
			image_std[1] += image.shape[0]*image.shape[1]

		image_std[0] = image_std[0]/image_std[1]

		with open(self.config['metadata']['COCO']['meta']+'/normalisation_'+str(train_ratio)+'.pkl', 'wb') as f:
			pickle.dump({'average': image_average, 'std': image_std}, f)

		#This function reads the images from JSON file format and splits into testing and training images 
Example 48
Project: Text-Recognition   Author: mayank-git-hub   File: meta_ic13.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def calc_average(self, train):

		image_average = [np.zeros(3), 0]
		image_std = [np.zeros(3), 0]

		random_images = np.random.choice(train, min(1000, len(train)), replace=False)

		for i in random_images:

			image = plt.imread(self.config['metadata']['IC13']['image']+'/'+i)
			if len(image.shape) == 2:
				continue
			image_average[0] += np.sum(image, axis=(0, 1))
			image_average[1] += image.shape[0]*image.shape[1]

		image_average[0] = image_average[0]/image_average[1]

		for i in random_images:

			image = plt.imread(self.config['metadata']['IC13']['image']+'/'+i)
			if len(image.shape) == 2:
				continue
			image_std[0] += np.sum(np.square(image - image_average[0]), axis=(0, 1))
			image_std[1] += image.shape[0]*image.shape[1]

		image_std[0] = image_std[0]/image_std[1]

		with open(self.config['metadata']['IC13']['meta']+'/normalisation_'+str(train_ratio)+'.pkl', 'wb') as f:
			pickle.dump({'average': image_average, 'std': image_std}, f) 
Example 49
Project: ble5-nrf52-mac   Author: tomasero   File: test_png.py    MIT 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 50
Project: ble5-nrf52-mac   Author: tomasero   File: test_png.py    MIT 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)