Python PIL.Image.html() Examples
The following are 30
code examples of PIL.Image.html().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
PIL.Image
, or try the search function
.
Example #1
Source File: prepro.py From deepsleepnet with Apache License 2.0 | 6 votes |
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
Example #2
Source File: prepro.py From super-resolution-videos with The Unlicense | 6 votes |
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
Example #3
Source File: prepro.py From LapSRN-tensorflow with Apache License 2.0 | 6 votes |
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
Example #4
Source File: prepro.py From super-resolution-videos with The Unlicense | 6 votes |
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
Example #5
Source File: prepro.py From LapSRN-tensorflow with Apache License 2.0 | 6 votes |
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
Example #6
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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
Example #7
Source File: prepro.py From deepsleepnet with Apache License 2.0 | 5 votes |
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
Example #8
Source File: prepro.py From deepsleepnet with Apache License 2.0 | 5 votes |
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
Example #9
Source File: prepro.py From deepsleepnet with Apache License 2.0 | 5 votes |
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
Example #10
Source File: prepro.py From deepsleepnet with Apache License 2.0 | 5 votes |
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
Example #11
Source File: prepro.py From deepsleepnet with Apache License 2.0 | 5 votes |
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]) ## Sequence
Example #12
Source File: thumbnail.py From BotHub with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return await event.edit("Processing ...") if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: downloaded_file_name = await borg.download_media( await event.get_reply_message(), Config.TMP_DOWNLOAD_DIRECTORY ) if downloaded_file_name.endswith(".mp4"): downloaded_file_name = get_video_thumb( downloaded_file_name ) metadata = extractMetadata(createParser(downloaded_file_name)) height = 0 if metadata.has("height"): height = metadata.get("height") # resize image # ref: https://t.me/PyrogramChat/44663 # https://stackoverflow.com/a/21669827/4723940 Image.open(downloaded_file_name).convert("RGB").save(downloaded_file_name) img = Image.open(downloaded_file_name) # https://stackoverflow.com/a/37631799/4723940 # img.thumbnail((320, 320)) img.resize((320, height)) img.save(thumb_image_path, "JPEG") # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails os.remove(downloaded_file_name) await event.edit( "Custom video / file thumbnail saved. " + \ "This image will be used in the upload, till `.clearthumbnail`." ) else: await event.edit("Reply to a photo to save custom thumbnail")
Example #13
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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
Example #14
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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
Example #15
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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
Example #16
Source File: prepro.py From LapSRN-tensorflow with Apache License 2.0 | 5 votes |
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
Example #17
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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
Example #18
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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
Example #19
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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
Example #20
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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])
Example #21
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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')
Example #22
Source File: prepro.py From super-resolution-videos with The Unlicense | 5 votes |
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
Example #23
Source File: input_data_gen.py From DeepMoon with MIT License | 5 votes |
def ringmaker(r=10., dr=1): """ Creates ring of radius r and thickness dr. Parameters ---------- r : float Ring radius dr : int Ring thickness (cv2.circle requires int) """ # See <http://docs.opencv.org/2.4/modules/core/doc/ # drawing_functions.html#circle>, supplemented by # <http://docs.opencv.org/3.1.0/dc/da5/tutorial_py_drawing_functions.html> # and <https://github.com/opencv/opencv/blob/ # 05b15943d6a42c99e5f921b7dbaa8323f3c042c6/modules/imgproc/ # src/drawing.cpp>. # mask grid extent (dr/2 +1 to ensure we capture ring width # and radius); same philosophy as above rhext = int(np.ceil(r + dr / 2.)) + 1 # cv2.circle requires integer radius mask = np.zeros([2 * rhext + 1, 2 * rhext + 1], np.uint8) # Generate ring ring = cv2.circle(mask, (rhext, rhext), int(np.round(r)), 1, thickness=dr) return ring.astype(float)
Example #24
Source File: image.py From coffeegrindsize with MIT License | 5 votes |
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
Example #25
Source File: image.py From CogAlg with MIT License | 5 votes |
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
Example #26
Source File: image.py From cate with MIT License | 5 votes |
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 """ pass
Example #27
Source File: tiledimage.py From xcube with MIT License | 5 votes |
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 """
Example #28
Source File: prepro.py From LapSRN-tensorflow with Apache License 2.0 | 5 votes |
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
Example #29
Source File: prepro.py From LapSRN-tensorflow with Apache License 2.0 | 5 votes |
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
Example #30
Source File: prepro.py From LapSRN-tensorflow with Apache License 2.0 | 5 votes |
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