• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python io.import_image函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: blue_peter

def blue_peter():
    import menpo.io as mio
    import h5it
    from menpo.visualize.image import glyph
    from menpo.feature import hog
    import matplotlib.pyplot as plt
    # Loading the pre-built HOG AAM
    import cPickle as pickle

    with open('/Users/pts08/hog_lfpw_aam.pkl', 'rb') as f:
        hog_aam = pickle.load(f)
    
    #hog_aam = h5it.load('/Users/pts08/sparse_hog.hdf5')
    print('Here is one I made earlier!')

    bp = mio.import_image('blue_peter.jpg')
    hog_blue_peter = hog(bp)

    plt.figure()

    plt.subplot(121)
    bp.view()
    plt.axis('off')
    plt.gcf().set_size_inches(11, 11)
    plt.title('RGB')

    plt.subplot(122)
    glyph(hog_blue_peter).view()
    plt.axis('off')
    plt.gcf().set_size_inches(11, 11)
    plt.title('HOG')

    return hog_aam
开发者ID:patricksnape,项目名称:acm_seminar_20_10_2014,代码行数:33,代码来源:seminar.py


示例2: image

    def image(self):
        if self._image is None:
            image = mio.import_image(self._image_path)
            image.crop_to_landmarks_proportion_inplace(0.5)
            self._image = image

        return self._image
开发者ID:jalabort,项目名称:alabortijcv2015,代码行数:7,代码来源:result.py


示例3: test_importing_I_no_normalise

def test_importing_I_no_normalise(is_file, mock_image):
    mock_image.return_value = PILImage.new('I', (10, 10))
    is_file.return_value = True

    im = mio.import_image('fake_image_being_mocked.jpg', normalise=False)
    assert im.shape == (10, 10)
    assert im.n_channels == 1
    assert im.pixels.dtype == np.int32
开发者ID:jacksoncsy,项目名称:menpo,代码行数:8,代码来源:io_import_test.py


示例4: test_importing_PIL_L_normalise

def test_importing_PIL_L_normalise(is_file, mock_image):
    mock_image.return_value = PILImage.new('L', (10, 10))
    is_file.return_value = True

    im = mio.import_image('fake_image_being_mocked.ppm', normalise=True)
    assert im.shape == (10, 10)
    assert im.n_channels == 1
    assert im.pixels.dtype == np.float
开发者ID:dkollias,项目名称:menpo,代码行数:8,代码来源:io_import_test.py


示例5: test_importing_PIL_P_no_normalize

def test_importing_PIL_P_no_normalize(is_file, mock_image):
    mock_image.return_value = PILImage.new('P', (10, 10))
    is_file.return_value = True

    im = mio.import_image('fake_image_being_mocked.ppm', normalize=False)
    assert im.shape == (10, 10)
    assert im.n_channels == 3
    assert im.pixels.dtype == np.uint8
开发者ID:dvdm,项目名称:menpo,代码行数:8,代码来源:io_import_test.py


示例6: test_importing_imageio_RGB_no_normalise

def test_importing_imageio_RGB_no_normalise(is_file, mock_image):

    mock_image.return_value = np.zeros([10, 10, 3], dtype=np.uint8)
    is_file.return_value = True

    im = mio.import_image('fake_image_being_mocked.jpg', normalise=False)
    assert im.shape == (10, 10)
    assert im.n_channels == 3
    assert im.pixels.dtype == np.uint8
开发者ID:dkollias,项目名称:menpo,代码行数:9,代码来源:io_import_test.py


示例7: image

    def image(self):
        if self._image is None:
            image_ = mio.import_image(self._image_path)
            image = Image(np.rollaxis(image_.pixels, -1))
            image.landmarks = image_.landmarks
            image.crop_to_landmarks_proportion_inplace(0.5)
            self._image = image

        return self._image
开发者ID:jalabort,项目名称:ijcv-2014-aam,代码行数:9,代码来源:result.py


示例8: ply_importer

