当前位置: 首页>>代码示例>>Python>>正文


Python data.imread函数代码示例

本文整理汇总了Python中skimage.data.imread函数的典型用法代码示例。如果您正苦于以下问题:Python imread函数的具体用法?Python imread怎么用?Python imread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了imread函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: loadImage

def loadImage(path, basename='', color='rgb'):
  ''' Load JPEG image from file, 

      Returns
      --------
      IM : 2D or 3D array, size H x W x nColors
           dtype will be float64, with each pixel in range (0,1)
  '''
  path = str(path)
  if len(basename) > 0:
    path = os.path.join(path, basename)
  if color == 'gray' or color == 'grey':
    IM = imread(path, as_grey=True)
    assert IM.ndim == 2
  else:
    IM = imread(path, as_grey=False)
    if not IM.ndim == 3:
      raise ValueError('Color image not available.')

  if IM.dtype == np.float:
    MaxVal = 1.0
  elif IM.dtype == np.uint8:
    MaxVal = 255
  else:
    raise ValueError("Unrecognized dtype: %s" % (IM.dtype))
  assert IM.min() >= 0.0
  assert IM.max() <= MaxVal

  IM = np.asarray(IM, dtype=np.float64)
  if MaxVal > 1:
    IM /= MaxVal
  return IM
开发者ID:michaelchughes,项目名称:satdetect,代码行数:32,代码来源:IOUtil.py

示例2: main

def main():
    for file_path in glob.glob("/home/lucas/Downloads/Lucas/GSK 10uM/*.JPG"):

        img = data.imread(file_path, as_grey=True)

        img = transform.resize(img, [600, 600])
        img_color = transform.resize(data.imread(file_path), [600, 600])

        img[img >img.mean()-0.1] = 0

        # io.imshow(img)
        # io.show()
        #
        edges = canny(img)
        bordas_fechadas = closing(img > 0.1, square(15)) # fechando gaps
        fill_cells = ndi.binary_fill_holes(bordas_fechadas)
        # io.imshow(fill_cells)
        # io.show()
        img_label = label(fill_cells, background=0)
        n= 0
        for  x in regionprops(img_label):
            if x.area < 2000 and x.area > 300:
                n +=1
                print x.area
                minr, minc, maxr, maxc = x.bbox
                try:
                    out_path_name = file_path.split("/")[-1].rstrip(".JPG")
                    io.imsave("out/cell_{}_pic_{}_area_{}.png".format(n, out_path_name, str(round(x.area))),img_color[minr-3: maxr+3, minc-3: maxc+3])
                    #io.show()
                except:
                    pass
开发者ID:LucasSilvaFerreira,项目名称:egg_finder,代码行数:31,代码来源:microscopia_eggs.py

示例3: load

def load(pos_dir, neg_dir, hard_examples=[]):
    gc.disable()
    images, labels = [], []
    files = listdir(pos_dir)
    for i, f in enumerate(files):
        if not is_image(f):
            continue
        if "hard_example" in f and (
            hard_examples is None or not any([f.startswith(prefix) for prefix in hard_examples])
        ):
            continue
        if i > 0 and i % 1000 == 0:
            print "loaded {0}/{1} positive".format(i, len(files))
        images.append(data.imread(join(pos_dir, f))[:, :, :3])
        labels.append(1)
    files = listdir(neg_dir)
    for i, f in enumerate(files):
        if not is_image(f):
            continue
        if "hard_example" in f and (
            hard_examples is None or not any([f.startswith(prefix) for prefix in hard_examples])
        ):
            continue
        if i > 0 and i % 1000 == 0:
            print "loaded {0}/{1} negative".format(i, len(files))
        images.append(data.imread(join(neg_dir, f))[:, :, :3])
        labels.append(0)
    gc.enable()
    return images, labels
开发者ID:ahadviger,项目名称:pedestrian-detection,代码行数:29,代码来源:load.py

示例4: main

