Python PIL.Image.FLIP_TOP_BOTTOM Examples

The following are 30 code examples for showing how to use PIL.Image.FLIP_TOP_BOTTOM(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module PIL.Image , or try the search function .

Example 1
Project: Custom-vision-service-iot-edge-raspberry-pi   Author: Azure-Samples   File: predict-amd64.py    License: MIT License 6 votes vote down vote up
def update_orientation(image):
    exif_orientation_tag = 0x0112
    if hasattr(image, '_getexif'):
        exif = image._getexif()
        if exif != None and exif_orientation_tag in exif:
            orientation = exif.get(exif_orientation_tag, 1)
            log_msg('Image has EXIF Orientation: ' + str(orientation))
            # orientation is 1 based, shift to zero based and flip/transpose based on 0-based values
            orientation -= 1
            if orientation >= 4:
                image = image.transpose(Image.TRANSPOSE)
            if orientation == 2 or orientation == 3 or orientation == 6 or orientation == 7:
                image = image.transpose(Image.FLIP_TOP_BOTTOM)
            if orientation == 1 or orientation == 2 or orientation == 5 or orientation == 6:
                image = image.transpose(Image.FLIP_LEFT_RIGHT)
    return image 
Example 2
Project: Custom-vision-service-iot-edge-raspberry-pi   Author: Azure-Samples   File: predict.py    License: MIT License 6 votes vote down vote up
def update_orientation(image):
    exif_orientation_tag = 0x0112
    if hasattr(image, '_getexif'):
        exif = image._getexif()
        if exif != None and exif_orientation_tag in exif:
            orientation = exif.get(exif_orientation_tag, 1)
            log_msg('Image has EXIF Orientation: ' + str(orientation))
            # orientation is 1 based, shift to zero based and flip/transpose based on 0-based values
            orientation -= 1
            if orientation >= 4:
                image = image.transpose(Image.TRANSPOSE)
            if orientation == 2 or orientation == 3 or orientation == 6 or orientation == 7:
                image = image.transpose(Image.FLIP_TOP_BOTTOM)
            if orientation == 1 or orientation == 2 or orientation == 5 or orientation == 6:
                image = image.transpose(Image.FLIP_LEFT_RIGHT)
    return image 
Example 3
Project: pg   Author: fogleman   File: core.py    License: MIT License 6 votes vote down vote up
def __init__(
        self, unit, im,
        min_filter=GL_LINEAR, mag_filter=GL_LINEAR,
        wrap_s=GL_REPEAT, wrap_t=GL_REPEAT,
        mipmap=False):
        self.unit = unit
        if isinstance(im, basestring):
            im = Image.open(im)
        im = im.convert('RGBA').transpose(Image.FLIP_TOP_BOTTOM)
        self.size = width, height = im.size
        data = im.tobytes()
        self.handle = glGenTextures(1)
        self.bind()
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t)
        glTexImage2D(
            GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
            GL_UNSIGNED_BYTE, data)
        if mipmap:
            glGenerateMipmap(GL_TEXTURE_2D) 
Example 4
Project: sketal   Author: ekonda   File: quote.py    License: MIT License 6 votes vote down vote up
def __init__(self, *commands, prefixes=None, strict=False):
        """Answers with image containing stylish quote."""

        if not commands:
            commands = ("цитата",)

        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"), 24)
        self.fs = ImageFont.truetype(self.get_path("font.ttf"), 16)
        self.fss = ImageFont.truetype(self.get_path("font.ttf"), 15)

        example = self.command_example()
        self.description = [f"Генератор цитат",
                            f"{example} [титул] - перешлите сообщение и укажите титул (по желанию) и "
                             "получите цитату!"] 
