Python PIL.Image 模块,NEAREST 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.Image.NEAREST

项目:pytorch-semseg    作者:meetshah1995    | 项目源码 | 文件源码
def __call__(self, img, mask):
        if self.padding > 0:
            img = ImageOps.expand(img, border=self.padding, fill=0)
            mask = ImageOps.expand(mask, border=self.padding, fill=0)

        assert img.size == mask.size
        w, h = img.size
        th, tw = self.size
        if w == tw and h == th:
            return img, mask
        if w < tw or h < th:
            return img.resize((tw, th), Image.BILINEAR), mask.resize((tw, th), Image.NEAREST)

        x1 = random.randint(0, w - tw)
        y1 = random.randint(0, h - th)
        return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th))
项目:PrivacyScore    作者:PrivacyScore    | 项目源码 | 文件源码
def pixelize_screenshot(screenshot, screenshot_pixelized, target_width=390, pixelsize=3):
    """
    Thumbnail a screenshot to `target_width` and pixelize it.

    :param screenshot: Screenshot to be thumbnailed in pixelized
    :param screenshot_pixelized: File to which the result should be written
    :param target_width: Width of the final thumbnail
    :param pixelsize: Size of the final pixels
    :return: None
    """
    if target_width % pixelsize != 0:
        raise ValueError("pixelsize must divide target_width")

    img = Image.open(screenshot)
    width, height = img.size
    if height > width:
        img = img.crop((0, 0, width, width))
        height = width
    undersampling_width = target_width // pixelsize
    ratio = width / height
    new_height = int(undersampling_width / ratio)
    img = img.resize((undersampling_width, new_height), Image.BICUBIC)
    img = img.resize((target_width, new_height * pixelsize), Image.NEAREST)
    img.save(screenshot_pixelized, format='png')
项目:enet-keras    作者:PavlosMelissinos    | 项目源码 | 文件源码
def resize(item, target_h, target_w, keep_aspect_ratio=False):
    """
    Resizes an image to match target dimensions
    :type item: np.ndarray
    :type target_h: int
    :type target_w: int
    :param item: 3d numpy array or PIL.Image
    :param target_h: height in pixels
    :param target_w: width in pixels
    :param keep_aspect_ratio: If False then image is rescaled to smallest dimension and then cropped
    :return: 3d numpy array
    """
    img = array_to_img(item, scale=False)
    if keep_aspect_ratio:
        img.thumbnail((target_w, target_w), PILImage.ANTIALIAS)
        img_resized = img
    else:
        img_resized = img.resize((target_w, target_h), resample=PILImage.NEAREST)

    # convert output
    img_resized = img_to_array(img_resized)
    img_resized = img_resized.astype(dtype=np.uint8)

    return img_resized
项目:ascii-art-py    作者:blinglnav    | 项目源码 | 文件源码
def scale(image, factor, resample=Image.NEAREST):
    """
    Returns a rescaled image by a specific factor given in parameter.
    A factor greater than 1 expands the image, between 0 and 1 contracts the
    image.

    :param factor: The expansion factor, as a float.
    :param resample: An optional resampling filter. Same values possible as
       in the PIL.Image.resize function.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """
    if factor == 1:
        return image.copy()
    elif factor <= 0:
        raise ValueError("the factor must be greater than 0")
    else:
        size = (int(round(factor * image.width)),
                int(round(factor * image.height)))
        return image.resize(size, resample)
项目:ML-Project    作者:Shiam-Chowdhury    | 项目源码 | 文件源码
def rotate_img(image, angle, color, filter = Image.NEAREST):

    if image.mode == "P" or filter == Image.NEAREST:
        matte = Image.new("1", image.size, 1) # mask
    else:
        matte = Image.new("L", image.size, 255) # true matte
    bg = Image.new(image.mode, image.size, color)
    bg.paste(
        image.rotate(angle, filter),
        matte.rotate(angle, filter)
    )
    return bg


# function to turn grey-colored backgrounds to white. r, b and g specify the
# exact shade of grey color to eliminate. Source: stackoverflow.
项目:EYE-Pi    作者:w84death    | 项目源码 | 文件源码
def refresh_oled(camera):
    camera.capture('oled.jpg')
    img_tmp = Image.open('oled.jpg')
    img_small = img_tmp.resize((85,64), Image.NEAREST).convert("1")
    img2oled.paste(img_small, (0,0))

    draw.polygon([(85,0), (128,0), (128,64), (85,64), (85,0)], fill=000)

    iso = 'AUTO' #str(camera.iso)
    exp = str(camera.exposure_speed) + 'ms'

    draw.text((88, 0), 'EYE-Pi',  font=font, fill=255)
    draw.text((88, 15), 'ISO:',  font=font, fill=255)
    draw.text((88, 25), iso,  font=font, fill=255)
    draw.text((88, 40), 'EXP:',  font=font, fill=255)
    draw.text((88, 50), exp,  font=font, fill=255)
    disp.image(img2oled)
    disp.display()
    last_t = time.time()