def main():
  imgs = MultiImage(data_dir + '/multipage.tif')

  for a, i in zip(range(0, 4), [1, 9, 7, 8]):
    fig = plt.figure()
    ax = fig.add_axes([-0.1, -0.1, 1.2, 1.2])
    # ax.set_axis_off()
    im = data.imread('samolot0' + str(i) + '.jpg', as_grey = True)
    im = invert(im)
    im = process(im)
    out = np.ones_like(im)
    io.imshow(out)
    contours = measure.find_contours(im, 0.9)
    for n, contour in enumerate(contours):
      plt.plot(contour[:, 1], contour[:, 0], linewidth=2, color = 'white')
    plt.savefig(str(a) + '.jpg', bbox_inches = 0, frameon = False)

  fig = plt.figure()
  grid = AxesGrid(fig, rect = (1, 1, 1), nrows_ncols = (2, 2), axes_pad = 0.1)

  for i in range(0, 4):
    frame = data.imread(str(i) + '.jpg')
    grid[i].imshow(frame)
    grid[i].set_xticks([])
    grid[i].set_yticks([])

  plt.savefig('na3.jpg')
开发者ID:ja999,项目名称:sem5,代码行数:27,代码来源:na3.py

示例5: process

def process():
    data = {
            0: 0,
            1: 0,
            2: 0,
            3: 0,
            4: 0,
            5: 0,
            6: 0,
            7: 0,
            8: 0,
            }
    sobel_v_image = imread('sobel_v2.jpg')
    sobel_h_image = imread('sobel_h2.jpg')
    canny_image = imread('canny2.jpg')
    row, col = canny_image.shape
    for r in xrange(row):
        for c in xrange(col):
            if sobel_v_image[r][c] < 0 or sobel_h_image[r][c] < 0:
                print sobel_v_image[r][c], sobel_h_image[r][c]
            if canny_image[r][c] != 255:
                continue
            interval = which_interval(sobel_v_image[r][c], sobel_h_image[r][c])
            data[interval] += 1

    print data
开发者ID:yidinghan,项目名称:graduation-project,代码行数:26,代码来源:cal_gradients.py

示例6: read_files

def read_files(dir, dataset):
    """
    yield data_type(train? val? test?), numpy.ndarray('uint8')
    """
    dir_path = os.path.join(dir,dataset)
    if dataset=='train':
        for(root, dirs, files) in os.walk(dir_path):
            for file in files:
                if not '.txt' in file:
                    label = file.split("_")[0]
                    img_filepath = os.path.join(root,file)
                    yield label, data.imread(img_filepath)
    elif dataset=='val':
        for(root, dirs, files) in os.walk(dir_path):
            for file in files:
                if '.txt' in file:
                    # this is val_annotaions.txt
                    f = open(os.path.join(root,file), 'r')
                    while 1:
                        line = f.readline()
                        if not line: break
                        line_seg = line.split()
                        img_filepath = os.path.join(root,'images',line_seg[0])
                        label = line_seg[1]
                        yield label, data.imread(img_filepath)
                    f.close()
开发者ID:HunjaeJung,项目名称:imagenet2014-modified,代码行数:26,代码来源:tinyimagenet.py

示例7: main

def main():
    plt.figure(figsize=(25, 24))
    planes = ['samolot00.jpg', 'samolot01.jpg', 'samolot03.jpg', 'samolot04.jpg', 'samolot05.jpg','samolot07.jpg',
              'samolot08.jpg', 'samolot09.jpg', 'samolot10.jpg', 'samolot11.jpg', 'samolot12.jpg', 'samolot13.jpg',
              'samolot14.jpg', 'samolot15.jpg', 'samolot16.jpg', 'samolot17.jpg', 'samolot18.jpg', 'samolot20.jpg']
    i = 1
    for file in planes:
        img = data.imread(file, as_grey=True)
        img2 = data.imread(file)
        ax = plt.subplot(6, 3, i)
        ax.axis('off')
        img **= 0.4
        img = filter.canny(img, sigma=3.0)
        img = morphology.dilation(img, morphology.disk(4))
        img = ndimage.binary_fill_holes(img)
        img = morphology.remove_small_objects(img, 1000)
        contours = measure.find_contours(img, 0.8)
        ax.imshow(img2, aspect='auto')
        for n, contour in enumerate(contours):
            ax.plot(contour[:, 1], contour[:, 0], linewidth=1.5)
            center = (sum(contour[:, 1])/len(contour[:, 1]), sum(contour[:, 0])/len(contour[:, 0]))
            ax.scatter(center[0], center[1], color='white')
        i += 1

    plt.savefig('zad2.pdf')
开发者ID:gracz21,项目名称:KCK,代码行数:25,代码来源:Zad_2.py

示例8: read_image

