Python Image 模块,BICUBIC 实例源码

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

项目:blog    作者:benhoff    | 项目源码 | 文件源码
def ScaleRotateTranslate(image, angle, center = None, new_center = None, scale = None, resample=Image.BICUBIC):
  if (scale is None) and (center is None):
    return image.rotate(angle=angle, resample=resample)
  nx,ny = x,y = center
  sx=sy=1.0
  if new_center:
    (nx,ny) = new_center
  if scale:
    (sx,sy) = (scale, scale)
  cosine = math.cos(angle)
  sine = math.sin(angle)
  a = cosine/sx
  b = sine/sx
  c = x-nx*a-ny*b
  d = -sine/sy
  e = cosine/sy
  f = y-nx*d-ny*e
  return image.transform(image.size, Image.AFFINE, (a,b,c,d,e,f), resample=resample)
项目:text-renderer    作者:cjnolet    | 项目源码 | 文件源码
def apply_perspective_surf(self, surf):
        self.invert_surface(surf)
        data = pygame.image.tostring(surf, 'RGBA')
        img = Image.fromstring('RGBA', surf.get_size(), data)
        img = img.transform(img.size, self.affinestate.proj_type,
            self.affinestate.sample_transformation(img.size),
            Image.BICUBIC)
        img = img.transform(img.size, self.perspectivestate.proj_type,
            self.perspectivestate.sample_transformation(img.size),
            Image.BICUBIC)
        im = n.array(img)
        # pyplot.imshow(im)
        # pyplot.show()
        surf = pygame.surfarray.make_surface(im[...,0:3].swapaxes(0,1))
        self.invert_surface(surf)
        return surf
项目:flickrpy    作者:khaxis    | 项目源码 | 文件源码
def create_wallpaper(screen, urls, size=(100, 100), randomise=False):
    if randomise:
        random.shuffle(urls)

    wallpaper = Image.new("RGB", screen, "blue")

    width = int(math.ceil(float(screen[0]) / size[0]))
    height = int(math.ceil(float(screen[1]) / size[1]))

    offset = [0,0]
    for i in xrange(height):
        y = size[1] * i
        for j in xrange(width):
            x = size[0] * j
            photo = load_photo(urls.pop())
            if photo.size != size:
                photo = photo.resize(size, Image.BICUBIC)
            wallpaper.paste(photo, (x, y))
            del photo
    return wallpaper
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
def copy_image_files_pil(self):
        """Copy images using the PIL.
        The method tries to read and write the files with the PIL,
        converting the format and resizing the image if necessary/possible.
        """
        ensuredir(path.join(self.outdir, self.imagedir))
        for src in self.app.status_iterator(self.images, 'copying images... ',
                                            brown, len(self.images)):
            dest = self.images[src]
            try:
                img = Image.open(path.join(self.srcdir, src))
            except IOError:
                if not self.is_vector_graphics(src):
                    self.warn('cannot read image file %r: copying it instead' %
                              (path.join(self.srcdir, src), ))
                try:
                    copyfile(path.join(self.srcdir, src),
                             path.join(self.outdir, self.imagedir, dest))
                except (IOError, OSError) as err:
                    self.warn('cannot copy image file %r: %s' %
                              (path.join(self.srcdir, src), err))
                continue
            if self.config.epub_fix_images:
                if img.mode in ('P',):
                    # See PIL documentation for Image.convert()
                    img = img.convert()
            if self.config.epub_max_image_width > 0:
                (width, height) = img.size
                nw = self.config.epub_max_image_width
                if width > nw:
                    nh = (height * nw) / width
                    img = img.resize((nw, nh), Image.BICUBIC)
            try:
                img.save(path.join(self.outdir, self.imagedir, dest))
            except (IOError, OSError) as err:
                self.warn('cannot write image file %r: %s' %
                          (path.join(self.srcdir, src), err))
项目:nvda-ocr    作者:nvaccess    | 项目源码 | 文件源码
def script_ocrNavigatorObject(self, gesture):
        nav = api.getNavigatorObject()
        left, top, width, height = nav.location
        img = ImageGrab.grab(bbox=(left, top, left + width, top + height))
        # Tesseract copes better if we convert to black and white...
        img = img.convert(mode='L')
        # and increase the size.
        img = img.resize((width * IMAGE_RESIZE_FACTOR, height * IMAGE_RESIZE_FACTOR), Image.BICUBIC)
        baseFile = os.path.join(tempfile.gettempdir(), "nvda_ocr")
        try:
            imgFile = baseFile + ".bmp"
            img.save(imgFile)

            ui.message(_("Running OCR"))
            lang = getConfig()['language']
            # Hide the Tesseract window.
            si = subprocess.STARTUPINFO()
            si.dwFlags = subprocess.STARTF_USESHOWWINDOW
            si.wShowWindow = subprocess.SW_HIDE
            subprocess.check_call((TESSERACT_EXE, imgFile, baseFile, "-l", lang, "hocr"),
                startupinfo=si)
        finally:
            try:
                os.remove(imgFile)
            except OSError:
                pass
        try:
            hocrFile = baseFile + ".html"

            parser = HocrParser(file(hocrFile).read(),
                left, top)
        finally:
            try:
                os.remove(hocrFile)
            except OSError:
                pass

        # Let the user review the OCR output.
        nav.makeTextInfo = lambda position: OcrTextInfo(nav, position, parser)
        api.setReviewPosition(nav.makeTextInfo(textInfos.POSITION_FIRST))
        ui.message(_("Done"))
项目:text-renderer    作者:cjnolet    | 项目源码 | 文件源码
def apply_perspective_arr(self, arr, affstate, perstate, filtering=Image.BICUBIC):
        img = Image.fromarray(arr)
        img = img.transform(img.size, self.affinestate.proj_type,
            affstate,
            filtering)
        img = img.transform(img.size, self.perspectivestate.proj_type,
            perstate,
            filtering)
        arr = n.array(img)
        return arr
项目:jiango    作者:yefei    | 项目源码 | 文件源码
def render(self, stream, value):
        im = self.im.copy()
        im2 = self.im.copy()
        x = 0
        r_i = sum(ord(c) for c in value)  # ????????????????
        for c in value:
            fgimg = Image.new('RGBA', self.size, self.font_color)
            charimg = Image.new('L', self.font.getsize(c), '#000000')

            draw = ImageDraw.Draw(charimg)
            draw.text((0, 0), c, font=self.font, fill='#ffffff')

            r = (int(time()) / 1000 + ord(c) + r_i) % 40 - 20  # ???????????????
            charimg = charimg.rotate(r, expand=1, resample=Image.BICUBIC)
            charimg = charimg.crop(charimg.getbbox())

            maskimg = Image.new('L', self.size)
            y = (im2.size[1] - charimg.size[1]) / 2
            maskimg.paste(charimg, (x, y, charimg.size[0] + x, charimg.size[1] + y))

            im2 = Image.composite(fgimg, im2, maskimg)
            x += charimg.size[0] - 5  # - X???

        # ??????? x ??
        center = (im.size[0] - x) / 2
        im.paste(im2, (center, 0, im2.size[0]+center, im2.size[1]))

        im.save(stream, self.image_type)
项目:bolero    作者:rock-learning    | 项目源码 | 文件源码
def scale_image(in_fname, out_fname, max_width, max_height):
    """Scales an image with the same aspect ratio centered in an
       image with a given max_width and max_height
       if in_fname == out_fname the image can only be scaled down
    """
    # local import to avoid testing dependency on PIL:
    try:
        from PIL import Image
    except ImportError:
        import Image
    img = Image.open(in_fname)
    width_in, height_in = img.size
    scale_w = max_width / float(width_in)
    scale_h = max_height / float(height_in)

    if height_in * scale_w <= max_height:
        scale = scale_w
    else:
        scale = scale_h

    if scale >= 1.0 and in_fname == out_fname:
        return

    width_sc = int(round(scale * width_in))
    height_sc = int(round(scale * height_in))

    # resize the image using resize; if using .thumbnail and the image is
    # already smaller than max_width, max_height, then this won't scale up
    # at all (maybe could be an option someday...)
    img = img.resize((width_sc, height_sc), Image.BICUBIC)
    # img.thumbnail((width_sc, height_sc), Image.BICUBIC)
    # width_sc, height_sc = img.size  # necessary if using thumbnail

    # insert centered
    thumb = Image.new('RGB', (max_width, max_height), (255, 255, 255))
    pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)
    thumb.paste(img, pos_insert)

    thumb.save(out_fname)
    # Use optipng to perform lossless compression on the resized image if
    # software is installed
    if os.environ.get('SKLEARN_DOC_OPTIPNG', False):
        try:
            subprocess.call(["optipng", "-quiet", "-o", "9", out_fname])
        except Exception:
            logger.warning(
                'Install optipng to reduce the size of the generated images')
项目:mlstudy_week7    作者:ByungKeon-Ko    | 项目源码 | 文件源码
def create_ns (tmp_imgpath, cnt_ns ) :
    global pyramids

    tmp_img = Image.open("%s/%s" %(coco_path, tmp_imgpath), 'r' )
    pyramids = list( pyramid_gaussian( tmp_img, downscale=math.sqrt(2) ) )

    for i in range ( len(pyramids) ):
        if min( pyramids[i].shape[0], pyramids[i].shape[1] ) < MinFace :
            del pyramids[i:]
            break

    # for j in range(4) :
    for j in range(36) :
        # creating random index
        img_index = random.randint(0, len(pyramids)-1 )
        tmp_patch_num = ( pyramids[img_index].shape[0] - 12 + 1) * ( pyramids[img_index].shape[1] - 12 + 1)
        rand_index = random.randint(0, tmp_patch_num)

        # x, y position decoding
        row_max = pyramids[img_index].shape[0]
        col_max = pyramids[img_index].shape[1]
        row = 0
        col = rand_index

        while ( col >= col_max - 12 +1 ) :
            row = row + 1
            col = col - (col_max-12+1)

        flag = 0
        # Rejecting Black and White image
        tmp_ns = pyramids[img_index][row:row+12, col:col+12]
        if not len(tmp_ns.shape)==3 :
            print " Gray Image. Skip "
            return 0

        # Rejecting Positive Samples
        scale_factor = math.sqrt(2)**img_index

        tmp_ns = pyramids[img_index][row:row+12, col:col+12]
        tmp_ns = Image.fromarray((tmp_ns*255.0).astype(np.uint8) )
        # tmp_ns = tmp_ns.resize( (12,12), Image.BICUBIC )
        tmp_ns = tmp_ns.resize( (12,12), Image.BILINEAR )
        tmp_ns.save("%s/ns-%s.jpg" %(ns_path, cnt_ns+j) )

    return 1

# -----------------------------------------