def ply_importer(filepath, asset=None, texture_resolver=None, **kwargs):
    """Allows importing Wavefront (OBJ) files.

    Uses VTK.

    Parameters
    ----------
    asset : `object`, optional
        An optional asset that may help with loading. This is unused for this
        implementation.
    texture_resolver : `callable`, optional
        A callable that recieves the mesh filepath and returns a single
        path to the texture to load.
    \**kwargs : `dict`, optional
        Any other keyword arguments.

    Returns
    -------
    shape : :map:`PointCloud` or subclass
        The correct shape for the given inputs.
    """
    import vtk
    from vtk.util.numpy_support import vtk_to_numpy

    ply_importer = vtk.vtkPLYReader()
    ply_importer.SetFileName(str(filepath))

    ply_importer.Update()

    # Get the output
    polydata = ply_importer.GetOutput()

    # We must have point data!
    points = vtk_to_numpy(polydata.GetPoints().GetData()).astype(np.float)

    trilist = np.require(vtk_ensure_trilist(polydata), requirements=['C'])

    texture = None
    if texture_resolver is not None:
        texture_path = texture_resolver(filepath)
        if texture_path is not None and texture_path.exists():
            texture = mio.import_image(texture_path)

    tcoords = None
    if texture is not None:
        try:
            tcoords = vtk_to_numpy(polydata.GetPointData().GetTCoords())
        except Exception:
            pass

        if isinstance(tcoords, np.ndarray) and tcoords.size == 0:
            tcoords = None

    colour_per_vertex = None
    return _construct_shape_type(points, trilist, tcoords, texture,
                                 colour_per_vertex)
开发者ID:HaoyangWang,项目名称:menpo3d,代码行数:56,代码来源:base.py


示例9: test_importing_PIL_RGBA_normalize

def test_importing_PIL_RGBA_normalize(is_file, mock_image):
    from menpo.image import MaskedImage

    mock_image.return_value = PILImage.new('RGBA', (10, 10))
    is_file.return_value = True

    im = mio.import_image('fake_image_being_mocked.ppm', normalize=True)
    assert im.shape == (10, 10)
    assert im.n_channels == 3
    assert im.pixels.dtype == np.float
    assert type(im) == MaskedImage
开发者ID:dvdm,项目名称:menpo,代码行数:11,代码来源:io_import_test.py


示例10: test_importing_PIL_1_no_normalize

def test_importing_PIL_1_no_normalize(is_file, mock_image):
    from menpo.image import BooleanImage

    mock_image.return_value = PILImage.new('1', (10, 10))
    is_file.return_value = True

    im = mio.import_image('fake_image_being_mocked.ppm', normalize=False)
    assert im.shape == (10, 10)
    assert im.n_channels == 1
    assert im.pixels.dtype == np.bool
    assert type(im) == BooleanImage
开发者ID:dvdm,项目名称:menpo,代码行数:11,代码来源:io_import_test.py


示例11: getImageFromFile

 def getImageFromFile(path):
 
     def load_image(i):
         i = i.crop_to_landmarks_proportion(0.5)
         if i.n_channels == 3:
             i = i.as_greyscale()
         labeller(i, 'PTS', face_ibug_68_to_face_ibug_68)
         return i
     
     image_path = Path(path)
     i =  load_image(mio.import_image(image_path))
     return i
开发者ID:Deathstroke7,项目名称:lipRead,代码行数:12,代码来源:captureImage.py


示例12: test_register_image_importer

def test_register_image_importer(is_file):
    from menpo.image import Image
    image = Image.init_blank((10, 10))

    def foo_importer(filepath, **kwargs):
        return image

    is_file.return_value = True

    with patch.dict(mio.input.extensions.image_types, {}, clear=True):
        mio.register_image_importer('.foo', foo_importer)
        new_image = mio.import_image('fake.foo')
    assert image is new_image
开发者ID:dvdm,项目名称:menpo,代码行数:13,代码来源:io_import_test.py