def read_image(name, size=None, debug=False):
    """ read image and segmentation, returns RGB + alpha composite """
    image = imread(name) / 255.

    if image.shape[2] == 4:
        alpha = image[...,3]
        image = image[...,:3]
    else:
        segmentation_name = os.path.splitext(name)[0][:-6] + '-label.png'
        segmentation = imread(segmentation_name)
        alpha = np.logical_or(segmentation[...,0], segmentation[...,1]) * 1.

    if size is not None:
        scale_x = float(size[0]) / image.shape[1]
        scale_y = float(size[1]) / image.shape[0]
        scale = min(scale_x, scale_y)

        if debug:
            print name, size[0], size[1], image.shape[1], image.shape[0], scale, image.shape[1]*scale, image.shape[0]*scale

        if scale > 1.0:
            print 'Image %s smaller than requested size' % name

        if scale != 1.0:
            image = rescale(image, scale, order=3)
            alpha = rescale(alpha, scale, order=0)

    return np.dstack((image, alpha))
开发者ID:cmusatyalab,项目名称:dermshare,代码行数:28,代码来源:util.py

示例9: Comparer_image_plot

def Comparer_image_plot(NumImg):
    
    liste1 = os.listdir("images")
    for i in liste1:
        if str(NumImg) in i:
            ImgPolyp = i
            break
    liste2 = os.listdir("graph_images12")
    for j in liste2:
        if str(NumImg) in j:
            PlotPolyp = j
            break
    
    polDia = data.imread("images\\"+ ImgPolyp)
    
    polDia_plot = data.imread("graph_images12\\"+ PlotPolyp)
    
    plt.subplot(1,2,1)
    plt.title("Image initiale:" + ImgPolyp)
    plt.imshow(polDia)
    
    plt.subplot(1,2,2)
    plt.title("Graph image apres analyse:"+ PlotPolyp)
    plt.imshow(polDia_plot)
    plt.show()
开发者ID:elekhac,项目名称:Projet_Polype,代码行数:25,代码来源:ComparisonTool.py

示例10: xformImage

def xformImage(filename, doPlot=False):
    
    #config area
    
    sigma=4
    mean_multiplier=2
    
    #end config area
    
#     img_gray = misc.imread(filename, True)
    img_gray = imread(filename, as_grey=True)
    img_color = imread(filename)
#     print(img_color.shape)
#     img_gray = resize(skimage.img_as_float(img_gray), (400,400))
    
    img_color_masked = copy.deepcopy(img_color)
#     img_color_masked = resize(img_color_masked, (400,400))
#     img_color_resized = resize(img_color, (200,200))
#     img_color = misc.imread(filename, False)
    
    img_gray = ndimage.gaussian_filter(img_gray, sigma=sigma)
    
    m,n = img_gray.shape
    
#     sx = ndimage.sobel(img_gray, axis=0, mode='constant')
#     sy = ndimage.sobel(img_gray, axis=1, mode='constant')
#     sob = np.hypot(sx, sy)
    
    mask = (img_gray > img_gray.mean()*mean_multiplier).astype(np.float)
    
    labels = morphology.label(mask)
    
    center_label = labels[m/2, m/2]
    
    labels[labels != center_label] = 0
    labels[labels == center_label] = 1
    
#     img_test = copy.deepcopy(img_color)
    
#     img_test[ labels == 0, : ] = 0
#     sob [ labels == 0] = 0
    img_color_masked [labels == 0, :] = 0
#     img_test = ndimage.gaussian_filter(img_test, 3)
    if doPlot:
        f, (ax_gray, ax_color, ax_sob) = plt.subplots(ncols=3)
        ax_gray.imshow(img_color_masked, cmap=plt.cm.get_cmap('gray'))
        ax_gray.axis('off')
#         ax_sob.imshow(sob, cmap=plt.cm.get_cmap('gray'))
        ax_sob.axis('off')
        ax_color.imshow(img_color, cmap=plt.cm.get_cmap('gray'))
        ax_color.axis('off')
        plt.show()    
    
    
    return np.reshape(img_color_masked, -1)
开发者ID:hansod1,项目名称:ml,代码行数:55,代码来源:vectorize_jpgs.py

示例11: load_image

    def load_image(path, as_grey=False, to_float=True):

        if DEBUG:
            im = imread(path, as_grey)
            im = (im - np.amin(im) * 1.0) / (np.amax(im) - np.amin(im))
            return im

        # Load image
        image = imread(path, as_grey)

        if to_float:
            # Convert to floating point matrix
            image = image.astype(np.float32)

        return image