项目:pcbot    作者:pckv    | 项目源码 | 文件源码
def resize(message: discord.Message, image_arg: image, resolution: parse_resolution, *options,
                 extension: str.lower=None):
    """ Resize an image with the given resolution formatted as `<width>x<height>`
    or `*<scale>` with an optional extension. """
    if extension:
        image_arg.set_extension(extension)

    # Generate a new image based on the scale
    if resolution[1] == 0:
        w, h = image_arg.object.size
        scale = resolution[0]
        assert w * scale < 3000 and h * scale < 3000, "**The result image must be less than 3000 pixels in each axis.**"
        resolution = (int(w * scale), int(h * scale))

    # Resize and upload the image
    image_arg.modify(Image.Image.resize, resolution, Image.NEAREST if "-nearest" in options else Image.ANTIALIAS)
    await send_image(message, image_arg)
项目:tf-unet    作者:ankurhanda    | 项目源码 | 文件源码
def get_random_shuffle(self, batch_size):

        imgarray   = np.empty([batch_size, 240, 320, 3],dtype=np.float32)
        labelarray = np.empty([batch_size, 240, 320],dtype=np.float32)

        for x in range(0,batch_size):
            rand_i = randint(1,self.dataset_size-5)
            img = Image.open(self.rgb_names[rand_i]).resize((320,240),Image.BILINEAR)
            labelImg = Image.open(self.label_names[rand_i]).resize((320,240),Image.NEAREST)
            imgarray[x] = np.asarray(img)
            labelarray[x] = np.asarray(labelImg)

        return imgarray,labelarray


#SUNRGBD_dataset = dataset("SUNRGBD","/media/ankur/nnseg/sunrgbd_training.txt")
#img, label = SUNRGBD_dataset.get_random_shuffle(4)
#Image.fromarray(np.uint8(img[1]),'RGB').show()
#label = np.reshape(label,[-1])
#print(label.shape)
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
def __new__(cls, size, fg="black", bg=None, antialias=4, invert=False, **kwargs):
        """Generate an image of the appropriate shape. See mask method for additional shape-specific parameters.
        - size (int/(int,int)): image size
        - fg (color/pattern): image foreground [black]
        - bg (color/pattern): image background [None]
        - antialias (x>0): level of antialiasing (if supported), where 1.0 is none [4.0]
        - invert (boolean): whether to invert the shape mask [False]
        """
        if isinstance(size, Integral): size = (size, size)
        if bg is None: bg = ImageColor.getrgba(fg)._replace(alpha=0)
        if cls.antialiasing:
            orig_size, size = size, [round(s * antialias) for s in size]
            if isinstance(bg, Image.Image): bg = bg.resize([round(s * antialias) for s in bg.size], Image.NEAREST)
            if isinstance(fg, Image.Image): fg = fg.resize([round(s * antialias) for s in fg.size], Image.NEAREST)
        mask = cls.mask(size, **kwargs)
        if invert: mask = mask.invert_mask()
        base = Image.from_pattern(bg, mask.size) if isinstance(bg, Image.Image) else Image.new("RGBA", mask.size, bg)
        fore = Image.from_pattern(fg, mask.size) if isinstance(fg, Image.Image) else  Image.new("RGBA", mask.size, fg)
        img = base.overlay(fore, mask=mask)
        if cls.antialiasing:
            img = img.resize(orig_size, resample=Image.LANCZOS if antialias > 1 else Image.NEAREST)
        return img
项目:pytorch-semantic-segmentation    作者:ZijunDeng    | 项目源码 | 文件源码
def __call__(self, img, mask):
        if self.padding > 0:
            img = ImageOps.expand(img, border=self.padding, fill=0)
            mask = ImageOps.expand(mask, border=self.padding, fill=0)

        assert img.size == mask.size
        w, h = img.size
        th, tw = self.size
        if w == tw and h == th:
            return img, mask
        if w < tw or h < th:
            return img.resize((tw, th), Image.BILINEAR), mask.resize((tw, th), Image.NEAREST)

        x1 = random.randint(0, w - tw)
        y1 = random.randint(0, h - th)
        return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th))
项目:cnn_polyp_detection    作者:odysszis    | 项目源码 | 文件源码
def load_label(self, idx):
        """
        Load binary mask and preprocess:
    - convert to greyscale
    - cast to integer
    - binarize
        """
    idx=idx.split()[0]
        im = Image.open('{}/{}'.format(self.data_dir, idx))
    im=im.resize((self.width, self.height), Image.NEAREST)
    im=im.convert('L')                      # makes it greyscale
    im=np.array(im, dtype=(np.int32))
    label=im
    label[label>0]=1                        # make sure the image is binary
    label=np.array(label,np.uint8)
    # an extra dimension is required by the loss function
        label = label[np.newaxis, ...]   
    return label
