Python PIL.ImageOps.flip() Examples

The following are 13 code examples of PIL.ImageOps.flip(). 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.ImageOps , or try the search function .
Example #1
Source File: dataset.py    From STARnet with MIT License 6 votes vote down vote up
def augment(img_in, img_tar, img_tar_l, flip_h=True, rot=True):
    info_aug = {'flip_h': False, 'flip_v': False, 'trans': False}
    
    if random.random() < 0.5 and flip_h:
        img_in = [ImageOps.flip(j) for j in img_in]
        img_tar = [ImageOps.flip(j) for j in img_tar]
        img_tar_l = ImageOps.flip(img_tar_l)
        info_aug['flip_h'] = True

    if rot:
        if random.random() < 0.5:
            img_in = [ImageOps.mirror(j) for j in img_in]
            img_tar = [ImageOps.mirror(j) for j in img_tar]
            img_tar_l = ImageOps.mirror(img_tar_l)
            info_aug['flip_v'] = True
        if random.random() < 0.5:
            img_in = [j.rotate(180) for j in img_in]
            img_tar = [j.rotate(180) for j in img_tar]
            img_tar_l = img_tar_l.rotate(180)
            info_aug['trans'] = True

    return img_in, img_tar, img_tar_l, info_aug 
Example #2
Source File: dataset.py    From iSeeBetter with MIT License 6 votes vote down vote up
def augment(img_in, img_tar, img_nn, flip_h=True, rot=True):
    info_aug = {'flip_h': False, 'flip_v': False, 'trans': False}
    
    if random.random() < 0.5 and flip_h:
        img_in = ImageOps.flip(img_in)
        img_tar = ImageOps.flip(img_tar)
        img_nn = [ImageOps.flip(j) for j in img_nn]
        info_aug['flip_h'] = True

    if rot:
        if random.random() < 0.5:
            img_in = ImageOps.mirror(img_in)
            img_tar = ImageOps.mirror(img_tar)
            img_nn = [ImageOps.mirror(j) for j in img_nn]
            info_aug['flip_v'] = True
        if random.random() < 0.5:
            img_in = img_in.rotate(180)
            img_tar = img_tar.rotate(180)
            img_nn = [j.rotate(180) for j in img_nn]
            info_aug['trans'] = True

    return img_in, img_tar, img_nn, info_aug 
Example #3
Source File: renderer.py    From strike-with-a-pose with GNU General Public License v3.0 6 votes vote down vote up
def get_normal_map(self):
        """See: https://stackoverflow.com/questions/5281261/generating-a-normal-map-from-a-height-map
        and: https://stackoverflow.com/questions/34644101/calculate-surface-normals-from-depth-image-using-neighboring-pixels-cross-produc
        and: https://en.wikipedia.org/wiki/Normal_mapping#How_it_works.

        :return:
        """
        (depth, depth_normed) = self.get_depth_arrays()
        depth_pad = np.pad(depth_normed, 1, "constant")
        (dx, dy) = (1 / depth.shape[1], 1 / depth.shape[0])
        dz_dx = (depth_pad[1:-1, 2:] - depth_pad[1:-1, :-2]) / (2 * dx)
        dz_dy = (depth_pad[2:, 1:-1] - depth_pad[:-2, 1:-1]) / (2 * dy)
        norms = np.stack([-dz_dx.flatten(), -dz_dy.flatten(), np.ones(dz_dx.size)])
        magnitudes = np.linalg.norm(norms, axis=0)
        norms /= magnitudes
        norms = norms.T
        norms[:, :2] = 255 * (norms[:, :2] + 1) / 2
        norms[:, 2] = 127 * norms[:, 2] + 128
        norms = np.uint8(norms).reshape((*depth.shape, 3))
        return ImageOps.flip(Image.fromarray(norms)) 