示例13: test_importing_imageio_GIF_no_normalise

def test_importing_imageio_GIF_no_normalise(is_file, mock_image):
    mock_image.return_value.get_data.return_value = np.ones((10, 10, 3),
                                                            dtype=np.uint8)
    mock_image.return_value.get_length.return_value = 2
    is_file.return_value = True

    ll = mio.import_image('fake_image_being_mocked.gif', normalise=False)
    assert len(ll) == 2

    im = ll[0]
    assert im.shape == (10, 10)
    assert im.n_channels == 3
    assert im.pixels.dtype == np.uint8
开发者ID:dkollias,项目名称:menpo,代码行数:13,代码来源:io_import_test.py


示例14: load_images

def load_images(list_frames, frames_path, path_land, clip_name, max_images=None,
                training_images=None, crop_reading=0.3, pix_thres=330, feat=None):
    """
    Read images from the clips that are processed. The landmarks can be a different folder with the extension of pts and
    are searched as such.
    :param list_frames:         List of images that will be read and loaded.
    :param frames_path:         Path to the folder of images.
    :param path_land:           Path of the respective landmarks.
    :param clip_name:           The name of the clip being processed.
    :param max_images:          (optional) Max images that will be loaded from this clip.
    :param training_images:     (optional) List of images to append the new ones.
    :param crop_reading:        (optional) Amount of cropping the image around the landmarks.
    :param pix_thres:           (optional) If the cropped image has a dimension bigger than this, it gets cropped to this diagonal dimension.
    :param feat:                (optional) Features to be applied to the images before inserting them to the list.
    :return:                    List of menpo images.
    """
    from random import shuffle
    if not check_path_and_landmarks(frames_path, clip_name, path_land):
        return []
    if feat is None:
        feat = no_op
    if training_images is None:
        training_images = []
    shuffle(list_frames)            # shuffle the list to ensure random ones are chosen
    if max_images is None:
        max_images = len(list_frames)
    elif max_images < 0:
        print('Warning: The images cannot be negative, loading the whole list instead.')
        max_images = len(list_frames)
    cnt = 0  # counter for images appended to the list
    for frame_name in list_frames:
        try:
            im = mio.import_image(frames_path + frame_name, normalise=True)
        except ValueError:                                      # in case the extension is unknown (by menpo)
            print('Ignoring the \'image\' {}.'.format(frame_name))
            continue
        res = glob.glob(path_land + clip_name + sep + im.path.stem + '*.pts')
        if len(res) == 0:                       # if the image does not have any existing landmarks, ignore it
            continue
        elif len(res) > 1:
            #_r = randint(0,len(res)-1); #just for debugging reasons in different variable
            #ln = mio.import_landmark_file(res[_r]) # in case there are plenty of landmarks for the image, load random ones
            print('The image {} has more than one landmarks, for one person, loading only the first ones.'.format(frame_name))
        ln = mio.import_landmark_file(res[0])
        im.landmarks['PTS'] = ln
        im = crop_rescale_img(im, crop_reading=crop_reading, pix_thres=pix_thres)
        training_images.append(feat(im))
        cnt += 1
        if cnt >= max_images:
            break  # the limit of images (appended to the list) is reached
    return training_images
开发者ID:caomw,项目名称:robust_deformable_face_tracking,代码行数:51,代码来源:pipeline_aux.py


示例15: load_image

