Python accimage.Image() Examples
The following are 30
code examples of accimage.Image().
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
accimage
, or try the search function
.
Example #1
Source File: nyu_transform.py From Visualizing-CNNs-for-monocular-depth-estimation with MIT License | 6 votes |
def changeScale(self, img, size, interpolation=Image.BILINEAR): if not _is_pil_image(img): raise TypeError( 'img should be PIL Image. Got {}'.format(type(img))) if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)): raise TypeError('Got inappropriate size arg: {}'.format(size)) if isinstance(size, int): w, h = img.size if (w <= h and w == size) or (h <= w and h == size): return img if w < h: ow = size oh = int(size * h / w) return img.resize((ow, oh), interpolation) else: oh = size ow = int(size * w / h) return img.resize((ow, oh), interpolation) else: return img.resize(size[::-1], interpolation)
Example #2
Source File: functional.py From opencv_transforms with MIT License | 6 votes |
def to_grayscale(img, num_output_channels=1): """Convert image to grayscale version of image. Args: img (numpy ndarray): Image to be converted to grayscale. Returns: numpy ndarray: Grayscale version of the image. if num_output_channels = 1 : returned image is single channel if num_output_channels = 3 : returned image is 3 channel with r = g = b """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if num_output_channels==1: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:,:,np.newaxis] elif num_output_channels==3: # much faster than doing cvtColor to go back to gray img = np.broadcast_to(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:,:,np.newaxis], img.shape) return img
Example #3
Source File: functional.py From opencv_transforms with MIT License | 6 votes |
def adjust_saturation(img, saturation_factor): """Adjust color saturation of an image. Args: img (numpy ndarray): numpy ndarray to be adjusted. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. Returns: numpy ndarray: Saturation adjusted image. """ # ~10ms slower than PIL! if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) img = Image.fromarray(img) enhancer = ImageEnhance.Color(img) img = enhancer.enhance(saturation_factor) return np.array(img)
Example #4
Source File: transforms.py From ACAN with MIT License | 6 votes |
def adjust_brightness(img, brightness_factor): """Adjust brightness of an Image. Args: img (PIL Image): PIL Image to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: PIL Image: Brightness adjusted image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) enhancer = ImageEnhance.Brightness(img) img = enhancer.enhance(brightness_factor) return img
Example #5
Source File: make_imagenet_c.py From robustness with Apache License 2.0 | 6 votes |
def __getitem__(self, index): path, target = self.imgs[index] img = self.loader(path) if self.transform is not None: img = self.transform(img) img = self.method(img, self.severity) if self.target_transform is not None: target = self.target_transform(target) save_path = '/share/data/vision-greg/DistortedImageNet/JPEG/' + self.method.__name__ + \ '/' + str(self.severity) + '/' + self.idx_to_class[target] if not os.path.exists(save_path): os.makedirs(save_path) save_path += path[path.rindex('/'):] Image.fromarray(np.uint8(img)).save(save_path, quality=85, optimize=True) return 0 # we do not care about returning the data
Example #6
Source File: transforms.py From ACAN with MIT License | 6 votes |
def adjust_contrast(img, contrast_factor): """Adjust contrast of an Image. Args: img (PIL Image): PIL Image to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2. Returns: PIL Image: Contrast adjusted image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(contrast_factor) return img
Example #7
Source File: transforms.py From ACAN with MIT License | 6 votes |
def adjust_saturation(img, saturation_factor): """Adjust color saturation of an image. Args: img (PIL Image): PIL Image to be adjusted. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. Returns: PIL Image: Saturation adjusted image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) enhancer = ImageEnhance.Color(img) img = enhancer.enhance(saturation_factor) return img
Example #8
Source File: opencv_functional.py From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License | 6 votes |
def to_grayscale(img, num_output_channels=1): """Convert image to grayscale version of image. Args: img (numpy ndarray): Image to be converted to grayscale. Returns: numpy ndarray: Grayscale version of the image. if num_output_channels = 1 : returned image is single channel if num_output_channels = 3 : returned image is 3 channel with r = g = b """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if num_output_channels==1: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:,:,np.newaxis] elif num_output_channels==3: # much faster than doing cvtColor to go back to gray img = np.broadcast_to(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:,:,np.newaxis], img.shape) return img
Example #9
Source File: transforms.py From ACAN with MIT License | 6 votes |
def __call__(self, img): """Convert a ``numpy.ndarray`` to tensor. Args: img (numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(_is_numpy_image(img)): raise TypeError('img should be ndarray. Got {}'.format(type(img))) if isinstance(img, np.ndarray): # handle numpy array if img.ndim == 3: img = torch.from_numpy(img.transpose((2, 0, 1)).copy()) elif img.ndim == 2: img = torch.from_numpy(img.copy()) else: raise RuntimeError('img should be ndarray with 2 or 3 dimensions. Got {}'.format(img.ndim)) # backward compatibility #return img.float().div(255) return img.float()
Example #10
Source File: functional.py From opencv_transforms with MIT License | 6 votes |
def adjust_contrast(img, contrast_factor): """Adjust contrast of an mage. Args: img (numpy ndarray): numpy ndarray to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2. Returns: numpy ndarray: Contrast adjusted image. """ # much faster to use the LUT construction than anything else I've tried # it's because you have to change dtypes multiple times if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) table = np.array([ (i-74)*contrast_factor+74 for i in range (0,256)]).clip(0,255).astype('uint8') # enhancer = ImageEnhance.Contrast(img) # img = enhancer.enhance(contrast_factor) if img.shape[2]==1: return cv2.LUT(img, table)[:,:,np.newaxis] else: return cv2.LUT(img,table)
Example #11
Source File: transforms.py From ACAN with MIT License | 6 votes |
def get_params(img, output_size): """Get parameters for ``crop`` for center crop. Args: img (numpy.ndarray (C x H x W)): Image to be cropped. output_size (tuple): Expected output size of the crop. Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for center crop. """ h = img.shape[0] w = img.shape[1] th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) # # randomized cropping # i = np.random.randint(i-3, i+4) # j = np.random.randint(j-3, j+4) return i, j, th, tw
Example #12
Source File: functional.py From opencv_transforms with MIT License | 6 votes |
def adjust_brightness(img, brightness_factor): """Adjust brightness of an Image. Args: img (numpy ndarray): numpy ndarray to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: numpy ndarray: Brightness adjusted image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) table = np.array([ i*brightness_factor for i in range (0,256)]).clip(0,255).astype('uint8') # same thing but a bit slower # cv2.convertScaleAbs(img, alpha=brightness_factor, beta=0) if img.shape[2]==1: return cv2.LUT(img, table)[:,:,np.newaxis] else: return cv2.LUT(img, table)
Example #13
Source File: opencv_functional.py From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License | 6 votes |
def adjust_saturation(img, saturation_factor): """Adjust color saturation of an image. Args: img (numpy ndarray): numpy ndarray to be adjusted. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. Returns: numpy ndarray: Saturation adjusted image. """ # ~10ms slower than PIL! if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) img = Image.fromarray(img) enhancer = ImageEnhance.Color(img) img = enhancer.enhance(saturation_factor) return np.array(img)
Example #14
Source File: opencv_functional.py From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License | 6 votes |
def adjust_contrast(img, contrast_factor): """Adjust contrast of an mage. Args: img (numpy ndarray): numpy ndarray to be adjusted. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2. Returns: numpy ndarray: Contrast adjusted image. """ # much faster to use the LUT construction than anything else I've tried # it's because you have to change dtypes multiple times if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) table = np.array([ (i-74)*contrast_factor+74 for i in range (0,256)]).clip(0,255).astype('uint8') # enhancer = ImageEnhance.Contrast(img) # img = enhancer.enhance(contrast_factor) if img.shape[2] == 1: return cv2.LUT(img, table)[:,:,np.newaxis] else: return cv2.LUT(img, table)
Example #15
Source File: transforms.py From ACAN with MIT License | 6 votes |
def __call__(self, img): """ Args: img (numpy.ndarray (C x H x W)): Image to be cropped. Returns: img (numpy.ndarray (C x H x W)): Cropped image. """ i, j, h, w = self.i, self.j, self.h, self.w if not(_is_numpy_image(img)): raise TypeError('img should be ndarray. Got {}'.format(type(img))) if img.ndim == 3: return img[i:i + h, j:j + w, :] elif img.ndim == 2: return img[i:i + h, j:j + w] else: raise RuntimeError( 'img should be ndarray with 2 or 3 dimensions. Got {}'.format(img.ndim))
Example #16
Source File: nyu_transform.py From Visualizing-CNNs-for-monocular-depth-estimation with MIT License | 6 votes |
def __call__(self, sample): image, depth = sample['image'], sample['depth'] applied_angle = random.uniform(-self.angle, self.angle) angle1 = applied_angle angle1_rad = angle1 * np.pi / 180 # print('before rotating:',image.size) image = ndimage.interpolation.rotate( image, angle1, reshape=self.reshape, order=self.order) depth = ndimage.interpolation.rotate( depth, angle1, reshape=self.reshape, order=self.order) image = Image.fromarray(image) depth = Image.fromarray(depth) # print('after rotating:',image.shape,depth.shape) return {'image': image, 'depth': depth}
Example #17
Source File: functional.py From opencv_transforms with MIT License | 6 votes |
def to_tensor(pic): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(_is_numpy_image(pic)): raise TypeError('pic should be ndarray. Got {}'.format(type(pic))) # handle numpy array img = torch.from_numpy(pic.transpose((2, 0, 1))) # backward compatibility if isinstance(img, torch.ByteTensor) or img.dtype==torch.uint8: return img.float().div(255) else: return img
Example #18
Source File: spatial_transforms.py From PyTorchConv3D with Apache License 2.0 | 6 votes |
def __call__(self, img): """ Args: img (PIL.Image): Image to be scaled. Returns: PIL.Image: Rescaled image. """ if isinstance(self.size, int): w, h = img.size if (w <= h and w == self.size) or (h <= w and h == self.size): return img if w < h: ow = self.size oh = int(self.size * h / w) return img.resize((ow, oh), self.interpolation) else: oh = self.size ow = int(self.size * w / h) return img.resize((ow, oh), self.interpolation) else: return img.resize(self.size, self.interpolation)
Example #19
Source File: opencv_functional.py From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License | 6 votes |
def to_tensor(pic): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(_is_numpy_image(pic)): raise TypeError('pic should be ndarray. Got {}'.format(type(pic))) # handle numpy array img = torch.from_numpy(pic.transpose((2, 0, 1))) # backward compatibility if isinstance(img, torch.ByteTensor) or img.dtype==torch.uint8: return img.float() else: return img
Example #20
Source File: transforms.py From DeepLung with GNU General Public License v3.0 | 6 votes |
def __call__(self, img): """ Args: img (PIL.Image): Image to be scaled. Returns: PIL.Image: Rescaled image. """ if isinstance(self.size, int): w, h, d = img.size if (w <= h and w == self.size) or (h <= w and h == self.size): return img if w < h: ow = self.size oh = int(self.size * h / w) return img.resize((ow, oh), self.interpolation) else: oh = self.size ow = int(self.size * w / h) return img.resize((ow, oh), self.interpolation) else: return img.resize(self.size, self.interpolation)
Example #21
Source File: functional.py From opencv_transforms with MIT License | 6 votes |
def resized_crop(img, i, j, h, w, size, interpolation=cv2.INTER_LINEAR): """Crop the given numpy ndarray and resize it to desired size. Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. Args: img (numpy ndarray): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. size (sequence or int): Desired output size. Same semantics as ``scale``. interpolation (int, optional): Desired interpolation. Default is ``cv2.INTER_CUBIC``. Returns: PIL Image: Cropped image. """ assert _is_numpy_image(img), 'img should be numpy image' img = crop(img, i, j, h, w) img = resize(img, size, interpolation=interpolation) return img
Example #22
Source File: opencv_functional.py From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License | 6 votes |
def resized_crop(img, i, j, h, w, size, interpolation=cv2.INTER_LINEAR): """Crop the given numpy ndarray and resize it to desired size. Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. Args: img (numpy ndarray): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. size (sequence or int): Desired output size. Same semantics as ``scale``. interpolation (int, optional): Desired interpolation. Default is ``cv2.INTER_LINEAR``. Returns: PIL Image: Cropped image. """ assert _is_numpy_image(img), 'img should be numpy image' img = crop(img, i, j, h, w) img = resize(img, size, interpolation=interpolation) return img
Example #23
Source File: transforms.py From ACAN with MIT License | 6 votes |
def __call__(self, img): """ Args: img (numpy.ndarray (H x W x C)): Image to be cropped. Returns: img (numpy.ndarray (H x W x C)): Cropped image. """ i, j, h, w = self.get_params(img, self.size, self.slide) """ i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. """ if not(_is_numpy_image(img)): raise TypeError('img should be ndarray. Got {}'.format(type(img))) if img.ndim == 3: return img[i:i+h, j:j+w, :] elif img.ndim == 2: return img[i:i + h, j:j + w] else: raise RuntimeError('img should be ndarray with 2 or 3 dimensions. Got {}'.format(img.ndim))
Example #24
Source File: transforms.py From ACAN with MIT License | 6 votes |
def get_params(img, output_size, slide): """Get parameters for ``crop`` for random crop. Args: img (numpy.ndarray (H x W x C)): Image to be cropped. output_size (tuple): Expected output size of the crop. Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for random crop. """ h = img.shape[0] w = img.shape[1] th, tw = output_size i = round((h - th - 1) * slide[0]) j = round((w - tw - 1) * slide[1]) # i = np.random.randint(0, h - th) # j = np.random.randint(0, w - tw) return i, j, th, tw
Example #25
Source File: opencv_functional.py From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License | 6 votes |
def adjust_brightness(img, brightness_factor): """Adjust brightness of an Image. Args: img (numpy ndarray): numpy ndarray to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: numpy ndarray: Brightness adjusted image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) table = np.array([ i*brightness_factor for i in range (0,256)]).clip(0,255).astype('uint8') # same thing but a bit slower # cv2.convertScaleAbs(img, alpha=brightness_factor, beta=0) if img.shape[2] == 1: return cv2.LUT(img, table)[:,:,np.newaxis] else: return cv2.LUT(img, table)
Example #26
Source File: functional.py From opencv_transforms with MIT License | 5 votes |
def crop(img, i, j, h, w): """Crop the given PIL Image. Args: img (numpy ndarray): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. Returns: numpy ndarray: Cropped image. """ if not _is_numpy_image(img): raise TypeError('img should be numpy image. Got {}'.format(type(img))) return img[i:i+h, j:j+w, :]
Example #27
Source File: spatial_transforms.py From PyTorchConv3D with Apache License 2.0 | 5 votes |
def __init__(self, scales, size, interpolation=Image.BILINEAR): self.scales = scales self.size = size self.interpolation = interpolation
Example #28
Source File: spatial_transforms.py From PyTorchConv3D with Apache License 2.0 | 5 votes |
def __init__(self, scales, size, interpolation=Image.BILINEAR, crop_positions=['c', 'tl', 'tr', 'bl', 'br']): self.scales = scales self.size = size self.interpolation = interpolation self.crop_positions = crop_positions
Example #29
Source File: spatial_transforms.py From PyTorchConv3D with Apache License 2.0 | 5 votes |
def __init__(self, size, interpolation=Image.BILINEAR): assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2) self.size = size self.interpolation = interpolation
Example #30
Source File: functional.py From opencv_transforms with MIT License | 5 votes |
def affine(img, angle, translate, scale, shear, interpolation=cv2.INTER_LINEAR, mode=cv2.BORDER_CONSTANT, fillcolor=0): """Apply affine transformation on the image keeping image center invariant Args: img (numpy ndarray): numpy ndarray to be transformed. angle (float or int): rotation angle in degrees between -180 and 180, clockwise direction. translate (list or tuple of integers): horizontal and vertical translations (post-rotation translation) scale (float): overall scale shear (float): shear angle value in degrees between -180 to 180, clockwise direction. interpolation (``cv2.INTER_NEAREST` or ``cv2.INTER_LINEAR`` or ``cv2.INTER_AREA``, ``cv2.INTER_CUBIC``): An optional resampling filter. See `filters`_ for more information. If omitted, it is set to ``cv2.INTER_CUBIC``, for bicubic interpolation. mode (``cv2.BORDER_CONSTANT`` or ``cv2.BORDER_REPLICATE`` or ``cv2.BORDER_REFLECT`` or ``cv2.BORDER_REFLECT_101``) Method for filling in border regions. Defaults to cv2.BORDER_CONSTANT, meaning areas outside the image are filled with a value (val, default 0) val (int): Optional fill color for the area outside the transform in the output image. Default: 0 """ if not _is_numpy_image(img): raise TypeError('img should be numpy Image. Got {}'.format(type(img))) assert isinstance(translate, (tuple, list)) and len(translate) == 2, \ "Argument translate should be a list or tuple of length 2" assert scale > 0.0, "Argument scale should be positive" output_size = img.shape[0:2] center = (img.shape[1] * 0.5 + 0.5, img.shape[0] * 0.5 + 0.5) matrix = _get_affine_matrix(center, angle, translate, scale, shear) if img.shape[2]==1: return cv2.warpAffine(img, matrix, output_size[::-1],interpolation, borderMode=mode, borderValue=fillcolor)[:,:,np.newaxis] else: return cv2.warpAffine(img, matrix, output_size[::-1],interpolation, borderMode=mode, borderValue=fillcolor)