Example #4
Source File: notsobot.py    From Trusty-cogs with MIT License 6 votes vote down vote up
def do_haah(self, b):
        f = BytesIO()
        f2 = BytesIO()
        with wand.image.Image(file=b) as img:
            h1 = img.clone()
            h1.transform("50%x100%")
            h2 = h1.clone()
            h2.rotate(degree=180)
            h2.flip()
            h1.save(file=f)
            h2.save(file=f2)
        f.seek(0)
        f2.seek(0)
        list_im = [f2, f]
        imgs = [ImageOps.mirror(Image.open(i).convert("RGBA")) for i in list_im]
        min_shape = sorted([(np.sum(i.size), i.size) for i in imgs])[0][1]
        imgs_comb = np.hstack([np.asarray(i.resize(min_shape)) for i in imgs])
        imgs_comb = Image.fromarray(imgs_comb)
        final = BytesIO()
        imgs_comb.save(final, "png")
        file_size = final.tell()
        final.seek(0)
        return final, file_size 
Example #5
Source File: dataset.py    From DBPN-Pytorch with MIT License 6 votes vote down vote up
def augment(img_in, img_tar, img_bic, flip_h=True, rot=True):
    info_aug = {'flip_h': False, 'flip_v': False, 'trans': False}
    
    if random.random() < 0.5 and flip_h:
        img_in = ImageOps.flip(img_in)
        img_tar = ImageOps.flip(img_tar)
        img_bic = ImageOps.flip(img_bic)
        info_aug['flip_h'] = True

    if rot:
        if random.random() < 0.5:
            img_in = ImageOps.mirror(img_in)
            img_tar = ImageOps.mirror(img_tar)
            img_bic = ImageOps.mirror(img_bic)
            info_aug['flip_v'] = True
        if random.random() < 0.5:
            img_in = img_in.rotate(180)
            img_tar = img_tar.rotate(180)
            img_bic = img_bic.rotate(180)
            info_aug['trans'] = True
            
    return img_in, img_tar, img_bic, info_aug 
Example #6
Source File: megaface_utils.py    From InsightFace-PyTorch with Apache License 2.0 5 votes vote down vote up
def get_image(transformer, filepath, flip=False):
    img = Image.open(filepath)
    if flip:
        img = ImageOps.flip(img)
    img = transformer(img)
    return img.to(device) 
Example #7
Source File: dataset.py    From binseg_pytoch with Apache License 2.0 5 votes vote down vote up
def augment_data(self, rotation=True, HFlip=True, VFlip=True):
        
        listImgFiles = [k.split('/')[-1].split('.')[0] for k in glob.glob(os.path.join(self.img_root, '*.bmp'))]
        listFilesTrain = [k for k in listImgFiles if 'train' in k]
        listFilesVal = [k for k in listImgFiles if 'train' not in k]

        for filenames in tqdm(listFilesVal):
            src_im = Image.open(os.path.join(self.img_root, filenames + '.bmp')).resize((self.input_width, self.input_height),Image.ANTIALIAS)
            gt_im = Image.open(os.path.join(self.gt_root, filenames + '.bmp')).resize((self.input_width, self.input_height),Image.ANTIALIAS)
            src_im.save(os.path.join(self.img_root, filenames + '.bmp'))
            gt_im.save(os.path.join(self.gt_root, filenames + '.bmp'))

        for filenames in tqdm(listFilesTrain):
            src_im = Image.open(os.path.join(self.img_root, filenames + '.bmp')).resize((self.input_width, self.input_height),Image.ANTIALIAS)
            gt_im = Image.open(os.path.join(self.gt_root, filenames + '.bmp')).resize((self.input_width, self.input_height),Image.ANTIALIAS)
            src_im.save(os.path.join(self.img_root, filenames + '.bmp'))
            gt_im.save(os.path.join(self.gt_root, filenames + '.bmp'))
            if rotation:
                for angle in [90, 180, 270]:
                    src_im = Image.open(os.path.join(self.img_root, filenames + '.bmp'))
                    gt_im = Image.open(os.path.join(self.gt_root, filenames + '.bmp'))
                    rot_im = src_im.rotate(angle, expand=True).resize((self.input_width, self.input_height),Image.ANTIALIAS)
                    rot_gt = gt_im.rotate(angle, expand=True).resize((self.input_width, self.input_height), Image.ANTIALIAS)
                    rot_im.save(os.path.join(self.img_root, filenames + '_' + str(angle) + '.bmp'))
                    rot_gt.save(os.path.join(self.gt_root, filenames + '_' + str(angle) + '.bmp'))
            if VFlip:
                vert_im = ImageOps.flip(src_im)
                vert_gt = ImageOps.flip(gt_im)
                vert_im.save(os.path.join(self.img_root, filenames + '_vert.bmp'))
                vert_gt.save(os.path.join(self.gt_root, filenames + '_vert.bmp'))
            if HFlip:
                horz_im = ImageOps.mirror(src_im)
                horz_gt = ImageOps.mirror(gt_im)
                horz_im.save(os.path.join(self.img_root, filenames + '_horz.bmp'))
                horz_gt.save(os.path.join(self.gt_root, filenames + '_horz.bmp')) 