项目:cnn_polyp_detection    作者:odysszis    | 项目源码 | 文件源码
def load_label(self, idx):
        """
        Load binary mask and preprocess:
    - resize
    - convert to greyscale
    - cast to integer
    - binarize
        """
        idx = self.indices_label[idx]
        idx=idx.split()[0]
        im = io.imread('{}/{}'.format(self.data_dir, idx))
        im = Image.fromarray(im)
        im=im.resize((self.width, self.height), Image.NEAREST)      # resize
        im=im.convert('L')                      # convert to greyscale
        im=np.array(im, dtype=(np.int32))               # cast to integer
        label=im
        label[label>0]=1                        # convert to binary
        label=np.array(label,np.uint8)
        label = label[np.newaxis, ...]
        return label
项目:cnn_polyp_detection    作者:odysszis    | 项目源码 | 文件源码
def load_label(self, idx):
        """
        Load binary mask and preprocess:
    - convert to greyscale
    - cast to integer
    - binarize
        """
    idx=idx.split()[0]
        im = Image.open('{}/{}'.format(self.data_dir, idx))
    im=im.resize((self.width, self.height), Image.NEAREST)
    im=im.convert('L')                      # makes it greyscale
    im=np.array(im, dtype=(np.int32))
    label=im
    label[label>0]=1                        # make sure the image is binary
    label=np.array(label,np.uint8)
    # an extra dimension is required by the loss function
        label = label[np.newaxis, ...]   
    return label
项目:cnn_polyp_detection    作者:odysszis    | 项目源码 | 文件源码
def load_label(self, idx):
        """
        Load binary mask and preprocess:
    - convert to greyscale
    - cast to integer
    - binarize
        """
    idx=idx.split()[0]
        im = Image.open('{}/{}'.format(self.data_dir, idx))
    im=im.resize((self.width, self.height), Image.NEAREST)
    im=im.convert('L')                      # makes it greyscale
    im=np.array(im, dtype=(np.int32))
    label=im
    label[label>0]=1                        # make sure the image is binary
    label=np.array(label,np.uint8)
    # an extra dimension is required by the loss function
        label = label[np.newaxis, ...]   
    return label
项目:cnn_polyp_detection    作者:odysszis    | 项目源码 | 文件源码
def load_label(self, idx):
        """
        Load binary mask and preprocess:
    - resize
    - convert to greyscale
    - cast to integer
    - binarize
        """
        idx = self.indices_label[idx]
        idx=idx.split()[0]
        im = io.imread('{}/{}'.format(self.data_dir, idx))
        im = Image.fromarray(im)
        im=im.resize((self.width, self.height), Image.NEAREST)      # resize
        im=im.convert('L')                      # convert to greyscale
        im=np.array(im, dtype=(np.int32))               # cast to integer
        label=im
        label[label>0]=1                        # convert to binary
        label=np.array(label,np.uint8)
        label = label[np.newaxis, ...]
        return label
项目:cnn_polyp_detection    作者:odysszis    | 项目源码 | 文件源码
def load_label(self, idx):
        """
        Load binary mask and preprocess:
    - resize
    - convert to greyscale
    - cast to integer
    - binarize
        """
    idx=idx.split()[0]
        im = Image.open('{}/{}'.format(self.data_dir, idx))
    im=im.resize((self.width, self.height), Image.NEAREST)
    im=im.convert('L')                      # convert to greyscale
    im=np.array(im, dtype=(np.int32))
    label=im
    label[label>0]=1                        # make sure the image is binary
    label=np.array(label,np.uint8)
    # an extra dimension is required by the loss function
        label = label[np.newaxis, ...]   
    return label
项目:cnn_polyp_detection    作者:odysszis    | 项目源码 | 文件源码
def load_label(self, idx):
        """
        Load binary mask and preprocess:
    - convert to greyscale
    - cast to integer
    - binarize
        """
    idx=idx.split()[0]
        im = Image.open('{}/{}'.format(self.data_dir, idx))
    im=im.resize((self.width, self.height), Image.NEAREST)
    im=im.convert('L')                      # makes it greyscale
    im=np.array(im, dtype=(np.int32))
    label=im
    label[label>0]=1                        # make sure the image is binary
    label=np.array(label,np.uint8)
    # an extra dimension is required by the loss function
        label = label[np.newaxis, ...]   
    return label
项目:cnn_polyp_detection    作者:odysszis    | 项目源码 | 文件源码
def load_label(self, idx):
        """
        Load binary mask and preprocess:
    - resize
    - convert to greyscale
    - cast to integer
    - binarize
        """
        idx = self.indices_label[idx]
        idx=idx.split()[0]
        im = io.imread('{}/{}'.format(self.data_dir, idx))
        im = Image.fromarray(im)
        im=im.resize((self.width, self.height), Image.NEAREST)      # resize
        im=im.convert('L')                      # convert to greyscale
        im=np.array(im, dtype=(np.int32))               # cast to integer
        label=im
        label[label>0]=1                        # convert to binary
        label=np.array(label,np.uint8)
        label = label[np.newaxis, ...]
        return label