def load_image(path, reference_shape, is_training=False, group='PTS',
               mirror_image=False):
    """Load an annotated image.

    In the directory of the provided image file, there
    should exist a landmark file (.pts) with the same
    basename as the image file.

    Args:
      path: a path containing an image file.
      reference_shape: a numpy array [num_landmarks, 2]
      is_training: whether in training mode or not.
      group: landmark group containing the grounth truth landmarks.
      mirror_image: flips horizontally the image's pixels and landmarks.
    Returns:
      pixels: a numpy array [width, height, 3].
      estimate: an initial estimate a numpy array [68, 2].
      gt_truth: the ground truth landmarks, a numpy array [68, 2].
    """
    im = mio.import_image(path)
    bb_root = im.path.parent.relative_to(im.path.parent.parent.parent)
    if 'set' not in str(bb_root):
        bb_root = im.path.parent.relative_to(im.path.parent.parent)

    im.landmarks['bb'] = mio.import_landmark_file(str(Path('bbs') / bb_root / (
        im.path.stem + '.pts')))

    im = im.crop_to_landmarks_proportion(0.3, group='bb')
    reference_shape = PointCloud(reference_shape)

    bb = im.landmarks['bb'].lms.bounding_box()

    im.landmarks['__initial'] = align_shape_with_bounding_box(reference_shape,
                                                              bb)
    im = im.rescale_to_pointcloud(reference_shape, group='__initial')

    if mirror_image:
        im = utils.mirror_image(im)

    lms = im.landmarks[group].lms
    initial = im.landmarks['__initial'].lms

    # if the image is greyscale then convert to rgb.
    pixels = grey_to_rgb(im).pixels.transpose(1, 2, 0)

    gt_truth = lms.points.astype(np.float32)
    estimate = initial.points.astype(np.float32)
    return pixels.astype(np.float32).copy(), gt_truth, estimate
开发者ID:trigeorgis,项目名称:mdm,代码行数:48,代码来源:data_provider.py


示例16: test_importing_ffmpeg_GIF_no_normalize

def test_importing_ffmpeg_GIF_no_normalize(is_file, video_infos_ffprobe, pipe):
    video_infos_ffprobe.return_value = {'duration': 2, 'width': 100,
                                        'height': 150, 'n_frames': 10, 'fps': 5}
    empty_frame = np.zeros(150*100*3, dtype=np.uint8).tostring()
    pipe.return_value.stdout.read.return_value = empty_frame
    is_file.return_value = True

    ll = mio.import_image('fake_image_being_mocked.gif', normalize=False)
    assert ll.path.name == 'fake_image_being_mocked.gif'
    assert ll.fps == 5
    assert len(ll) == 10

    im = ll[0]
    assert im.shape == (150, 100)
    assert im.n_channels == 3
    assert im.pixels.dtype == np.uint8
开发者ID:dvdm,项目名称:menpo,代码行数:16,代码来源:io_import_test.py


示例17: im_read_greyscale

def im_read_greyscale(frame_name, frames_path, img_type, normalise=True):
    """
    The function reads an image with name frame_name in frames_path and returns the greyscale menpo image.
    :param frame_name:  Name of the frame .
    :param frames_path: Folder of the images (assumption that it exists).
    :param img_type:    Type/extension of the image.
    :param normalise:   (optional) Whether the image should be normalised when imported.
    :return:            Menpo greyscale image or [] if not found.
    """
    if frame_name[frame_name.rfind('.'):] != img_type:
        return []  # in case they are something different than an image
    try:
        im = mio.import_image(frames_path + frame_name, normalise=normalise)
        if im.n_channels == 3 and normalise:
            im = im.as_greyscale(mode='luminosity')
        elif im.n_channels == 3:
            im = im.as_greyscale(mode='channel', channel=1)
        return im
    except:
        print('Potentially wrong path or wrong image.')
        return []
开发者ID:caomw,项目名称:robust_deformable_face_tracking,代码行数:21,代码来源:pipeline_aux.py


示例18: mjson_importer