Example #8
Source File: renderer.py    From strike-with-a-pose with GNU General Public License v3.0 5 votes vote down vote up
def get_depth_map(self):
        (depth, depth_normed) = self.get_depth_arrays()
        depth_map = np.uint8(255 * depth_normed)
        return ImageOps.flip(Image.fromarray(depth_map, "L")) 
Example #9
Source File: __init__.py    From Semi-supervised-segmentation-cycleGAN with MIT License 5 votes vote down vote up
def PILaugment(img, mask):
    if random.random() > 0.2:
        (w, h) = img.size
        (w_, h_) = mask.size
        assert (w == w_ and h == h_), 'The size should be the same.'
        crop = random.uniform(0.45, 0.75)
        W = int(crop * w)
        H = int(crop * h)
        start_x = w - W
        start_y = h - H
        x_pos = int(random.uniform(0, start_x))
        y_pos = int(random.uniform(0, start_y))
        img = img.crop((x_pos, y_pos, x_pos + W, y_pos + H))
        mask = mask.crop((x_pos, y_pos, x_pos + W, y_pos + H))

    if random.random() > 0.2:
        img = ImageOps.flip(img)
        mask = ImageOps.flip(mask)

    if random.random() > 0.2:
        img = ImageOps.mirror(img)
        mask = ImageOps.mirror(mask)

    if random.random() > 0.2:
        angle = random.random() * 90 - 45
        img = img.rotate(angle)
        mask = mask.rotate(angle)
    if random.random() > 0.95:
        img = img.filter(ImageFilter.GaussianBlur(2))

    if random.random() > 0.95:
        img = ImageEnhance.Contrast(img).enhance(1)

    if random.random() > 0.95:
        img = ImageEnhance.Brightness(img).enhance(1)

    return img, mask 
Example #10
Source File: notsobot.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def do_waaw(self, b):
        f = BytesIO()
        f2 = BytesIO()
        with wand.image.Image(file=b) as img:
            h1 = img.clone()
            width = int(img.width / 2) if int(img.width / 2) > 0 else 1
            h1.crop(width=width, height=int(img.height), gravity="east")
            h2 = h1.clone()
            h1.rotate(degree=180)
            h1.flip()
            h1.save(file=f)
            h2.save(file=f2)
        f.seek(0)
        f2.seek(0)
        list_im = [f2, f]
        imgs = [ImageOps.mirror(Image.open(i).convert("RGBA")) for i in list_im]
        min_shape = sorted([(np.sum(i.size), i.size) for i in imgs])[0][1]
        imgs_comb = np.hstack([np.asarray(i.resize(min_shape)) for i in imgs])
        imgs_comb = Image.fromarray(imgs_comb)
        final = BytesIO()
        imgs_comb.save(final, "png")
        file_size = final.tell()
        final.seek(0)
        return final, file_size

    # Thanks to Iguniisu#9746 for the idea 
Example #11
Source File: notsobot.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def flipimg(self, ctx, urls: ImageFinder = None):
        """Rotate an image 180 degrees"""
        if urls is None:
            urls = await ImageFinder().search_for_images(ctx)
        url = urls[0]
        async with ctx.typing():
            b, mime = await self.bytes_download(url)
            if b is False:
                await ctx.send(":warning: **Command download function failed...**")
                return

            def flip_img(b):
                img = Image.open(b)
                img = ImageOps.flip(img)
                final = BytesIO()
                img.save(final, "png")
                file_size = final.tell()
                final.seek(0)
                return discord.File(final, filename="flip.png"), file_size

            task = ctx.bot.loop.run_in_executor(None, flip_img, b)
            try:
                file, file_size = await asyncio.wait_for(task, timeout=60)
            except asyncio.TimeoutError:
                return await ctx.send("The image is too large.")
            await self.safe_send(ctx, None, file, file_size) 