项目:chainer-pix2pix    作者:wuhuikai    | 项目源码 | 文件源码
def _read_image_as_array(path, dtype, load_size, crop_size, flip):
    f = Image.open(path)

    A, B = numpy.array_split(numpy.asarray(f), 2, axis=1)
    if hasattr(f, 'close'):
        f.close()

    A = _resize(A, load_size, Image.BILINEAR, dtype)
    B = _resize(B, load_size, Image.NEAREST, dtype)

    sx, sy = numpy.random.randint(0, load_size-crop_size, 2)
    A = _crop(A, sx, sy, crop_size)
    B = _crop(B, sx, sy, crop_size)

    if flip and numpy.random.rand() > 0.5:
        A = numpy.fliplr(A)
        B = numpy.fliplr(B)

    return A.transpose(2, 0, 1), B.transpose(2, 0, 1)
项目:chainer-pix2pix    作者:pfnet-research    | 项目源码 | 文件源码
def __init__(self, dataDir='./facade/base', data_range=(1,300)):
        print("load dataset start")
        print("    from: %s"%dataDir)
        print("    range: [%d, %d)"%(data_range[0], data_range[1]))
        self.dataDir = dataDir
        self.dataset = []
        for i in range(data_range[0],data_range[1]):
            img = Image.open(dataDir+"/cmp_b%04d.jpg"%i)
            label = Image.open(dataDir+"/cmp_b%04d.png"%i)
            w,h = img.size
            r = 286/min(w,h)
            # resize images so that min(w, h) == 286
            img = img.resize((int(r*w), int(r*h)), Image.BILINEAR)
            label = label.resize((int(r*w), int(r*h)), Image.NEAREST)

            img = np.asarray(img).astype("f").transpose(2,0,1)/128.0-1.0
            label_ = np.asarray(label)-1  # [0, 12)
            label = np.zeros((12, img.shape[1], img.shape[2])).astype("i")
            for j in range(12):
                label[j,:] = label_==j
            self.dataset.append((img,label))
        print("load dataset done")
项目:TensorArtist    作者:vacancy    | 项目源码 | 文件源码
def resize(image, dsize, interpolation='LINEAR'):
    assert interpolation in ('NEAREST', 'LINEAR', 'CUBIC', 'LANCZOS4')

    dsize = tuple(map(int, dsize))
    assert len(dsize) == 2
    if cv2:
        interpolation = getattr(cv2, 'INTER_' + interpolation)
        return cv2.resize(image, dsize, interpolation=interpolation)
    else:
        if interpolation == 'NEAREST':
            interpolation = Image.NEAREST
        elif interpolation == 'LANCZOS4':
            interpolation = Image.LANCZOS
        else:
            interpolation = getattr(Image, 'BI' + interpolation)

        image = pil_nd2img(image)
        image = image.resize(dsize, resample=interpolation)
        return pil_img2nd(image)
项目:pose2img    作者:Hi-king    | 项目源码 | 文件源码
def __init__(self, dataDir='./facade/base', data_range=(1, 300)):
        print("load dataset start")
        print("    from: %s" % dataDir)
        print("    range: [%d, %d)" % (data_range[0], data_range[1]))
        self.dataDir = dataDir
        self.dataset = []
        for i in range(data_range[0], data_range[1]):
            img = Image.open(dataDir + "/cmp_b%04d.jpg" % i)
            label = Image.open(dataDir + "/cmp_b%04d.png" % i)
            w, h = img.size
            r = 286 / min(w, h)
            # resize images so that min(w, h) == 286
            img = img.resize((int(r * w), int(r * h)), Image.BILINEAR)
            label = label.resize((int(r * w), int(r * h)), Image.NEAREST)

            img = numpy.asarray(img).astype("f").transpose(2, 0, 1) / 128.0 - 1.0
            label_ = numpy.asarray(label) - 1  # [0, 12)
            label = numpy.zeros((12, img.shape[1], img.shape[2])).astype("i")
            for j in range(12):
                label[j, :] = label_ == j
            self.dataset.append((img, label))
        print("load dataset done")
项目:gitsome    作者:donnemartin    | 项目源码 | 文件源码
def load_and_resize_image(imgname, antialias, maxLen):
    from PIL import Image
    img = Image.open(imgname)
    # force image to RGBA - deals with palettized images (e.g. gif) etc.
    if img.mode != 'RGBA':
        img = img.convert('RGBA')
    # resize up or down so that longer side of image is maxLen
    if maxLen is not None:
        native_width, native_height = img.size
        rate = float(maxLen) / max(native_width, native_height)
        width = int(rate * native_width) * 2
        height = int(rate * native_height)
        if native_width != width or native_height != height:
            img = img.resize((width, height), Image.ANTIALIAS
                             if antialias else Image.NEAREST)
    return img
