Python PIL.Image 模块,FLIP_LEFT_RIGHT 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.Image.FLIP_LEFT_RIGHT。
def font_variant(self, font=None, size=None, index=None, encoding=None):
"""
Create a copy of this FreeTypeFont object,
using any specified arguments to override the settings.
Parameters are identical to the parameters used to initialize this
object.
:return: A FreeTypeFont object.
"""
return FreeTypeFont(font=self.path if font is None else font,
size=self.size if size is None else size,
index=self.index if index is None else index,
encoding=self.encoding if encoding is None else
encoding)
##
# Wrapper that creates a transposed font from any existing font
# object.
#
# @param font A font object.
# @param orientation An optional orientation. If given,this should
# be one of Image.FLIP_LEFT_RIGHT,Image.FLIP_TOP_BottOM,
# Image.ROTATE_90,Image.ROTATE_180,or Image.ROTATE_270.
def transformImg(self, img, t):
imgT = img.transform((int(img.size[0]*t[3]),int(img.size[1]*t[3])), Image.EXTENT, (0,0,img.size[0],img.size[1]), Image.BILINEAR)
imgT = imgT.rotate(numpy.rad2deg(t[0]), Image.BILINEAR, expand=1)
if t[4] == 1.:
imgT = imgT.transpose(Image.FLIP_LEFT_RIGHT)
# crop only valid part
if self.crop:
imgT = imgT.crop(self.getInscribedRectangle(t[0], (img.size[0]*t[3], img.size[1]*t[3])))
# crop from translation
imgT = imgT.resize((int(self.imgSize[0]*1.1), int(self.imgSize[1]*1.1)), Image.BILINEAR)
xstart = int((imgT.size[0] // 2 - t[1]) - self.imgSize[0] // 2)
ystart = int((imgT.size[1] // 2 - t[2]) - self.imgSize[1] // 2)
assert xstart >= 0 and ystart >= 0
return imgT.crop((xstart, ystart, xstart+self.imgSize[0], ystart+self.imgSize[1]))
def flip_and_save(self, image_path):
"""
flip the image by the path and save the flipped image with suffix 'flip'
:param path: the path of specific image
:return: the path of saved image
"""
[image_name, image_ext] = os.path.splitext(os.path.basename(image_path))
image_dir = os.path.dirname(image_path)
saved_image_path = os.path.join(image_dir, image_name + '_flip' + image_ext)
try:
flipped_image = Image.open(saved_image_path)
except:
flipped_image = Image.open(image_path)
flipped_image = flipped_image.transpose(Image.FLIP_LEFT_RIGHT)
flipped_image.save(saved_image_path, 'png')
return saved_image_path
def __call__(self, img_group):
if self.scale_worker is not None:
img_group = self.scale_worker(img_group)
image_w, image_h = img_group[0].size
crop_w, crop_h = self.crop_size
offsets = GroupMultiScaleCrop.fill_fix_offset(False, image_w, image_h, crop_w, crop_h)
oversample_group = list()
for o_w, o_h in offsets:
normal_group = list()
flip_group = list()
for i, img in enumerate(img_group):
crop = img.crop((o_w, o_h, o_w + crop_w, o_h + crop_h))
normal_group.append(crop)
flip_crop = crop.copy().transpose(Image.FLIP_LEFT_RIGHT)
if img.mode == 'L' and i % 2 == 0:
flip_group.append(ImageOps.invert(flip_crop))
else:
flip_group.append(flip_crop)
oversample_group.extend(normal_group)
oversample_group.extend(flip_group)
return oversample_group
def flip_and_save(self, 'png')
return saved_image_path
def flip_and_save(self, 'png')
return saved_image_path
def load_input_image(self, path, flip=False, zoom_factor=1, left_lower_corner=(0, 0), jitter=None):
"""Load a single input image"""
image = load_image(image_path=path, image_scaling_factor=self.image_scaling_factor,
resampling_method=self.input_interpolation)
if flip:
image = image.transpose(Image.FLIP_LEFT_RIGHT)
if zoom_factor != 1:
image = zoom_into_image(image=image, zoom_factor=zoom_factor, left_lower_corner=left_lower_corner,
resample=self.input_interpolation)
if jitter:
image = add_color_jittering(image, jitter)
if self.add_luminance:
image = add_luminance(image)
if self.stretch_values:
image = stretch_values(image)
return np.asarray(image, dtype=np.float32)
def load_label_image(self, 0)):
"""Load a single label image"""
image = load_image(image_path=path,
resampling_method=self.label_interpolation)
if flip:
image = image.transpose(Image.FLIP_LEFT_RIGHT)
if zoom_factor != 1:
image = zoom_into_image(image=image,
resample=self.label_interpolation)
label = np.asarray(image, dtype=np.uint8)
if self.id2label is not None:
temp = np.array(image)
for k, v in self.id2label.items():
temp[label == k] = v
label = temp
return label
def _showloop(self):
while cv2.waitKey(10) not in [keycode.ESCAPE, keycode.Q, keycode.q]:
image = self.capture.read()
image = image.transpose(Image.FLIP_LEFT_RIGHT)
image = _resize_image(image, self.size)
array = np.asarray(image)
array = _mount_roi(array, self.roi, color = (74, 20, 140), thickness = 2)
crop = _crop_array(array, self.roi)
# process image for any gestures
if self.verbose:
segments, event = spockpy.detect(crop, verbose = self.verbose)
else:
event = spockpy.detect(crop, verbose = self.verbose)
self.image = Image.fromarray(segments)
self.event = event
cv2.imshow(HoverPad.TITLE, array)
cv2.destroyWindow(HoverPad.TITLE)
def image_transpose_exif(im):
exif_orientation_tag = 0x0112 # contains an integer,1 through 8
exif_transpose_sequences = [ # corresponding to the following
[],
[Image.FLIP_LEFT_RIGHT],
[Image.ROTATE_180],
[Image.FLIP_TOP_BottOM],
[Image.FLIP_LEFT_RIGHT, Image.ROTATE_90],
[Image.ROTATE_270],
[Image.FLIP_TOP_BottOM,
[Image.ROTATE_90],
]
try:
if im._getexif() is not None:
seq = exif_transpose_sequences[im._getexif()[exif_orientation_tag] - 1]
return functools.reduce(lambda im, op: im.transpose(op), seq, im)
else:
return im
except KeyError:
return im
def image_transpose_exif(im):
exif_orientation_tag = 0x0112 # contains an integer, im)
else:
return im
except KeyError:
return im
def random_flip(img, Boxes):
'''Randomly flip the given PIL Image.
Args:
img: (PIL Image) image to be flipped.
Boxes: (tensor) object Boxes,sized [#ojb,4].
Returns:
img: (PIL.Image) randomly flipped image.
Boxes: (tensor) randomly flipped Boxes.
'''
if random.random() < 0.5:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
w = img.width
xmin = w - Boxes[:,2]
xmax = w - Boxes[:,0]
Boxes[:,0] = xmin
Boxes[:,2] = xmax
return img, Boxes
def transform_image(src_root, dst_root, file_list, config):
img_Box, img_mode, img_flip = config
print "Transforming images from %s to %s." % (src_root, dst_root)
for file_path in file_list:
src_path = src_root + '/' + file_path
dst_path = dst_root + '/' + file_path
dst_dir = os.path.dirname(dst_path)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
img = Image.open(src_path)
if img_mode:
img = img.convert(img_mode)
if img_Box:
img = img.crop(img_Box)
if img_flip == True:
img = img.flip(Image.FLIP_LEFT_RIGHT)
img.save(dst_path)
return
def __getitem__(self, index):
if not self.train:
index += self.train_length
idx = self.idxes[index]
# Open file as Pillow Image
x_img = Image.open(self.x_dir[idx]).convert('RGB')
y_img = Image.open(self.y_dir[idx]).convert('RGB')
# Randomly flip
if random.random() < 0.5:
x_img = x_img.transpose(Image.FLIP_LEFT_RIGHT)
y_img = y_img.transpose(Image.FLIP_LEFT_RIGHT)
if self.transform:
x_img = self.transform(x_img)
y_img = self.transform(y_img)
x_img = normalize(x_img, -1, 1)
y_img = normalize(y_img, 1)
return x_img, y_img
def flip_and_save(self, 'png')
return saved_image_path
def load_images(self, idxs):
"""
Load input image and preprocess for Caffe:
- cast to float
- switch channels RGB -> BGR
- subtract mean
- transpose to channel x height x width order
"""
for i,idx in enumerate(idxs):
im = Image.open(self.img_dir+idx)
im = im.resize((256,256)) # resize to 256x256
# data augmentation by random crops
offset_x = random.randint(0,29)
offset_y = random.randint(0,29)
im = im.crop((offset_x,offset_y,227+offset_x,227+offset_y)) # crop of 227x227
if random.randint(0,1) == 1:
im = im.transpose(Image.FLIP_LEFT_RIGHT) # data augmentation by random mirror
if len(np.array(im).shape) < 3:
im = im.convert('RGB') # grayscale to RGB
in_ = np.array(im, dtype=np.float32)
in_ = in_[:,:,::-1] # switch channels RGB -> BGR
in_ -= self.mean # subtract mean
in_ = in_.transpose((2,1)) # transpose to channel x height x width order
self.data[i,:] = in_
def __getitem__(self, index):
'''
output data format:
img: Tensor,size = (3,224,224)
pose: Tensor,),[yaw,pitch,roll]
'''
if self.debug == 1:
s = self.sample_lst[0]
else:
s = self.sample_lst[index]
img = Image.open(os.path.join(self.img_root, s['image'])).convert('RGB')
pose = np.array(s['pose'])
if self.flip and np.random.rand() > 0.5:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
pose[0] = -pose[0] # yaw need to be reversed
img = self.transform(img)
return img, pose
def __call__(self, mask):
if random.random() < 0.5:
return img.transpose(Image.FLIP_LEFT_RIGHT), mask.transpose(Image.FLIP_LEFT_RIGHT)
return img, mask
def mirror(image):
"""
Flip image horizontally (left to right).
:param image: The image to mirror.
:return: An image.
"""
return image.transpose(Image.FLIP_LEFT_RIGHT)
def __getitem__(self, index):
Cpath, Spath = self.imgs[index][0], self.imgs[index][1]
Cimg, Simg = color_loader(Cpath), grey_loader(Spath)
Cimg, Simg = RandomCrop(511)(Cimg, Simg)
if random.random() < 0.5:
Cimg, Simg = Cimg.transpose(Image.FLIP_LEFT_RIGHT), Simg.transpose(Image.FLIP_LEFT_RIGHT)
if random.random() < 0.5:
Cimg, Simg = Cimg.transpose(Image.FLIP_TOP_BottOM), Simg.transpose(Image.FLIP_TOP_BottOM)
if random.random() < 0.5:
Cimg, Simg = Cimg.transpose(Image.ROTATE_90), Simg.transpose(Image.ROTATE_90)
Cimg, Vimg, Simg = self.transform(Cimg), self.vtransform(Cimg), self.stransform(Simg)
return Cimg, Simg
def __getitem__(self, Spath = self.imgs[index]
Cimg, sketch_loader(Spath)
Cimg, Simg.transpose(Image.FLIP_TOP_BottOM)
# if random.random() < 0.5:
# Vimg = Vimg.transpose(Image.ROTATE_90)
Cimg, Simg
def __getitem__(self, sketch_loader(Spath)
if random.random() < 0.5:
Cimg, Simg.transpose(Image.FLIP_LEFT_RIGHT)
Vimg = Cimg
if random.random() < 0.5:
Vimg = Vimg.transpose(Image.FLIP_LEFT_RIGHT)
# if random.random() < 0.5:
# Vimg = Vimg.transpose(Image.ROTATE_90)
Cimg, self.vtransform(Vimg), Simg
def __getitem__(self, Simg.transpose(Image.FLIP_LEFT_RIGHT)
Vimg = Cimg
# if random.random() < 0.5:
# Vimg = Vimg.transpose(Image.FLIP_LEFT_RIGHT)
# if random.random() < 0.5:
# Vimg = Vimg.transpose(Image.ROTATE_90)
Cimg, Simg
def __getitem__(self, self.imgs[index][random.randint(1, 3)]
Cimg, Simg
def __init__(self, *commands, prefixes=None, strict=False):
"""Answers with image containing stylish quote."""
super().__init__(*commands, prefixes=prefixes, strict=strict)
self.q = Image.open(self.get_path("q.png")).resize((40, 40), Image.lanczos)
self.qf = self.q.copy().transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.FLIP_TOP_BottOM)
self.f = ImageFont.truetype(self.get_path("font.ttf"), 20)
self.fs = ImageFont.truetype(self.get_path("font.ttf"), 14)
example = self.command_example()
self.description = [f"????????? ?????",
f"{example} [?????] - ????????? ????????? ? ??????? ????? (?? ???????) ? "
"???????? ??????!"]
def __init__(self, font, orientation=None):
"""
Wrapper that creates a transposed font from any existing font
object.
:param font: A font object.
:param orientation: An optional orientation. If given,this should
be one of Image.FLIP_LEFT_RIGHT,
Image.ROTATE_90,or Image.ROTATE_270.
"""
self.font = font
self.orientation = orientation # any 'transpose' argument,or None
def mirror(image):
"""
Flip image horizontally (left to right).
:param image: The image to mirror.
:return: An image.
"""
return image.transpose(Image.FLIP_LEFT_RIGHT)
def mirror(image):
"""
Flip image horizontally (left to right).
:param image: The image to mirror.
:return: An image.
"""
return image.transpose(Image.FLIP_LEFT_RIGHT)
def flip_image(input_file, input_Box):
prefix = os.path.splitext(input_file)[0]
x1 = input_Box[0]["x1"]
y1 = input_Box[0]["y1"]
x2 = input_Box[0]["x2"]
y2 = input_Box[0]["y2"]
im = Image.open(input_file)
im1 = im.transpose(Image.FLIP_LEFT_RIGHT)
im2 = im.transpose(Image.FLIP_TOP_BottOM)
output_file = [
prefix + "_flip_1.bmp", prefix + "_flip_2.bmp"]
output_Box = [
{
"x1": SIZE - 1 - x1,
"x2": SIZE - 1 - x2,
"y1": y1,
"y2": y2,
},
{
"x1": x1,
"x2": x2,
"y1": SIZE - 1 - y1,
"y2": SIZE - 1 - y2,
]
im1.save(output_file[0])
im2.save(output_file[1])
# draw_Box(im1,output_Box[0]).save(output_file[0])
# draw_Box(im2,output_Box[1]).save(output_file[1])
return output_file, output_Box
def __call__(self, img):
img_flip = img.transpose(Image.FLIP_LEFT_RIGHT)
center_crop = transforms.CenterCrop(self.size)
img_list = []
w, h = img.size
for image in [img, img_flip]:
img_list.append(center_crop(image))
img_list.append(image.crop((0, 0, self.size, self.size)))
img_list.append(image.crop((w-self.size, w, self.size)))
img_list.append(image.crop((0, h - self.size, h)))
img_list.append(image.crop((w-self.size, h-self.size, h)))
imgs = None
to_tensor = transforms.ToTensor()
for image in img_list:
if imgs is None:
temp_img = to_tensor(image)
imgs = self.normalize(temp_img)
else:
temp_img = to_tensor(image)
temp_img = self.normalize(temp_img)
imgs = torch.cat((imgs, temp_img))
return imgs
# ---------------------------------------------------------------------------------------------
# from: https://github.com/eladhoffer/convNet.pytorch/blob/master/preprocess.py
def load_image_transform(self, idx, scale, rotation, trans_h, trans_w, flip):
img_W = np.int( self.W*(1.0 + scale) )
img_H = np.int( self.H*(1.0 + scale) )
print >> sys.stderr, 'loading {}/00000.jpg'.format(idx)
print >> sys.stderr, 'scale: {}; rotation: {}; translation: ({},{}); flip: {}.'.format(scale, flip)
im = Image.open('{}/JPEGImages/480p/{}/00000.jpg'.format(self.davis_dir, idx))
im = im.resize((img_W,img_H))
im = im.transform((img_W,img_H),Image.AFFINE,(1,trans_w,1,trans_h))
im = im.rotate(rotation)
if flip:
im = im.transpose(Image.FLIP_LEFT_RIGHT)
if scale>0:
Box = (np.int((img_W - self.W)/2), np.int((img_H - self.H)/2), np.int((img_W - self.W)/2)+self.W, np.int((img_H - self.H)/2)+self.H)
im = im.crop(Box)
else:
im = im.resize((self.W, self.H))
# im_name = 'img_{}_{}.jpg'.format(trans_h,trans_w)
# im.save(im_name,"JPEG")
# print(im.size)
in_ = np.array(im, dtype=np.float32)
in_ = in_[:,::-1]
in_ -= self.mean
return in_
def load_label_transform(self, flip):
img_W = np.int( self.W*(1.0 + scale) )
img_H = np.int( self.H*(1.0 + scale) )
# print >> sys.stderr,'loading {}'.format(idx)
# print >> sys.stderr,'scale: {}; rotation: {}; translation: ({},{}); flip: {}.'.format(scale,rotation,trans_w,trans_h,flip)
im = Image.open('{}/Annotations/2017/{}/00000.png'.format(self.davis_dir, idx))
im = im.resize((img_W,img_H))
im = im.transform((img_W,trans_h))
im = im.rotate(rotation)
if flip:
im = im.transpose(Image.FLIP_LEFT_RIGHT)
if scale>0:
w_start = np.int(random.random()*(img_W - self.W))
h_start = np.int(random.random()*(img_H - self.H))
Box = (w_start, h_start, w_start+self.W, h_start+self.H)
im = im.crop(Box)
else:
im = im.resize((self.W, self.H))
# im_name = 'label_{}_{}.png'.format(trans_h,trans_w)
# im.save(im_name,"PNG")
# print(im.size)
label = np.array(im, dtype=np.uint8)
print >> sys.stderr, 'Number of Objects: {}'.format(np.max(label))
label = np.uint8((label>0))
return label
def load_image_transform(self, 'loading {}'.format(idx)
print >> sys.stderr, flip)
im = Image.open('{}/{}'.format(self.davis_dir,::-1]
in_ -= self.mean
return in_
def load_label_transform(self,flip)
im = Image.open('{}/{}'.format(self.davis_dir, 'Number of Objects: {}'.format(np.max(label))
label = np.uint8((label>0))
return label
def load_image_transform(self,::-1]
in_ -= self.mean
return in_
def get_example(self, i):
# type: (any) -> typing.Tuple[str,Image]
path = os.path.join(self._root, self._paths[i])
image = Image.open(path)
if self._resize is not None:
image = image.resize(self._resize)
if self._crop_size is not None:
width, height = image.size
if self._test is True:
top = int((height - self._crop_size[1]) / 2)
left = int((width - self._crop_size[0]) / 2)
bottom = top + self._crop_size[1]
right = left + self._crop_size[0]
else:
top = numpy.random.randint(height - self._crop_size[1] + 1)
left = numpy.random.randint(width - self._crop_size[0] + 1)
bottom = top + self._crop_size[1]
right = left + self._crop_size[0]
image = image.crop((left, top, right, bottom))
if self._flip:
if numpy.random.randint(2) == 1:
image = image.transpose(Image.FLIP_LEFT_RIGHT)
return path, image
def __call__(self, img_group, is_flow=False):
v = random.random()
if v < 0.5:
ret = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in img_group]
if self.is_flow:
for i in range(0, len(ret), 2):
ret[i] = ImageOps.invert(ret[i]) # invert flow pixel values when flipping
return ret
else:
return img_group
def mirror(message: discord.Message, image_arg: image, extension: str.lower=None):
""" Mirror an image along the x-axis. """
if extension:
image_arg.set_extension(extension)
# Mirror the image
image_arg.modify(Image.Image.transpose, Image.FLIP_LEFT_RIGHT)
await send_image(message, image_arg)
def horizontal_reflection(img):
#flips an image horizontally
if isinstance(img,(np.ndarray,np.core.memmap)):
img = np.array(Image.fromarray(img).transpose(Image.FLIP_LEFT_RIGHT))
else:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
return img
def flip_vertical(img):
"""
Flip image over the vertical axis
:param img: PIL image object
:return: PIL image object
"""
return img.transpose(Image.FLIP_LEFT_RIGHT)
def __call__(self, 2):
ret[i] = ImageOps.invert(ret[i]) # invert flow pixel values when flipping
return ret
else:
return img_group
def __call__(self, img_group):
if self.scale_worker is not None:
img_group = self.scale_worker(img_group)
image_w, o_h + crop_h))
normal_group.append(crop)
flip_crop = crop.copy().transpose(Image.FLIP_LEFT_RIGHT)
if img.mode == 'L' and i % 2 == 0:
flip_group.append(ImageOps.invert(flip_crop))
else:
flip_group.append(flip_crop)
oversample_group.extend(normal_group)
oversample_group.extend(flip_group)
return oversample_group
def fliplr_img(imdir,outdir,deg):
im = Image.open(imdir)
out_filename = outdir
im.transpose(Image.FLIP_LEFT_RIGHT).save(out_filename, 'JPEG', quality = 100)
def fliplr_img(imdir,outdir):
im = Image.open(imdir)
out_filename = outdir
im.transpose(Image.FLIP_LEFT_RIGHT).save(out_filename, quality = 100)
def mask(cls, size, round=0):
"""Rectangular mask with optional rounded corners."""
m = Image.new("L", 255)
if round > 0:
w, h = int(round * size[0] / 2), int(round * size[1] / 2)
m.place(Quadrant.mask((w,h)), align=(0,0), copy=False)
m.place(Quadrant.mask((w,h)).transpose(Image.FLIP_LEFT_RIGHT), align=(1,h)).transpose(Image.FLIP_TOP_BottOM),1),h)).transpose(Image.ROTATE_180), copy=False)
return m
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。