Example #12
Source File: megaface_utils.py    From InsightFace-PyTorch with Apache License 2.0 4 votes vote down vote up
def gen_feature(path, model):
    model.eval()

    print('gen features {}...'.format(path))
    # Preprocess the total files count
    files = []
    for filepath in walkdir(path, ('.jpg', '.png')):
        files.append(filepath)
    file_count = len(files)

    transformer = data_transforms['val']

    batch_size = 128

    with torch.no_grad():
        for start_idx in tqdm(range(0, file_count, batch_size)):
            end_idx = min(file_count, start_idx + batch_size)
            length = end_idx - start_idx

            imgs_0 = torch.zeros([length, 3, 112, 112], dtype=torch.float, device=device)
            for idx in range(0, length):
                i = start_idx + idx
                filepath = files[i]
                imgs_0[idx] = get_image(transformer, filepath, flip=False)

            features_0 = model(imgs_0.to(device))
            features_0 = features_0.cpu().numpy()

            imgs_1 = torch.zeros([length, 3, 112, 112], dtype=torch.float, device=device)
            for idx in range(0, length):
                i = start_idx + idx
                filepath = files[i]
                imgs_1[idx] = get_image(transformer, filepath, flip=True)

            features_1 = model(imgs_1.to(device))
            features_1 = features_1.cpu().numpy()

            for idx in range(0, length):
                i = start_idx + idx
                filepath = files[i]
                filepath = filepath.replace(' ', '_')
                tarfile = filepath + '_0.bin'
                feature = features_0[idx] + features_1[idx]
                write_feature(tarfile, feature / np.linalg.norm(feature)) 
Example #13
Source File: test_imageops.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_sanity(self):

        ImageOps.autocontrast(hopper("L"))
        ImageOps.autocontrast(hopper("RGB"))

        ImageOps.autocontrast(hopper("L"), cutoff=10)
        ImageOps.autocontrast(hopper("L"), ignore=[0, 255])

        ImageOps.colorize(hopper("L"), (0, 0, 0), (255, 255, 255))
        ImageOps.colorize(hopper("L"), "black", "white")

        ImageOps.pad(hopper("L"), (128, 128))
        ImageOps.pad(hopper("RGB"), (128, 128))

        ImageOps.crop(hopper("L"), 1)
        ImageOps.crop(hopper("RGB"), 1)

        ImageOps.deform(hopper("L"), self.deformer)
        ImageOps.deform(hopper("RGB"), self.deformer)

        ImageOps.equalize(hopper("L"))
        ImageOps.equalize(hopper("RGB"))

        ImageOps.expand(hopper("L"), 1)
        ImageOps.expand(hopper("RGB"), 1)
        ImageOps.expand(hopper("L"), 2, "blue")
        ImageOps.expand(hopper("RGB"), 2, "blue")

        ImageOps.fit(hopper("L"), (128, 128))
        ImageOps.fit(hopper("RGB"), (128, 128))

        ImageOps.flip(hopper("L"))
        ImageOps.flip(hopper("RGB"))

        ImageOps.grayscale(hopper("L"))
        ImageOps.grayscale(hopper("RGB"))

        ImageOps.invert(hopper("L"))
        ImageOps.invert(hopper("RGB"))

        ImageOps.mirror(hopper("L"))
        ImageOps.mirror(hopper("RGB"))

        ImageOps.posterize(hopper("L"), 4)
        ImageOps.posterize(hopper("RGB"), 4)

        ImageOps.solarize(hopper("L"))
        ImageOps.solarize(hopper("RGB"))

        ImageOps.exif_transpose(hopper("L"))
        ImageOps.exif_transpose(hopper("RGB"))