项目:ademxapp    作者:itijyou    | 项目源码 | 文件源码
def Scale(size=256, interpolation=Image.CUBIC, shorter_side=True):
    func = min if shorter_side else max
    def _impl(data):
        h, w = data.shape[:2]
        if func(h, w) == size:
            return data
        if func(h, w) == w:
            nw = size
            nh = int(np.round(1. * size * h / w))
        else:
            nw = int(np.round(1. * size * w / h))
            nh = size
        if interpolation != Image.NEAREST:
            interp_method = get_interp_method(h, w, nh, nw)
        return np.array(Image.fromarray(data.astype(np.uint8, copy=False)).resize((nw, nh), interp_method))
    return _impl

# Crop into centered square
项目:Semi-automatic-Annotation    作者:Luoyadan    | 项目源码 | 文件源码
def disp_segBI_on(self):
        print "displaying segBI ON"
        ## unable edit
        self.parent().mode = "view"
        self.img_arr_tmp = self.img_arr.copy()
        img_arr = self.ori_img.copy()

        ## display binary img
        segBI = np.zeros(img_arr.shape[:2], np.uint8)
        segBI[self.seg_arr == self.current_label] = 255
        segBI = cv2.cvtColor(segBI, cv2.COLOR_GRAY2RGB)


        if self.Zoomed == True:
            large_segBI = Image.fromarray(segBI).resize((self.w * self.zRate, self.h * self.zRate), Image.NEAREST)
            cropped_segBI = large_segBI.crop(tuple(self.zoom_pos))
            segBI = np.array(cropped_segBI)

        self.img_arr = segBI
        self.update()
项目:alfred-image-utilities    作者:danielecook    | 项目源码 | 文件源码
def scale(image, factor, resample=Image.NEAREST):
    """
    Returns a rescaled image by a specific factor given in parameter.
    A factor greater than 1 expands the image, between 0 and 1 contracts the
    image.

    :param factor: The expansion factor, as a float.
    :param resample: An optional resampling filter. Same values possible as
       in the PIL.Image.resize function.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """
    if factor == 1:
        return image.copy()
    elif factor <= 0:
        raise ValueError("the factor must be greater than 0")
    else:
        size = (int(round(factor * image.width)),
                int(round(factor * image.height)))
        return image.resize(size, resample)
项目:DualFisheye    作者:ooterness    | 项目源码 | 文件源码
def update_preview(self, psize):
        # Safety check: Ignore calls during construction/destruction.
        if not self.init_done: return
        # Copy latest user settings to the lens object.
        self.lens.fov_deg = self.f.get()
        self.lens.radius_px = self.r.get()
        self.lens.center_px[0] = self.x.get()
        self.lens.center_px[1] = self.y.get()
        # Re-scale the image to match the canvas size.
        # Note: Make a copy first, because thumbnail() operates in-place.
        self.img_sc = self.img.copy()
        self.img_sc.thumbnail(psize, Image.NEAREST)
        self.img_tk = ImageTk.PhotoImage(self.img_sc)
        # Re-scale the x/y/r parameters to match the preview scale.
        pre_scale = float(psize[0]) / float(self.img.size[0])
        x = self.x.get() * pre_scale
        y = self.y.get() * pre_scale
        r = self.r.get() * pre_scale
        # Clear and redraw the canvas.
        self.preview.delete('all')
        self.preview.create_image(0, 0, anchor=tk.NW, image=self.img_tk)
        self.preview.create_oval(x-r, y-r, x+r, y+r,
                                 outline='#C00000', width=3)

    # Make a combined label/textbox/slider for a given variable:
项目:jaccardSegment    作者:bermanmaxim    | 项目源码 | 文件源码
def __call__(self, images):
        single = False
        if not isinstance(images, collections.Sequence):
            images = [images]
            single = True
        interps = self.interpolations
        if interps == 'auto':
            interps = Image.BILINEAR
            if len(images) == 2:
                interps = [Image.BILINEAR, Image.NEAREST]
        if not isinstance(interps, collections.Sequence):
            interps = [interps] * len(images)
        resized = []
        ratio = random.uniform(self.low, self.high)
        for img, interp in zip(images, interps):
            h, w = img.size[0], img.size[1]
            h2, w2 = (int(ratio * h), int(ratio * w))
            img2 = img.resize((h2, w2), interp)
            resized.append(img2)
        if single:
            resized = resized[0]
        return resized
项目:pytorch-semseg    作者:meetshah1995    | 项目源码 | 文件源码
def __call__(self, img, mask):
        assert img.size == mask.size
        return img.resize(self.size, Image.BILINEAR), mask.resize(self.size, Image.NEAREST)
项目:pytorch-semseg    作者:meetshah1995    | 项目源码 | 文件源码
def __call__(self, img, mask):
        assert img.size == mask.size
        w, h = img.size
        if (w >= h and w == self.size) or (h >= w and h == self.size):
            return img, mask
        if w > h:
            ow = self.size
            oh = int(self.size * h / w)
            return img.resize((ow, oh), Image.BILINEAR), mask.resize((ow, oh), Image.NEAREST)
        else:
            oh = self.size
            ow = int(self.size * w / h)
            return img.resize((ow, oh), Image.BILINEAR), mask.resize((ow, oh), Image.NEAREST)
项目:pytorch-semseg    作者:meetshah1995    | 项目源码 | 文件源码
def __call__(self, img, mask):
        assert img.size == mask.size
        for attempt in range(10):
            area = img.size[0] * img.size[1]
            target_area = random.uniform(0.45, 1.0) * area
            aspect_ratio = random.uniform(0.5, 2)

            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))

            if random.random() < 0.5:
                w, h = h, w

            if w <= img.size[0] and h <= img.size[1]:
                x1 = random.randint(0, img.size[0] - w)
                y1 = random.randint(0, img.size[1] - h)

                img = img.crop((x1, y1, x1 + w, y1 + h))
                mask = mask.crop((x1, y1, x1 + w, y1 + h))
                assert (img.size == (w, h))

                return img.resize((self.size, self.size), Image.BILINEAR), mask.resize((self.size, self.size),
                                                                                       Image.NEAREST)

        # Fallback
        scale = Scale(self.size)
        crop = CenterCrop(self.size)
        return crop(*scale(img, mask))
项目:pytorch-semseg    作者:meetshah1995    | 项目源码 | 文件源码
def __call__(self, img, mask):
        rotate_degree = random.random() * 2 * self.degree - self.degree
        return img.rotate(rotate_degree, Image.BILINEAR), mask.rotate(rotate_degree, Image.NEAREST)
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def write(self, s):
        global lcd

        b1 = bytearray()
        b1.extend(s[:(P_WIDTH*P_HEIGHT)])

        mi = min(b1)
        ma = max(b1)
        ra = ma-mi
        b2 = bytearray()

        for pix in range(P_WIDTH*P_HEIGHT):
            b2.append( (b1[pix]*(255/ra))-mi )

        print(max(b1), min(b1), max(b2), min(b2))

        image = Image.frombuffer('L', P_SIZE, b2, "raw", 'L', 0, 1)
        image.thumbnail(S_SIZE, Image.NEAREST)

#         draw = ImageDraw.Draw(image)
#         font = ImageFont.truetype('arial.ttf', 18)
#         
#         draw.rectangle([(0, 0), (115, 22)], fill=255, outline=0)
#         draw.text((2, 2), "TESt *", fill='black', font=font)

        image = ImageOps.invert(image)
        image = image.convert('1')
        lcd.write(image.tobytes())
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def write(self, s):
        global lcd
        image = Image.frombuffer('L', P_SIZE, s, "raw", 'L', 0, 1)
        image = image.crop((self.x, 0, self.x+1, P_HEIGHT))
        self.image_scan.paste(image,(self.x, 0))
        if self.x < P_WIDTH-1:
            self.x += 1
        image = ImageOps.invert(self.image_scan)
        image.thumbnail(S_SIZE, Image.NEAREST)
        image = image.convert('1')
        lcd.write(image.tobytes())
项目:PixelDCN    作者:HongyangGao    | 项目源码 | 文件源码
def build_h5_dataset(data_dir, list_path, out_dir, shape, name, norm=False):
    images = read_images(list_path)
    images_size = len(images)
    dataset = h5py.File(out_dir+name+'.h5', 'w')
    dataset.create_dataset('X', (images_size, *shape, 3), dtype='f')
    dataset.create_dataset('Y', (images_size, *shape), dtype='f')
    pbar = ProgressBar()
    for index, (image, label) in pbar(enumerate(images)):
        image = process_image(data_dir+image, shape)
        label = process_image(data_dir+label, shape, Image.NEAREST)
        image -= IMG_MEAN
        image = image / 255. if norm else image
        dataset['X'][index], dataset['Y'][index] = image, label
    dataset.close()
项目:Boundary-Trees    作者:jayricco    | 项目源码 | 文件源码
def boundary_tree_to_texture(boundary_tree, texture, size, img_mesh):
    sz = texture.size
    arr = array('B')
    img = boundary_tree_to_image(boundary_tree, size, img_mesh)
    img_resize = img.resize(size=sz, resample=Image.NEAREST)
    [arr.extend(list(c)) for c in img_resize.getdata()]
    texture.blit_buffer(arr, colorfmt='rgb', bufferfmt='ubyte')
    return texture
项目:3D_Dense_Transformer_Networks    作者:JohnYC1995    | 项目源码 | 文件源码
def build_h5_dataset(data_dir, list_path, out_dir, shape, name, norm=False):
    images = read_images(list_path)
    images_size = len(images)
    dataset = h5py.File(out_dir+name+'.h5', 'w')
    dataset.create_dataset('X', (images_size, *shape, 3), dtype='f')
    dataset.create_dataset('Y', (images_size, *shape), dtype='f')
    pbar = ProgressBar()
    for index, (image, label) in pbar(enumerate(images)):
        image = process_image(data_dir+image, shape)
        label = process_image(data_dir+label, shape, Image.NEAREST)
        image -= IMG_MEAN
        image = image / 255. if norm else image
        dataset['X'][index], dataset['Y'][index] = image, label
    dataset.close()
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def print_picture(self):
        #????
        im = Image.open(self.img)
        #?????????
        im = im.resize((self.width,self.heigth),Image.NEAREST)
        for i in range(self.heigth):
            for j in range(self.width):
                self.txt += self.get_char(*im.getpixel((j,i)))
                self.txt += '\r\n'
        print self.txt