Example 5
Project: GroundControl   Author: MaslowCNC   File: backgroundMenu.py    License: GNU General Public License v3.0 6 votes vote down vote up
def processBackground(self):
        if self.data.backgroundFile == "" or os.path.isdir(self.data.backgroundFile) or not os.path.isfile(self.data.backgroundFile):
            self.data.backgroundTexture = None
            self.data.backgroundManualReg = []
            self.updateAlignmentInConfig()
            self.data.backgroundRedraw = True
            return
        else:
            img = PILImage.open(self.data.backgroundFile)
            img.thumbnail((1920, 1080), PILImage.ANTIALIAS)
            img = img.transpose(PILImage.FLIP_TOP_BOTTOM)
            imgBytes = BytesIO()
            img.save(imgBytes, format="png")
            imgBytes.seek(0)
            texture = CoreImage(imgBytes, ext="png").texture
            self.data.backgroundTexture = texture
            if self.data.backgroundManualReg:
                # Already have centers to use; just go on to warp_image
                self.warp_image()
            else:
                # Start the manual alignment process
                self.realignBackground() 
Example 6
def vflip(img):
    """Vertically flip the given PIL Image.
    Args:
        img (PIL Image): Image to be flipped.
    Returns:
        PIL Image: Vertically flipped image.
    """

    is_numpy = isinstance(img, np.ndarray)

    if not _is_pil_image(img):
        if is_numpy:
            img = Image.fromarray(img)
        else:
            raise TypeError(
                'img should be PIL Image or numpy array. \
                Got {}'.format(type(img)))

    img = img.transpose(Image.FLIP_TOP_BOTTOM)

    if is_numpy:
        img = np.array(img)

    return img 
Example 7
Project: ursina   Author: pokepetter   File: texture.py    License: MIT License 6 votes vote down vote up
def __init__(self, value):

        if isinstance(value, str):
            value = Path(value)

        if isinstance(value, Path):
            self.path = Path(value)
            self._texture = loader.loadTexture(Filename.fromOsSpecific(str(value)))
            self._cached_image = None   # for get_pixel() method

        elif isinstance(value, PandaTexture):
            self._texture = value

        else:
            from PIL import Image
            image = value
            self._texture = PandaTexture()
            self._texture.setup2dTexture(image.width, image.height, PandaTexture.TUnsignedByte, PandaTexture.FRgba)
            self._texture.setRamImageAs(image.transpose(Image.FLIP_TOP_BOTTOM).tobytes(), image.mode)
            self._cached_image = image.transpose(Image.FLIP_TOP_BOTTOM)
            self.path = None



        self.filtering = Texture.default_filtering 
Example 8
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: images_stub.py    License: Apache License 2.0 6 votes vote down vote up
def _CorrectOrientation(self, image, orientation):
    """Use PIL to correct the image orientation based on its EXIF.

    See JEITA CP-3451 at http://www.exif.org/specifications.html,
    Exif 2.2, page 18.

    Args:
      image: source PIL.Image.Image object.
      orientation: integer in range (1,8) inclusive, corresponding the image
        orientation from EXIF.

    Returns:
      PIL.Image.Image with transforms performed on it. If no correction was
        done, it returns the input image.
    """


    if orientation == 2:
      image = image.transpose(Image.FLIP_LEFT_RIGHT)
    elif orientation == 3:
      image = image.rotate(180)
    elif orientation == 4:
      image = image.transpose(Image.FLIP_TOP_BOTTOM)
    elif orientation == 5:
      image = image.transpose(Image.FLIP_TOP_BOTTOM)
      image = image.rotate(270)
    elif orientation == 6:
      image = image.rotate(270)
    elif orientation == 7:
      image = image.transpose(Image.FLIP_LEFT_RIGHT)
      image = image.rotate(270)
    elif orientation == 8:
      image = image.rotate(90)

    return image 
Example 9
Project: Anime-Super-Resolution   Author: wmylxmj   File: utils.py    License: MIT License 6 votes vote down vote up
def flip(self, lr, hr):
        mode = random.choice([0, 1, 2, 3])
        if mode == 0:
            pass
        elif mode == 1:
            lr = lr.transpose(Image.FLIP_LEFT_RIGHT)
            hr = hr.transpose(Image.FLIP_LEFT_RIGHT)
            pass
        elif mode == 2:
            lr = lr.transpose(Image.FLIP_TOP_BOTTOM)
            hr = hr.transpose(Image.FLIP_TOP_BOTTOM)
            pass
        elif mode == 3:
            lr = lr.transpose(Image.FLIP_LEFT_RIGHT)
            hr = hr.transpose(Image.FLIP_LEFT_RIGHT)
            lr = lr.transpose(Image.FLIP_TOP_BOTTOM)
            hr = hr.transpose(Image.FLIP_TOP_BOTTOM)
            pass
        return lr, hr 