def mjson_importer(filepath, asset=None, texture_resolver=True, **kwargs):
    """
    Import meshes that are in a simple JSON format.

    Parameters
    ----------
    asset : `object`, optional
        An optional asset that may help with loading. This is unused for this
        implementation.
    texture_resolver : `callable`, optional
        A callable that recieves the mesh filepath and returns a single
        path to the texture to load.
    \**kwargs : `dict`, optional
        Any other keyword arguments.

    Returns
    -------
    shape : :map:`PointCloud` or subclass
        The correct shape for the given inputs.
    """
    with open(str(filepath), 'rb') as f:
        mesh_json = json.load(f)

    texture = None
    if texture_resolver is not None:
        texture_path = texture_resolver(filepath)
        if texture_path is not None and texture_path.exists():
            texture = mio.import_image(texture_path)

    points = mesh_json['points']
    trilist = mesh_json['trilist']
    tcoords = mesh_json.get('tcoords'),
    colour_per_vertex = mesh_json.get('colour_per_vertex')

    return _construct_shape_type(points, trilist, tcoords, texture,
                                 colour_per_vertex)
开发者ID:HaoyangWang,项目名称:menpo3d,代码行数:36,代码来源:base.py


示例19: wrl_importer

def wrl_importer(filepath, asset=None, texture_resolver=None, **kwargs):
    """Allows importing VRML 2.0 meshes.

    Uses VTK and assumes that the first actor in the scene is the one
    that we want.

    Parameters
    ----------
    asset : `object`, optional
        An optional asset that may help with loading. This is unused for this
        implementation.
    texture_resolver : `callable`, optional
        A callable that recieves the mesh filepath and returns a single
        path to the texture to load.
    \**kwargs : `dict`, optional
        Any other keyword arguments.

    Returns
    -------
    shape : :map:`PointCloud` or subclass
        The correct shape for the given inputs.
    """
    import vtk
    from vtk.util.numpy_support import vtk_to_numpy

    vrml_importer = vtk.vtkVRMLImporter()
    vrml_importer.SetFileName(str(filepath))
    vrml_importer.Update()

    # Get the first actor.
    actors = vrml_importer.GetRenderer().GetActors()
    actors.InitTraversal()
    mapper = actors.GetNextActor().GetMapper()
    mapper_dataset = mapper.GetInput()

    if actors.GetNextActor():
        # There was more than one actor!
        warnings.warn('More than one actor was detected in the scene. Only '
                      'single scene actors are currently supported.')

    # Get the Data
    polydata = vtk.vtkPolyData.SafeDownCast(mapper_dataset)

    # We must have point data!
    points = vtk_to_numpy(polydata.GetPoints().GetData()).astype(np.float)

    trilist = vtk_ensure_trilist(polydata)

    texture = None
    if texture_resolver is not None:
        texture_path = texture_resolver(filepath)
        if texture_path is not None and texture_path.exists():
            texture = mio.import_image(texture_path)

    # Three different outcomes - either we have a textured mesh, a coloured
    # mesh or just a plain mesh. Let's try each in turn.

    # Textured
    tcoords = None
    try:
        tcoords = vtk_to_numpy(polydata.GetPointData().GetTCoords())
    except Exception:
        pass

    if isinstance(tcoords, np.ndarray) and tcoords.size == 0:
        tcoords = None

    # Colour-per-vertex
    try:
        colour_per_vertex = vtk_to_numpy(mapper.GetLookupTable().GetTable()) / 255.
    except Exception:
        pass

    if isinstance(colour_per_vertex, np.ndarray) and colour_per_vertex.size == 0:
        colour_per_vertex = None

    return _construct_shape_type(points, trilist, tcoords, texture,
                                 colour_per_vertex)
开发者ID:HaoyangWang,项目名称:menpo3d,代码行数:78,代码来源:base.py


示例20: plot_image_latex_with_subcaptions