项目:pcbot    作者:pckv    | 项目源码 | 文件源码
def rotate(message: discord.Message, image_arg: image, degrees: int, *options, extension: str.lower=None):
    """ Rotate an image clockwise using the given degrees. """
    if extension:
        image_arg.set_extension(extension)

    # Rotate and upload the image
    image_arg.modify(Image.Image.rotate, -degrees, Image.NEAREST if "-nearest" in options else Image.BICUBIC,
                     expand=True)
    await send_image(message, image_arg)
项目:pcbot    作者:pckv    | 项目源码 | 文件源码
def resize_sprite(sprite, factor: float):
    """ Resize a sprite (string of bytes / rb). """
    image = Image.open(BytesIO(sprite))

    # Resize with the scaled proportions
    width, height = image.size
    width, height = int(width * factor), int(height * factor)
    image = image.resize((width, height), Image.NEAREST)

    # Return the byte-like object
    return utils.convert_image_object(image)
项目:cozmo    作者:yp7y-stu    | 项目源码 | 文件源码
def run(sdk_conn):
    '''The run method runs once Cozmo is connected.'''

    robot = sdk_conn.wait_for_robot()

    get_in_position(robot)

    # load some images and convert them for display cozmo's face
    image_settings = [("images/cozmosdk.png", Image.BICUBIC),
                      ("images/hello_world.png", Image.NEAREST)]
    face_images = []
    for image_name, resampling_mode in image_settings:
        image = Image.open(image_name)

        # resize to fit on Cozmo's face screen
        resized_image = image.resize(cozmo.oled_face.dimensions(), resampling_mode)

        # convert the image to the format used by the oled screen
        face_image = cozmo.oled_face.convert_image_to_screen_data(resized_image,
                                                                 invert_image=True)
        face_images.append(face_image)

    # display each image on Cozmo's face for duration_s seconds (Note: this
    # is clamped at 30 seconds max within the engine to prevent burn-in)
    # repeat this num_loops times

    num_loops = 10
    duration_s = 2.0

    print("Press CTRL-C to quit (or wait %s seconds to complete)" % int(num_loops*duration_s) )

    for _ in range(num_loops):
        for image in face_images:
            robot.display_oled_face_image(image, duration_s * 1000.0)
            time.sleep(duration_s)
项目:cozmo    作者:yp7y-stu    | 项目源码 | 文件源码
def display_image_file_on_face(self, image_name):
        # load image and convert it for display on cozmo's face
        image = Image.open(image_name)

        # resize to fit on Cozmo's face screen
        resized_image = image.resize(cozmo.oled_face.dimensions(), Image.NEAREST)

        # convert the image to the format used by the oled screen
        face_image = cozmo.oled_face.convert_image_to_screen_data(resized_image,
                                                                  invert_image=True)

        # display image for 5 seconds
        self.display_oled_face_image(face_image, 5000.0)
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def pixelate(self, ctx, image_source: converters.Image, size: int = 15):
        """Pixelates something."""
        if size < 5:
            await ctx.send('The minimum size is 5.')
        size = min(size, 25)
        async with ctx.typing():
            im: Image = await download_image(ctx.bot.session, image_source)
            original_size = im.size
            im = im.resize((size, size), Image.NEAREST)
            im = im.resize(original_size, Image.NEAREST)
            await export_image(ctx, im, 'pixelated.png')
            im.close()
项目:tensorflow-layer-library    作者:bioinf-jku    | 项目源码 | 文件源码
def zoom_into_image(image: Image, zoom_factor: float, left_lower_corner: tuple = (0, 0), resample: int = Image.NEAREST):
    """Zoom into area of image (i.e. crop to area at position left_lower_corner and rescale area to original image size)

    Parameters
    -------
    image : PIL.Image
        PIL image

    zoom_factor : float
        Zoom into image with a factor zoom_factor >= 1.

    left_lower_corner: tuple
        Tuple with position of left lower corner of area to be zoomed into as (horizontal_pos, vertical_pos)

    resample: int
        Resampling filter to be used by PIL resize
    """
    if zoom_factor < 1.:
        raise ValueError("zoom_factor has to be >= 1. but is {}".format(zoom_factor))
    elif zoom_factor == 1.:
        return image

    full_size = image.size
    zoom_area_shape = [np.round(size / zoom_factor).astype(np.int) for size in full_size]
    crop_box = (left_lower_corner[0], left_lower_corner[1],
                left_lower_corner[0] + zoom_area_shape[0], left_lower_corner[1] + zoom_area_shape[1])
    zoom_area = image.crop(crop_box)  # Error in PIL documentation: crop_box is actually (left, lower, right, upper)!!!
    zoom_area = zoom_area.resize(full_size, resample=resample)

    return zoom_area