Example 10
def load_texture(path, texture):
    glBindTexture(GL_TEXTURE_2D, texture)
    # Set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    # Set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    # load image
    image = Image.open(path)
    image = image.transpose(Image.FLIP_TOP_BOTTOM)
    img_data = image.convert("RGBA").tobytes()
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data)
    return texture


# for use with pygame 
Example 11
Project: vergeml   Author: mme   File: flip_vertical.py    License: MIT License 5 votes vote down vote up
def transform_xy(self, x, y, rng):
      
        if rng.uniform(0.0, 1.0) < self.chance:

            x = x if not isinstance(x, ImageType) else x.transpose(Image.FLIP_TOP_BOTTOM)
            y = y if not isinstance(y, ImageType) else y.transpose(Image.FLIP_TOP_BOTTOM)
            
        return x, y 
Example 12
Project: Pytorch-Project-Template   Author: moemen95   File: voc_utils.py    License: MIT License 5 votes vote down vote up
def __call__(self, img):
        if random.random() < 0.5:
            return img.transpose(Image.FLIP_TOP_BOTTOM)
        return img 
Example 13
Project: robosat   Author: mapbox   File: transforms.py    License: MIT License 5 votes vote down vote up
def __call__(self, images, mask):
        """Randomly flips images and their mask top to bottom.

        Args:
          images: the PIL.Image image to transform.
          mask: the PIL.Image mask to transform.

        Returns:
          The PIL.Image (images, mask) tuple with either images and mask flipped or none of them flipped.
        """

        if random.random() < self.p:
            return [v.transpose(Image.FLIP_TOP_BOTTOM) for v in images], mask.transpose(Image.FLIP_TOP_BOTTOM)
        else:
            return images, mask 
Example 14
Project: TGC-Designer-Tools   Author: chadrockey   File: tgc_gui.py    License: Apache License 2.0 5 votes vote down vote up
def drawCourse(cjson):
    global root
    global canvas
    global canvas_image
    data = drawCourseAsImage(cjson)
    im = Image.fromarray((255.0*data).astype(np.uint8), 'RGB').resize((image_width, image_height), Image.NEAREST)
    im = im.transpose(Image.FLIP_TOP_BOTTOM)
    cim = ImageTk.PhotoImage(image=im)

    canvas.img = cim # Need to save reference to ImageTK
    canvas.itemconfig(canvas_image, image = cim)

    drawScorecard(cjson)
    root.update() 
Example 15
Project: LearnPaddle2   Author: yeyupiaoling   File: reader.py    License: Apache License 2.0 5 votes vote down vote up
def train_mapper(sample):
    img_path, label, crop_size, resize_size = sample
    try:
        img = Image.open(img_path)
        # 统一图片大小
        img = img.resize((resize_size, resize_size), Image.ANTIALIAS)
        # 随机水平翻转
        r1 = random.random()
        if r1 > 0.5:
            img = img.transpose(Image.FLIP_LEFT_RIGHT)
        # 随机垂直翻转
        r2 = random.random()
        if r2 > 0.5:
            img = img.transpose(Image.FLIP_TOP_BOTTOM)
        # 随机角度翻转
        r3 = random.randint(-3, 3)
        img = img.rotate(r3, expand=False)
        # 随机裁剪
        r4 = random.randint(0, int(resize_size - crop_size))
        r5 = random.randint(0, int(resize_size - crop_size))
        box = (r4, r5, r4 + crop_size, r5 + crop_size)
        img = img.crop(box)
        # 把图片转换成numpy值
        img = np.array(img).astype(np.float32)
        # 转换成CHW
        img = img.transpose((2, 0, 1))
        # 转换成BGR
        img = img[(2, 1, 0), :, :] / 255.0
        return img, int(label)
    except:
        print("%s 该图片错误,请删除该图片并重新创建图像数据列表" % img_path)


# 获取训练的reader 
Example 16
Project: PyTorchConv3D   Author: tomrunia   File: spatial_transforms.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, img):
        """
        Args:
            img (PIL.Image): Image to be flipped.
        Returns:
            PIL.Image: Randomly flipped image.
        """
        if self.p < 0.5:
            if isinstance(img, np.ndarray):
                return np.flipud(img).copy()
            else:
                return img.transpose(Image.FLIP_TOP_BOTTOM)
        return img 
Example 17
Project: pytorch-semantic-segmentation   Author: mapleneverfade   File: functional.py    License: MIT License 5 votes vote down vote up
def __call__(self, img, label):
        """
        Args:
            img (PIL Image): Image to be flipped.
        Returns:
            PIL Image: Randomly flipped image.
        """
        if random.random() < self.p:
            img = img.transpose(Image.FLIP_LEFT_RIGHT)
            label = label.transpose(Image.FLIP_LEFT_RIGHT) #left or right
        if random.random() < self.p:
            img = img.transpose(Image.FLIP_TOP_BOTTOM)
            label = label.transpose(Image.FLIP_TOP_BOTTOM) # bottom or top
        return img, label 
Example 18
Project: Qualia2.0   Author: Kashu7100   File: transforms.py    License: MIT License 5 votes vote down vote up
def __call__(self, img):
        '''
        Args:
            img (PIL Image): Image to be flipped.
        '''
        if random.random() < self.p:
            if isinstance(img, np.ndarray):
                return img[:,:,::-1,:]
            elif isinstance(img, Image.Image):
                return img.transpose(Image.FLIP_TOP_BOTTOM)
        return img 
Example 19
def get_glasses_info(self, face_shape, face_width):
        """
        获取当前面部的眼镜信息
        :param face_shape:
        :param face_width:
        :return:
        """
        left_eye = face_shape[36:42]
        right_eye = face_shape[42:48]

        left_eye_center = left_eye.mean(axis=0).astype("int")
        right_eye_center = right_eye.mean(axis=0).astype("int")

        y = left_eye_center[1] - right_eye_center[1]
        x = left_eye_center[0] - right_eye_center[0]
        eye_angle = np.rad2deg(np.arctan2(y, x))

        deal = self.deal.resize(
            (face_width, int(face_width * self.deal.size[1] / self.deal.size[0])),
            resample=Image.LANCZOS)

        deal = deal.rotate(eye_angle, expand=True)
        deal = deal.transpose(Image.FLIP_TOP_BOTTOM)

        left_eye_x = left_eye[0, 0] - face_width // 4
        left_eye_y = left_eye[0, 1] - face_width // 6

        return {"image": deal, "pos": (left_eye_x, left_eye_y)} 
Example 20
Project: face-detection-induction-course   Author: tomoncle   File: input_video_stream_paste_mask.py    License: MIT License 5 votes vote down vote up
def get_glasses_info(self, face_shape, face_width):
        """
        获取当前面部的眼镜信息
        :param face_shape:
        :param face_width:
        :return:
        """
        left_eye = face_shape[36:42]
        right_eye = face_shape[42:48]

        left_eye_center = left_eye.mean(axis=0).astype("int")
        right_eye_center = right_eye.mean(axis=0).astype("int")

        y = left_eye_center[1] - right_eye_center[1]
        x = left_eye_center[0] - right_eye_center[0]
        eye_angle = np.rad2deg(np.arctan2(y, x))

        deal = self.deal.resize(
            (face_width, int(face_width * self.deal.size[1] / self.deal.size[0])),
            resample=Image.LANCZOS)

        deal = deal.rotate(eye_angle, expand=True)
        deal = deal.transpose(Image.FLIP_TOP_BOTTOM)

        left_eye_x = left_eye[0, 0] - face_width // 4
        left_eye_y = left_eye[0, 1] - face_width // 6

        return {"image": deal, "pos": (left_eye_x, left_eye_y)} 