开发者ID:StefanoD,项目名称:ComputerVision,代码行数:15,代码来源:libcore.py

示例12: getseg

def getseg(gt_prefix, gt_ext, imname, fg_cat):
    path_name, ext = os.path.splitext(imname)
    gt_name = os.path.join(gt_prefix, '%s_gt.%s'%(path_name,gt_ext))
    #pdb.set_trace()
    seg = imread(gt_name)
    seg = [seg == fg_cat]
    return seg
开发者ID:hmilhy,项目名称:vlblocks-python,代码行数:7,代码来源:block_hist.py

示例13: load_scenes

def load_scenes(filename):
    zipped_scenes = []
    print 'Working on: ' + filename
    img = data.imread('scenes/' + filename, as_grey=True)
    tmp = img
    tmp = filter.canny(tmp, sigma=2.0)
    tmp = ndimage.binary_fill_holes(tmp)
    #tmp = morphology.dilation(tmp, morphology.disk(2))
    tmp = morphology.remove_small_objects(tmp, 2000)
    contours = measure.find_contours(tmp, 0.8)
    ymin, xmin = contours[0].min(axis=0)
    ymax, xmax = contours[0].max(axis=0)
    if xmax - xmin > ymax - ymin:
        xdest = 1000
        ydest = 670
    else:
        xdest = 670
        ydest = 1000
    src = np.array(((0, 0), (0, ydest), (xdest, ydest), (xdest, 0)))
    dst = np.array(((xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)))
    tform3 = tf.ProjectiveTransform()
    tform3.estimate(src, dst)
    warped = tf.warp(img, tform3, output_shape=(ydest, xdest))
    tmp = filter.canny(warped, sigma=2.0)
    tmp = morphology.dilation(tmp, morphology.disk(2))
    descriptor_extractor.detect_and_extract(tmp)
    obj_key = descriptor_extractor.keypoints
    scen_desc = descriptor_extractor.descriptors
    zipped_scenes.append([warped, scen_desc, obj_key, filename])
    return zipped_scenes
开发者ID:gracz21,项目名称:KCK,代码行数:30,代码来源:image.py

示例14: pestFeatureExtraction

def pestFeatureExtraction(filename):
	selem = disk(8)
	image = data.imread(filename,as_grey=True)
	thresh = threshold_otsu(image)
	elevation_map = sobel(image)
	markers = np.zeros_like(image)

	if ((image<thresh).sum() > (image>thresh).sum()):
		markers[image < thresh] = 1
		markers[image > thresh] = 2
	else:
		markers[image < thresh] = 2
		markers[image > thresh] = 1

	segmentation = morphology.watershed(elevation_map, markers)
	segmentation = dilation(segmentation-1, selem)
	segmentation = ndimage.binary_fill_holes(segmentation)

	segmentation = np.logical_not(segmentation)
	image[segmentation]=0;

	hist = np.histogram(image.ravel(),256,[0,1])

	hist = list(hist[0])
	hist[:] = [float(x) / (sum(hist) - hist[0]) for x in hist]
	hist.pop(0)

	features = np.empty( (1, len(hist)), 'float' )
	
	a = np.array(list(hist))
	f = a.astype('float')
	features[0,:]=f[:]

	return features
开发者ID:SPKhan,项目名称:sarai-pest-diseases,代码行数:34,代码来源:api.py

示例15: main

def main():
    def shutdown(signal, widget):
        exit()
    signal.signal(signal.SIGINT, shutdown)
    app = QtGui.QApplication(sys.argv)

    timer = QtCore.QTimer()
    timer.start(500)
    timer.timeout.connect(lambda: None)

    loaded = lh.load_files(str(DATA_PATH), filter_unfinished=False)
    for l in loaded:
        jpg_io = io.BytesIO(l['jpg_image'])
        l['image'] = imread(jpg_io)
        l['save_path'] = os.path.join(DATA_PATH, l['filename'])
        if 'edited' not in l:
            l['edited'] = False

    dh.triangulation(
        loaded,
        do_triangulation=tr.triangulation,
        do_import=partial(dh.import_bone, SEGMENTATION_METHODS)
    )

    sys.exit(app.exec_())
开发者ID:selaux,项目名称:master-of-bones,代码行数:25,代码来源:triangulation_helper.py


注:本文中的skimage.data.imread函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。