项目:tensorflow-layer-library    作者:bioinf-jku    | 项目源码 | 文件源码
def per_image(self, img):
        resample = {
            'nearest' : Image.NEAREST,
            'bilinear' : Image.BILINEAR,
            'bicubic' : Image.BICUBIC,
            'lanczos' : Image.LANCZOS}[self.resample]

        lower_left = [p * (s / self.factor) for p, s in zip(self.position, img.size)]
        return zoom_into_image(img, self.factor, tuple(lower_left), resample=resample)
项目:tensorflow-layer-library    作者:bioinf-jku    | 项目源码 | 文件源码
def zoom_into_image(image: Image, zoom_factor: float, left_lower_corner: tuple = (0, 0), resample: int = Image.NEAREST):
    """Zoom into area of image (i.e. crop to area at position left_lower_corner and rescale area to original image size)

    Parameters
    -------
    image : PIL.Image
        PIL image

    zoom_factor : float
        Zoom into image with a factor zoom_factor >= 1.

    left_lower_corner: tuple
        Tuple with position of left lower corner of area to be zoomed into as (horizontal_pos, vertical_pos)

    resample: int
        Resampling filter to be used by PIL resize
    """
    if zoom_factor < 1.:
        raise ValueError("zoom_factor has to be >= 1. but is {}".format(zoom_factor))
    elif zoom_factor == 1.:
        return image

    full_size = image.size
    zoom_area_shape = [np.round(size / zoom_factor).astype(np.int) for size in full_size]
    crop_box = (left_lower_corner[0], left_lower_corner[1],
                left_lower_corner[0] + zoom_area_shape[0], left_lower_corner[1] + zoom_area_shape[1])
    zoom_area = image.crop(crop_box)  # Error in PIL documentation: crop_box is actually (left, lower, right, upper)!!!
    zoom_area = zoom_area.resize(full_size, resample=resample)

    return zoom_area
项目:cozmo-python-sdk    作者:anki    | 项目源码 | 文件源码
def cozmo_program(robot: cozmo.robot.Robot):
    get_in_position(robot)

    # load some images and convert them for display cozmo's face
    image_settings = [("../../face_images/cozmosdk.png", Image.BICUBIC),
                      ("../../face_images/hello_world.png", Image.NEAREST)]
    face_images = []
    for image_name, resampling_mode in image_settings:
        image = Image.open(image_name)

        # resize to fit on Cozmo's face screen
        resized_image = image.resize(cozmo.oled_face.dimensions(), resampling_mode)

        # convert the image to the format used by the oled screen
        face_image = cozmo.oled_face.convert_image_to_screen_data(resized_image,
                                                                 invert_image=True)
        face_images.append(face_image)

    # display each image on Cozmo's face for duration_s seconds (Note: this
    # is clamped at 30 seconds max within the engine to prevent burn-in)
    # repeat this num_loops times

    num_loops = 10
    duration_s = 2.0

    print("Press CTRL-C to quit (or wait %s seconds to complete)" % int(num_loops*duration_s) )

    for _ in range(num_loops):
        for image in face_images:
            robot.display_oled_face_image(image, duration_s * 1000.0)
            time.sleep(duration_s)


# Cozmo is moved off his charger contacts by default at the start of any program.
# This is because not all motor movement is possible whilst drawing current from
# the charger. In cases where motor movement is not required, such as this example
# we can specify that Cozmo can stay on his charger at the start:
项目:cozmo-python-sdk    作者:anki    | 项目源码 | 文件源码
def display_image_file_on_face(self, image_name):
        # load image and convert it for display on cozmo's face
        image = Image.open(image_name)

        # resize to fit on Cozmo's face screen
        resized_image = image.resize(cozmo.oled_face.dimensions(), Image.NEAREST)

        # convert the image to the format used by the oled screen
        face_image = cozmo.oled_face.convert_image_to_screen_data(resized_image,
                                                                  invert_image=True)

        # display image for 5 seconds
        self.display_oled_face_image(face_image, 5000.0)
项目:pytorch-semantic-segmentation    作者:ZijunDeng    | 项目源码 | 文件源码
def __call__(self, img, mask):
        assert img.size == mask.size
        return img.resize(self.size, Image.BILINEAR), mask.resize(self.size, Image.NEAREST)
项目:pytorch-semantic-segmentation    作者:ZijunDeng    | 项目源码 | 文件源码
def __call__(self, img, mask):
        assert img.size == mask.size
        w, h = img.size
        if (w >= h and w == self.size) or (h >= w and h == self.size):
            return img, mask
        if w > h:
            ow = self.size
            oh = int(self.size * h / w)
            return img.resize((ow, oh), Image.BILINEAR), mask.resize((ow, oh), Image.NEAREST)
        else:
            oh = self.size
            ow = int(self.size * w / h)
            return img.resize((ow, oh), Image.BILINEAR), mask.resize((ow, oh), Image.NEAREST)