本文整理匯總了Python中PIL.Image.html方法的典型用法代碼示例。如果您正苦於以下問題:Python Image.html方法的具體用法?Python Image.html怎麽用?Python Image.html使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類PIL.Image
的用法示例。
在下文中一共展示了Image.html方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: brightness
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def brightness(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of a single image, randomly or non-randomly.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
gamma : float, small than 1 means brighter.
Non negative real number. Default value is 1.
- If is_random is True, gamma in a range of (1-gamma, 1+gamma).
gain : float
The constant multiplier. Default value is 1.
is_random : boolean, default False
- If True, randomly change brightness.
References
-----------
- `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`_
- `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`_
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
x = exposure.adjust_gamma(x, gamma, gain)
return x
示例2: dilation
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def dilation(x, radius=3):
""" Return greyscale morphological dilation of an image,
see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`_.
Parameters
-----------
x : 2D array image.
radius : int for the radius of mask.
"""
from skimage.morphology import disk, dilation
mask = disk(radius)
x = dilation(x, selem=mask)
return x
## Sequence
示例3: pil_to_array
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def pil_to_array(pilImage):
"""Load a `PIL image`_ and return it as a numpy array.
.. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
Returns
-------
numpy.array
The array shape depends on the image type:
- (M, N) for grayscale images.
- (M, N, 3) for RGB images.
- (M, N, 4) for RGBA images.
"""
if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
# return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
return np.asarray(pilImage)
elif pilImage.mode.startswith('I;16'):
# return MxN luminance array of uint16
raw = pilImage.tobytes('raw', pilImage.mode)
if pilImage.mode.endswith('B'):
x = np.frombuffer(raw, '>u2')
else:
x = np.frombuffer(raw, '<u2')
return x.reshape(pilImage.size[::-1]).astype('=u2')
else: # try to convert to an rgba image
try:
pilImage = pilImage.convert('RGBA')
except ValueError:
raise RuntimeError('Unknown image mode')
return np.asarray(pilImage) # return MxNx4 RGBA array
示例4: rotation
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def rotation(x, rg=20, is_random=False, row_index=0, col_index=1, channel_index=2,
fill_mode='nearest', cval=0.):
"""Rotate an image randomly or non-randomly.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
rg : int or float
Degree to rotate, usually 0 ~ 180.
is_random : boolean, default False
If True, randomly rotate.
row_index, col_index, channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : string
Method to fill missing pixel, default ‘nearest’, more options ‘constant’, ‘reflect’ or ‘wrap’
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
cval : scalar, optional
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
Examples
---------
>>> x --> [row, col, 1] greyscale
>>> x = rotation(x, rg=40, is_random=False)
>>> tl.visualize.frame(x[:,:,0], second=0.01, saveable=True, name='temp',cmap='gray')
"""
if is_random:
theta = np.pi / 180 * np.random.uniform(-rg, rg)
else:
theta = np.pi /180 * rg
rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
h, w = x.shape[row_index], x.shape[col_index]
transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)
x = apply_transform(x, transform_matrix, channel_index, fill_mode, cval)
return x
示例5: shift
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def shift(x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2,
fill_mode='nearest', cval=0.):
"""Shift an image randomly or non-randomly.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
wrg : float
Percentage of shift in axis x, usually -0.25 ~ 0.25.
hrg : float
Percentage of shift in axis y, usually -0.25 ~ 0.25.
is_random : boolean, default False
If True, randomly shift.
row_index, col_index, channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : string
Method to fill missing pixel, default ‘nearest’, more options ‘constant’, ‘reflect’ or ‘wrap’.
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
cval : scalar, optional
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
"""
h, w = x.shape[row_index], x.shape[col_index]
if is_random:
tx = np.random.uniform(-hrg, hrg) * h
ty = np.random.uniform(-wrg, wrg) * w
else:
tx, ty = hrg * h, wrg * w
translation_matrix = np.array([[1, 0, tx],
[0, 1, ty],
[0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
x = apply_transform(x, transform_matrix, channel_index, fill_mode, cval)
return x
示例6: shear
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def shear(x, intensity=0.1, is_random=False, row_index=0, col_index=1, channel_index=2,
fill_mode='nearest', cval=0.):
"""Shear an image randomly or non-randomly.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
intensity : float
Percentage of shear, usually -0.5 ~ 0.5 (is_random==True), 0 ~ 0.5 (is_random==False),
you can have a quick try by shear(X, 1).
is_random : boolean, default False
If True, randomly shear.
row_index, col_index, channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : string
Method to fill missing pixel, default ‘nearest’, more options ‘constant’, ‘reflect’ or ‘wrap’.
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
cval : scalar, optional
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
"""
if is_random:
shear = np.random.uniform(-intensity, intensity)
else:
shear = intensity
shear_matrix = np.array([[1, -np.sin(shear), 0],
[0, np.cos(shear), 0],
[0, 0, 1]])
h, w = x.shape[row_index], x.shape[col_index]
transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)
x = apply_transform(x, transform_matrix, channel_index, fill_mode, cval)
return x
示例7: imresize
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def imresize(x, size=[100, 100], interp='bilinear', mode=None):
"""Resize an image by given output size and method. Warning, this function
will rescale the value to [0, 255].
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
size : int, float or tuple (h, w)
- int, Percentage of current size.
- float, Fraction of current size.
- tuple, Size of the output image.
interp : str, optional
Interpolation to use for re-sizing (‘nearest’, ‘lanczos’, ‘bilinear’, ‘bicubic’ or ‘cubic’).
mode : str, optional
The PIL image mode (‘P’, ‘L’, etc.) to convert arr before resizing.
Returns
--------
imresize : ndarray
The resized array of image.
References
------------
- `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`_
"""
if x.shape[-1] == 1:
# greyscale
x = scipy.misc.imresize(x[:,:,0], size, interp=interp, mode=mode)
return x[:, :, np.newaxis]
elif x.shape[-1] == 3:
# rgb, bgr ..
return scipy.misc.imresize(x, size, interp=interp, mode=mode)
else:
raise Exception("Unsupported channel %d" % x.shape[-1])
# normailization
示例8: channel_shift
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def channel_shift(x, intensity, is_random=False, channel_index=2):
"""Shift the channels of an image, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`_.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
intensity : float
Intensity of shifting.
is_random : boolean, default False
If True, randomly shift.
channel_index : int
Index of channel, default 2.
"""
if is_random:
factor = np.random.uniform(-intensity, intensity)
else:
factor = intensity
x = np.rollaxis(x, channel_index, 0)
min_x, max_x = np.min(x), np.max(x)
channel_images = [np.clip(x_channel + factor, min_x, max_x)
for x_channel in x]
x = np.stack(channel_images, axis=0)
x = np.rollaxis(x, 0, channel_index+1)
return x
# x = np.rollaxis(x, channel_index, 0)
# min_x, max_x = np.min(x), np.max(x)
# channel_images = [np.clip(x_channel + np.random.uniform(-intensity, intensity), min_x, max_x)
# for x_channel in x]
# x = np.stack(channel_images, axis=0)
# x = np.rollaxis(x, 0, channel_index+1)
# return x
示例9: channel_shift_multi
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def channel_shift_multi(x, intensity, channel_index=2):
"""Shift the channels of images with the same arguments, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`_ .
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy array
List of images with dimension of [n_images, row, col, channel] (default).
others : see ``channel_shift``.
"""
if is_random:
factor = np.random.uniform(-intensity, intensity)
else:
factor = intensity
results = []
for data in x:
data = np.rollaxis(data, channel_index, 0)
min_x, max_x = np.min(data), np.max(data)
channel_images = [np.clip(x_channel + factor, min_x, max_x)
for x_channel in x]
data = np.stack(channel_images, axis=0)
data = np.rollaxis(x, 0, channel_index+1)
results.append( data )
return np.asarray(results)
# noise
示例10: apply_transform
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def apply_transform(x, transform_matrix, channel_index=2, fill_mode='nearest', cval=0.):
"""Return transformed images by given transform_matrix from ``transform_matrix_offset_center``.
Parameters
----------
x : numpy array
Batch of images with dimension of 3, [batch_size, row, col, channel].
transform_matrix : numpy array
Transform matrix (offset center), can be generated by ``transform_matrix_offset_center``
channel_index : int
Index of channel, default 2.
fill_mode : string
Method to fill missing pixel, default ‘nearest’, more options ‘constant’, ‘reflect’ or ‘wrap’
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
cval : scalar, optional
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`_
Examples
--------
- See ``rotation``, ``shift``, ``shear``, ``zoom``.
"""
x = np.rollaxis(x, channel_index, 0)
final_affine_matrix = transform_matrix[:2, :2]
final_offset = transform_matrix[:2, 2]
channel_images = [ndi.interpolation.affine_transform(x_channel, final_affine_matrix,
final_offset, order=0, mode=fill_mode, cval=cval) for x_channel in x]
x = np.stack(channel_images, axis=0)
x = np.rollaxis(x, 0, channel_index+1)
return x
示例11: array_to_img
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def array_to_img(x, dim_ordering=(0,1,2), scale=True):
"""Converts a numpy array to PIL image object (uint8 format).
Parameters
----------
x : numpy array
A image with dimension of 3 and channels of 1 or 3.
dim_ordering : list or tuple of 3 int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
scale : boolean, default is True
If True, converts image to [0, 255] from any range of value like [-1, 2].
References
-----------
- `PIL Image.fromarray <http://pillow.readthedocs.io/en/3.1.x/reference/Image.html?highlight=fromarray>`_
"""
from PIL import Image
# if dim_ordering == 'default':
# dim_ordering = K.image_dim_ordering()
# if dim_ordering == 'th': # theano
# x = x.transpose(1, 2, 0)
x = x.transpose(dim_ordering)
if scale:
x += max(-np.min(x), 0)
x_max = np.max(x)
if x_max != 0:
# print(x_max)
# x /= x_max
x = x / x_max
x *= 255
if x.shape[2] == 3:
# RGB
return Image.fromarray(x.astype('uint8'), 'RGB')
elif x.shape[2] == 1:
# grayscale
return Image.fromarray(x[:, :, 0].astype('uint8'), 'L')
else:
raise Exception('Unsupported channel number: ', x.shape[2])
示例12: find_contours
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def find_contours(x, level=0.8, fully_connected='low', positive_orientation='low'):
""" Find iso-valued contours in a 2D array for a given level value, returns list of (n, 2)-ndarrays
see `skimage.measure.find_contours <http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours>`_ .
Parameters
------------
x : 2D ndarray of double. Input data in which to find contours.
level : float. Value along which to find contours in the array.
fully_connected : str, {‘low’, ‘high’}. Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.)
positive_orientation : either ‘low’ or ‘high’. Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If ‘low’ then contours will wind counter-clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour.
"""
return skimage.measure.find_contours(x, level, fully_connected='low', positive_orientation='low')
示例13: binary_dilation
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def binary_dilation(x, radius=3):
""" Return fast binary morphological dilation of an image.
see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`_.
Parameters
-----------
x : 2D array image.
radius : int for the radius of mask.
"""
from skimage.morphology import disk, binary_dilation
mask = disk(radius)
x = binary_dilation(image, selem=mask)
return x
示例14: pil_to_array
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def pil_to_array(pilImage):
"""Load a `PIL image`_ and return it as a numpy array.
.. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
Returns
-------
numpy.array
The array shape depends on the image type:
- (M, N) for grayscale images.
- (M, N, 3) for RGB images.
- (M, N, 4) for RGBA images.
"""
if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
# return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
return np.asarray(pilImage)
elif pilImage.mode.startswith('I;16'):
# return MxN luminance array of uint16
raw = pilImage.tobytes('raw', pilImage.mode)
if pilImage.mode.endswith('B'):
x = np.fromstring(raw, '>u2')
else:
x = np.fromstring(raw, '<u2')
return x.reshape(pilImage.size[::-1]).astype('=u2')
else: # try to convert to an rgba image
try:
pilImage = pilImage.convert('RGBA')
except ValueError:
raise RuntimeError('Unknown image mode')
return np.asarray(pilImage) # return MxNx4 RGBA array
示例15: mode
# 需要導入模塊: from PIL import Image [as 別名]
# 或者: from PIL.Image import html [as 別名]
def mode(self) -> str:
"""
Return the image mode string such as 'RGBA', 'RGB', 'L', etc, or None according to PIL.
See http://pillow.readthedocs.org/en/3.0.x/handbook/concepts.html#modes
:return: A string indicating the image mode
"""