本文整理汇总了Python中menpo.image.Image.init_from_channels_at_back方法的典型用法代码示例。如果您正苦于以下问题:Python Image.init_from_channels_at_back方法的具体用法?Python Image.init_from_channels_at_back怎么用?Python Image.init_from_channels_at_back使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类menpo.image.Image
的用法示例。
在下文中一共展示了Image.init_from_channels_at_back方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: my_2d_rasterizer
# 需要导入模块: from menpo.image import Image [as 别名]
# 或者: from menpo.image.Image import init_from_channels_at_back [as 别名]
def my_2d_rasterizer(im, fn=None, group=None, f=None, crop=False, message=None):
"""
Visualisation related function. It accepts a menpo image and renders
a **single** pair of landmarks in a new image.
The fn offers the chance to apply a custom function to the image.
ASSUMPTION: There is no check for the case of no landmarks in the image.
:param im: menpo image.
:param fn: (optional) If None, then the default .view_landmarks() is
used for visualisation, otherwise the provided function.
:param group: (optional) Used in case fn is None.
:param f: (optional) Matplotlib figure to use. Leave None, unless
you know how to modify.
:param crop: (optional) Crop the resulting visualisation to avoid the
the excessive white boundary. By default False.
:param message: (optional) If None, nothing is added in the image. If a
string is passed, then this is annotated (as text) with matplotlib
utilities, i.e. the exact same text is written in the image.
:return: menpo rasterised image.
"""
if fn is None:
f = plt.figure(frameon=False)
if group is None:
# in this case, assume that the first group of landmarks should suffice.
group = im.landmarks.group_labels[0]
r = im.view_landmarks(group=group)
else:
fn(im)
if message is not None:
assert isinstance(message, str)
st1 = 25 + 90 * crop
t = plt.annotate(message, xy=(st1, im.shape[0] - 10),
size=26, fontweight='bold', color='b')
# set background transparency
t.set_bbox(dict(color='w', alpha=0.5, edgecolor='w'))
# get the image from plt
f.tight_layout(pad=0)
# Get the pixels directly from the canvas buffer which is fast
c_buffer, shape = f.canvas.print_to_buffer()
# Turn buffer into numpy array and reshape to image
pixels_buffer = np.fromstring(c_buffer,
dtype=np.uint8).reshape(shape[::-1] + (-1,))
# Prevent matplotlib from rendering
plt.close(f)
# Ignore the Alpha channel
im_plt = Image.init_from_channels_at_back(pixels_buffer[..., :3])
# ensure that they have the same dtype as the original pixels.
dtype = im.pixels.dtype
if dtype != np.uint8:
if dtype == np.float32 or dtype == np.float64:
im_plt.pixels = im_plt.pixels.astype(dtype)
im_plt.pixels /= 255.0
else:
m1 = 'Not recognised type of original dtype ({}).'
print(m1.format(dtype))
if crop:
# # position to crop the rasterised image (hardcoded for now).
cri = (50, 60)
sh1 = im_plt.shape
im_plt = im_plt.crop((cri[0], cri[1]), (sh1[0] + cri[0], sh1[1] + cri[1]))
return im_plt
示例2: _rasterize_matplotlib
# 需要导入模块: from menpo.image import Image [as 别名]
# 或者: from menpo.image.Image import init_from_channels_at_back [as 别名]
def _rasterize_matplotlib(image, pclouds, render_lines=True, line_style='-',
line_colour='b', line_width=1, render_markers=True,
marker_style='o', marker_size=1,
marker_face_colour='b', marker_edge_colour='b',
marker_edge_width=1):
import matplotlib.pyplot as plt
# Convert image shape into 100 DPI inches
# This makes sure we maintain the original image size
image_shape = np.array(image.shape)[::-1] / 100.0
f = plt.figure(figsize=image_shape, frameon=False, dpi=100)
image.view(figure_id=f.number, figure_size=image_shape)
for k, p in enumerate(pclouds):
p.view(figure_id=f.number, render_axes=False, figure_size=image_shape,
render_lines=render_lines[k], line_style=line_style[k],
line_colour=line_colour[k], line_width=line_width[k],
render_markers=render_markers[k], marker_style=marker_style[k],
marker_size=marker_size[k],
marker_face_colour=marker_face_colour[k],
marker_edge_colour=marker_edge_colour[k],
marker_edge_width=marker_edge_width[k])
# Make sure the layout is tight so that the image is of the original size
f.tight_layout(pad=0)
# Get the pixels directly from the canvas buffer which is fast
c_buffer, shape = f.canvas.print_to_buffer()
# Turn buffer into numpy array and reshape to image
pixels_buffer = np.fromstring(c_buffer,
dtype=np.uint8).reshape(shape[::-1] + (-1,))
# Prevent matplotlib from rendering
plt.close(f)
# Ignore the Alpha channel
return Image.init_from_channels_at_back(pixels_buffer[..., :3])
示例3: _rasterize_pillow
# 需要导入模块: from menpo.image import Image [as 别名]
# 或者: from menpo.image.Image import init_from_channels_at_back [as 别名]
def _rasterize_pillow(image, pclouds, render_lines=True, line_style='-',
line_colour='b', line_width=1, render_markers=True,
marker_style='o', marker_size=1, marker_face_colour='b',
marker_edge_colour='b', marker_edge_width=1):
from PIL import ImageDraw
if any(x != '-'for x in line_style):
raise ValueError("The Pillow rasterizer only supports the '-' "
"line style.")
if any(x not in {'o', 's'} for x in marker_style):
raise ValueError("The Pillow rasterizer only supports the 'o' and 's' "
"marker styles.")
if any(x > 1 for x in marker_edge_width):
raise ValueError('The Pillow rasterizer only supports '
'marker_edge_width of 1 or 0.')
pil_im = image.as_PILImage()
draw = ImageDraw.Draw(pil_im)
line_colour = [_parse_colour(x) for x in line_colour]
marker_edge_colour = [_parse_colour(x) for x in marker_edge_colour]
marker_face_colour = [_parse_colour(x) for x in marker_face_colour]
for k in range(len(pclouds)):
p = pclouds[k]
if isinstance(p, TriMesh):
pclouds[k] = p.as_pointgraph()
points = p.points
if (render_lines[k] and line_width[k] > 0 and
hasattr(p, 'edges') and p.edges.size > 0):
edges = p.edges
lines = zip(points[edges[:, 0], :],
points[edges[:, 1], :])
for l1, l2 in lines:
draw.line([tuple(l1[::-1]), tuple(l2[::-1])],
fill=line_colour[k], width=line_width[k])
if render_markers[k] and marker_size[k] > 0:
draw_func = (draw.ellipse if marker_style[k] == 'o'
else draw.rectangle)
outline = (marker_edge_colour[k] if marker_edge_width[k] == 1
else None)
for p in points:
y, x = p
draw_func((x - marker_size[k], y - marker_size[k],
x + marker_size[k], y + marker_size[k]),
fill=marker_face_colour[k], outline=outline)
del draw
pixels = np.asarray(pil_im)
if image.n_channels == 3:
return Image.init_from_channels_at_back(pixels)
else:
return Image(pixels)
示例4: ffmpeg_importer
# 需要导入模块: from menpo.image import Image [as 别名]
# 或者: from menpo.image.Image import init_from_channels_at_back [as 别名]
def ffmpeg_importer(filepath, normalize=True, exact_frame_count=True, **kwargs):
r"""
Imports videos by streaming frames from a pipe using FFMPEG. Returns a
:map:`LazyList` that gives lazy access to the video on a per-frame basis.
There are two important environment variables that can be set to alter
the behaviour of this function:
================== ======================================
ENV Variable Definition
================== ======================================
MENPO_FFMPEG_CMD The path to the 'ffmpeg' executable.
MENPO_FFPROBE_CMD The path to the 'ffprobe' executable.
================== ======================================
Parameters
----------
filepath : `Path`
Absolute filepath of the video.
normalize : `bool`, optional
If ``True``, normalize between 0.0 and 1.0 and convert to float. If
``False`` just return whatever ffmpeg imports.
exact_frame_count: `bool`, optional
If ``True``, the import fails if ffprobe is not available
(reading from ffmpeg's output returns inexact frame count)
\**kwargs : `dict`, optional
Any other keyword arguments.
Returns
-------
image : :map:`LazyList`
A :map:`LazyList` containing :map:`Image` or subclasses per frame
of the video.
"""
reader = FFMpegVideoReader(filepath, normalize=normalize, exact_frame_count=exact_frame_count)
ll = LazyList.init_from_index_callable(lambda x: Image.init_from_channels_at_back(reader[x]), len(reader))
ll.fps = reader.fps
return ll
示例5: test_init_from_channels_at_back_less_dimensions
# 需要导入模块: from menpo.image import Image [as 别名]
# 或者: from menpo.image.Image import init_from_channels_at_back [as 别名]
def test_init_from_channels_at_back_less_dimensions():
p = np.empty([50, 60])
im = Image.init_from_channels_at_back(p)
assert im.n_channels == 1
assert im.height == 50
assert im.width == 60
示例6: test_init_from_rolled_channels
# 需要导入模块: from menpo.image import Image [as 别名]
# 或者: from menpo.image.Image import init_from_channels_at_back [as 别名]
def test_init_from_rolled_channels():
p = np.empty([50, 60, 3])
im = Image.init_from_channels_at_back(p)
assert im.n_channels == 3
assert im.height == 50
assert im.width == 60
示例7: pillow_importer
# 需要导入模块: from menpo.image import Image [as 别名]
# 或者: from menpo.image.Image import init_from_channels_at_back [as 别名]
def pillow_importer(filepath, asset=None, normalize=True, **kwargs):
r"""
Imports an image using PIL/pillow.
Different image modes cause different importing strategies.
RGB, L, I:
Imported as either `float` or `uint8` depending on normalisation flag.
RGBA:
Imported as :map:`MaskedImage` if normalize is ``True`` else imported
as a 4 channel `uint8` image.
1:
Imported as a :map:`BooleanImage`. Normalisation is ignored.
F:
Imported as a floating point image. Normalisation is ignored.
Parameters
----------
filepath : `Path`
Absolute filepath of image
asset : `object`, optional
An optional asset that may help with loading. This is unused for this
implementation.
normalize : `bool`, optional
If ``True``, normalize between 0.0 and 1.0 and convert to float. If
``False`` just pass whatever PIL imports back (according
to types rules outlined in constructor).
\**kwargs : `dict`, optional
Any other keyword arguments.
Returns
-------
image : :map:`Image` or subclass
The imported image.
"""
import PIL.Image as PILImage
if isinstance(filepath, Path):
filepath = str(filepath)
pil_image = PILImage.open(filepath)
mode = pil_image.mode
if mode == 'RGBA':
# If normalize is False, then we return the alpha as an extra
# channel, which can be useful if the alpha channel has semantic
# meanings!
if normalize:
alpha = np.array(pil_image)[..., 3].astype(np.bool)
image_pixels = _pil_to_numpy(pil_image, True, convert='RGB')
image = MaskedImage.init_from_channels_at_back(image_pixels,
mask=alpha)
else:
# With no normalisation we just return the pixels
image = Image.init_from_channels_at_back(
_pil_to_numpy(pil_image, False))
elif mode in ['L', 'I', 'RGB']:
# Greyscale, Integer and RGB images
image = Image.init_from_channels_at_back(
_pil_to_numpy(pil_image, normalize))
elif mode == '1':
# Convert to 'L' type (http://stackoverflow.com/a/4114122/1716869).
# Can't normalize a binary image
image = BooleanImage(_pil_to_numpy(pil_image, False, convert='L'),
copy=True)
elif mode == 'P':
# Convert pallete images to RGB
image = Image.init_from_channels_at_back(
_pil_to_numpy(pil_image, normalize, convert='RGB'))
elif mode == 'F': # Floating point images
# Don't normalize as we don't know the scale
image = Image.init_from_channels_at_back(
_pil_to_numpy(pil_image, False))
else:
raise ValueError('Unexpected mode for PIL: {}'.format(mode))
return image