Example 21
Project: gctools   Author: thegaragelab   File: pcbpack.py    License: Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def createImage(self, filename):
    """ Generate an image for the current layout.
    """
    img = Image.new("RGB", (int(self.w * 4), int(self.h * 4)), "white")
    drw = ImageDraw.Draw(img)
    for board in self.layout:
      color = "green"
      if board.name == "_lock_":
        color = "red"
      rect = (int(board.x * 4), int(board.y * 4), int((board.x + board.w) * 4), int((board.y + board.h) * 4))
      drw.rectangle(rect, fill = "black")
      rect = (rect[0] + 1, rect[1] + 1, rect[2] - 1, rect[3] - 1)
      drw.rectangle(rect, fill = color)
    img = img.transpose(Image.FLIP_TOP_BOTTOM)
    img.save(filename) 
Example 22
Project: pytorch-semantic-segmentation   Author: zijundeng   File: transforms.py    License: MIT License 5 votes vote down vote up
def __call__(self, img):
        if random.random() < 0.5:
            return img.transpose(Image.FLIP_TOP_BOTTOM)
        return img 
Example 23
Project: Global-Second-order-Pooling-Convolutional-Networks   Author: ZilinGao   File: functional.py    License: MIT License 5 votes vote down vote up
def vflip(img):
    """Vertically flip the given PIL Image.

    Args:
        img (PIL Image): Image to be flipped.

    Returns:
        PIL Image:  Vertically flipped image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    return img.transpose(Image.FLIP_TOP_BOTTOM) 
Example 24
Project: fashion-mnist   Author: kefth   File: utils.py    License: MIT License 5 votes vote down vote up
def __call__(self, img):
        """
        Args:
            img (PIL.Image): Image to be flipped.
        Returns:
            PIL.Image: Randomly flipped image.
        """
        if np.random.random() < 0.5:
            return img.transpose(Image.FLIP_TOP_BOTTOM)
        return img 
Example 25
Project: ImEditor   Author: ImEditor   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def vertical_mirror(img):
    return img.transpose(Image.FLIP_TOP_BOTTOM) 
Example 26
Project: seismic-deeplearning   Author: microsoft   File: augmentations.py    License: MIT License 5 votes vote down vote up
def __call__(self, img, mask):
        if random.random() < 0.5:
            # Note: we use FLIP_TOP_BOTTOM here intentionaly. Due to the dimensions of the image,
            # it ends up being a horizontal flip.
            return (
                img.transpose(Image.FLIP_TOP_BOTTOM),
                mask.transpose(Image.FLIP_TOP_BOTTOM),
            )
        return img, mask 
Example 27
Project: Deep-Exemplar-based-Colorization   Author: msracver   File: functional.py    License: MIT License 5 votes vote down vote up
def vflip(img):
    """Vertically flip the given PIL Image.

    Args:
        img (PIL Image): Image to be flipped.

    Returns:
        PIL Image:  Vertically flipped image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    return img.transpose(Image.FLIP_TOP_BOTTOM) 
Example 28
Project: DualResidualNetworks   Author: liu-vis   File: N_modules.py    License: MIT License 5 votes vote down vote up
def DataAugmentation(im_input, label):
    if random.random() > 0.5:
        label    = label.transpose(   Image.FLIP_LEFT_RIGHT)
        im_input = im_input.transpose(Image.FLIP_LEFT_RIGHT)
#    if random.random() > 0.5:
#        label    = label.transpose(   Image.FLIP_TOP_BOTTOM)
#        im_input = im_input.transpose(Image.FLIP_TOP_BOTTOM)
#    if random.random() > 0.5:
#        angle    = random.choice([90, 180, 270])
#        label    = label.rotate(angle)
#        im_input = im_input.rotate(angle)
    return im_input, label 
Example 29
Project: seam-erasure   Author: zfergus   File: texture.py    License: MIT License 5 votes vote down vote up
def load_texture(fname):
    """ Load a PIL Image with name fname. """
    logging.info("Loading Texture: %s" % os.path.abspath(fname))
    return Image.open(fname).transpose(Image.FLIP_TOP_BOTTOM) 
Example 30
Project: seam-erasure   Author: zfergus   File: texture.py    License: MIT License 5 votes vote down vote up
def save_texture(data, fname):
    """ Save a PIL Image with name fname. """
    logging.info("Saving Texture: %s" % os.path.abspath(fname))
    texture = Image.fromarray(data).transpose(Image.FLIP_TOP_BOTTOM)
    texture.save(fname)