def plot_image_latex_with_subcaptions(folds, pb, pout, name_im, legend_names=None,
                                      normalise=None, allow_fail=False,
                                      overwr=True):
    """
    Customised function for my papers. It plots variations of an image (i.e. different
        images) next to each other with the respective legend names.
    The idea is: Import one by one from the folds, normalise (e.g. resize) and export each
        with a predictable name. Write the tex file and compile it to create the image
        with the several subplots and the custom labels.
    Attention: Because of latex compilation, this function writes and reads from the disk,
        so pay attention to the pout path.
    :param folds: (list) Names of the parent folders to search the image to. The assumption
        is that all those are relative to pb path.
    :param pb:    (str) Base path where the images to be imported exist.
    :param pout:  (str) Path to export the result in. The method will write the result in a
        new sub-folder named 'concatenated'.
    :param name_im: (str) Name (stem + suffix) of the image to be imported from folds.
    :param legend_names: (optional, list or None) If provided, it should match in length the
        folds; each one will be respectively provided as a sub-caption to the respective image.
    :param normalise: (optional, list of functions or None) If not None, then the function accepts
        a menpo image and normalises it.
    :param allow_fail: (optional, list or bool) If bool, it is converted into a list of
        length(folds). The images from folds that do not exist
        will be ignored if allow_fail is True.
    :param overwr:     (optional, bool) To overwrite or not the intermediate results written.
    :return:
    # TODO: extend the formulation to provide freedom in the number of elements per line etc.
    """
    # # short lambda for avoiding the long import command.
    import_im = lambda p, norm=False: mio.import_image(p, landmark_resolver=None,
                                                       normalize=norm)
    # # names_imout: Names of the output images in the disk.
    # # names_meth: Method of the name to put in the sub-caption.
    names_imout, names_meth = [], []
    # # if allow_fail is provided as a single boolean, convert into a list, i.e.
    # # each one of the folders has different permissions.
    if not isinstance(allow_fail, list):
        allow_fail = [allow_fail for _ in range(len(folds))]
    # # if normalise is provided as a single boolean, convert into a list.
    if not isinstance(normalise, list):
        normalise = [normalise for _ in range(len(folds))]

    for cnt, fold in enumerate(folds):
        if allow_fail[cnt]:
            # # In this case, we don't mind if an image fails.
            try:
                im = import_im(join(pb, fold, name_im))
            except:
                continue
        else:
            im = import_im(join(pb, fold, name_im))
        # # get the name for the sub-caption (legend).
        if legend_names is not None:
            if '_' in legend_names[cnt]:
                print('WARNING: `_` found on legend name, possibly issue with latex.')
            names_meth.append(legend_names[cnt])
        else:
            assert 0, 'Not implemented for now! Need to use map_to_name()'
        # # Optionally resize the image.
        if normalise[cnt]:
            im = normalise[cnt](im)
        # # export the image into the disk and append the name exported in the list.
        nn = '{}_{}'.format(Path(fold).stem, im.path.name)
        mio.export_image(im, pout + nn, overwrite=overwr)
        names_imout.append(nn)

    # # export into a file the latex command.
    nlat = Path(name_im).stem
    fo = open(pout + '{}.tex'.format(nlat),'wt')
    fo.writelines(('\\documentclass{article}\\usepackage{amsmath}'
                   '\n\\usepackage{graphicx}\\usepackage{subfig}'
                   '\\begin{document}\n'))
    list_to_latex(names_imout, wrap_subfloat=True, names_subfl=names_meth, pbl='',
                  file_to_print=fo, caption=False)
    fo.writelines('\\thispagestyle{empty}\\end{document}\n')
    fo.close()

    # # the concatenated for the final png
    pout1 = Path(mkdir_p(join(pout, 'concatenated', '')))
    # # create the png image and delete the tex and intermediate results.
    cmd = ('cd {0}; pdflatex {1}.tex; pdfcrop {1}.pdf;'
           'rm {1}.aux {1}.log {1}.pdf; mv {1}-crop.pdf {2}.pdf;'
           'pdftoppm -png {2}.pdf > {2}.png; rm {2}.pdf; rm {0}*.png; rm {0}*.tex')
    nconc = pout1.stem + sep + nlat
    return popen(cmd.format(pout, nlat, nconc))
开发者ID:grigorisg9gr,项目名称:pyutils,代码行数:85,代码来源:visualizations.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python io.import_images函数代码示例发布时间:2022-05-27
下一篇:
Python io.import_builtin_asset函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap