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

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

项目:Roomba980-Python    作者:NickWaterton    | 项目源码 | 文件源码
def ScaleRotateTranslate(self, image, angle, center=None, new_center=None,
                             scale=None, expand=False):
        '''
        experimental - not used yet
        '''
        if center is None:
            return image.rotate(angle, expand)
        angle = -angle / 180.0 * math.pi
        nx, ny = x, y = center
        if new_center != center:
            (nx, ny) = new_center
        sx = sy = 1.0
        if scale:
            (sx, sy) = 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=Image.BICUBIC)
项目:Roomba980-Python    作者:NickWaterton    | 项目源码 | 文件源码
def ScaleRotateTranslate(self, image, angle, center=None, new_center=None,
                             scale=None, expand=False):
        '''
        experimental - not used yet
        '''
        if center is None:
            return image.rotate(angle, expand)
        angle = -angle / 180.0 * math.pi
        nx, ny = x, y = center
        if new_center != center:
            (nx, ny) = new_center
        sx = sy = 1.0
        if scale:
            (sx, sy) = 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=Image.BICUBIC)
项目:Imagyn    作者:zevisert    | 项目源码 | 文件源码
def skew_image(img, angle):
    """
    Skew image using some math
    :param img: PIL image object
    :param angle: Angle in radians (function doesn't do well outside the range -1 -> 1, but still works)
    :return: PIL image object
    """
    width, height = img.size
    # Get the width that is to be added to the image based on the angle of skew
    xshift = tan(abs(angle)) * height
    new_width = width + int(xshift)

    if new_width < 0:
        return img

    # Apply transform
    img = img.transform(
        (new_width, height),
        Image.AFFINE,
        (1, angle, -xshift if angle > 0 else 0, 0, 1, 0),
        Image.BICUBIC
    )

    return img
项目:QR-Replace    作者:Metruption    | 项目源码 | 文件源码
def warpImage(background, image, parallelogram):
    '''
    @params:
        background is unchanged image
        image is image to be warped
        parallelogram is the coordinates to warp the image to, starting at upper
            left and going clockwise
    returns a new image that is the composition of background and image
        after image has been warped
    '''
    mapped = np.array([[parallelogram[0].x, parallelogram[1].x, parallelogram[2].x],
    [parallelogram[0].y, parallelogram[1].y, parallelogram[2].y], [1,1,1]])

    width, height = image.size
    original = np.array([[0, width, width],[0, 0, height]])

    #solve for affine matrix
    solution = np.dot(original, inv(mapped))
    #unroll matrix into a sequence
    affine = (solution[0][0], solution[0][1], solution[0][2], solution[1][0], solution[1][1], solution[1][2])
    transformed = image.transform(background.size, Image.AFFINE, affine)
    white = Image.new("RGBA", (width, height), "white")
    transformedMask = white.transform(background.size, Image.AFFINE, affine)
    background.paste(transformed, (0,0), transformedMask)
    return background
项目:CNN-Glasses-Remover    作者:JubilantJerry    | 项目源码 | 文件源码
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)
项目:emojiGenerator    作者:jiuya    | 项目源码 | 文件源码
def getEmoji(self):
        img = Image.new("RGBA",self.imageSize,self.backColor)
        draw = ImageDraw.Draw(img)
        l = len(self.textList)

        for i in range(0,l):
            img_str = Image.new("RGBA",(len(self.textList[i])*128,128),self.backColor)
            draw = ImageDraw.Draw(img_str)
            (size,x0,y0,x1,y1) = self.cutEffectiveRange(self.textList[i],len(self.textList[i])*64,int(128/l))
            #(size,x0,y0,x1,y1) = self.cutEffectiveRange(self.textList[i],256,128/l)
            font = self.getFont(size)
            draw.text((x0,y0), self.textList[i], fill=self.fontColor, font=font)
            img_str.crop((0,0,x1,y1))
            if x1 > 128:
                img_str = img_str.transform(img_str.size,Image.AFFINE,(x1/128.0,0,0,0,1,0),Image.BICUBIC)
                image_paste_x = 0
            else:
                image_paste_x = int((128-x1)/2)
            if l != 1:
                img.paste(img_str,(image_paste_x,int((128/l)*i)))
            else:
                img.paste(img_str,(image_paste_x,int((128-y1)/2)))
        return img
项目:Seg-with-SPN    作者:JingchunCheng    | 项目源码 | 文件源码
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, rotation, trans_w, trans_h, 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,0,trans_w,0,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_
项目:Seg-with-SPN    作者:JingchunCheng    | 项目源码 | 文件源码
def load_label_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 {}'.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,img_H),Image.AFFINE,(1,0,trans_w,0,1,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
项目:Seg-with-SPN    作者:JingchunCheng    | 项目源码 | 文件源码
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 {}'.format(idx)
       print >> sys.stderr, 'scale: {}; rotation: {}; translation: ({},{}); flip: {}.'.format(scale, rotation, trans_w, trans_h, flip)

       im    = Image.open('{}/{}'.format(self.davis_dir, idx))
       im    = im.resize((img_W,img_H))
       im    = im.transform((img_W,img_H),Image.AFFINE,(1,0,trans_w,0,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_
项目:Seg-with-SPN    作者:JingchunCheng    | 项目源码 | 文件源码
def load_label_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 {}'.format(idx)
#        print >> sys.stderr, 'scale: {}; rotation: {}; translation: ({},{}); flip: {}.'.format(scale, rotation, trans_w, trans_h, flip)

        im    = Image.open('{}/{}'.format(self.davis_dir, idx))
        im    = im.resize((img_W,img_H))
        im    = im.transform((img_W,img_H),Image.AFFINE,(1,0,trans_w,0,1,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
项目:Seg-with-SPN    作者:JingchunCheng    | 项目源码 | 文件源码
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, rotation, trans_w, trans_h, 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,0,trans_w,0,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_
项目:web_develop    作者:dongweiming    | 项目源码 | 文件源码
def affine(cls, old_paste, w, h, a):
        assert old_paste.is_image

        img_size = (int(w), int(h))
        img = Image.open(old_paste.path).transform(
            img_size, Image.AFFINE, a, Image.BILINEAR)

        return cls.create_by_img(img, old_paste.filename, old_paste.mimetype)
项目:ted-editor    作者:tarnheld    | 项目源码 | 文件源码
def adjustImg(self):
        if self.img:
            xf = self.canvas.xform()
            xf = deepcopy(xf)
            xf = la.inverse(xf)

            # canvas coordinate of image origin
            ox, oy = self.canvas.canvasxy(self.imgbbox[0], self.imgbbox[1])
            fx, fy = self.canvas.canvasxy(self.imgbbox[2], self.imgbbox[3])
            cw, ch = self.canvas.winfo_width(), self.canvas.winfo_height()  # max image width,height
            bx, by = self.canvas.canvasxy(0, 0)
            ex, ey = self.canvas.canvasxy(cw, ch)

            cbx, cby = self.canvas.canvasx(0), self.canvas.canvasy(0)
            cex, cey = self.canvas.canvasx(cw), self.canvas.canvasy(ch)
            cox, coy = self.canvas.canvasx(self.imgbbox[0]), self.canvas.canvasy(self.imgbbox[1])
            cfx, cfy = self.canvas.canvasx(self.imgbbox[2]), self.canvas.canvasy(self.imgbbox[3])

            ix = bx
            iy = by
            iw = cw
            ih = ch

            # print((ox,oy),(fx,fy),(bx,by),(ex,ey))
            # print((ix,iy),(iw,ih))

            # scale image contents, max size of cw,ch make sure to not overblow image size
            # self.simg = self.img.transform((iw,ih),Image.AFFINE,data=(xf[0][0],xf[0][1],xf[0][3],xf[1][0],xf[1][1],xf[1][3]))
            self.simg = self.img.transform((iw, ih), Image.AFFINE,
                                           data=(xf[0][0], xf[0][1], ix, xf[1][0], xf[1][1], iy))
            self.canvas.coords(self.imgcid, ix, iy)  # adjust image origin

            self.pimg = ImageTk.PhotoImage(self.simg)
            self.canvas.itemconfig(self.imgcid, image=self.pimg)  # set new image
            self.canvas.tag_lower(self.imgcid, "segment")  # just below segments
            # sys.stdout.flush()
项目:ted-editor    作者:tarnheld    | 项目源码 | 文件源码
def onWheel(self, ev):
    cx,cy = self.canvas.canvasxy(ev.x,ev.y)

    sf = 1.1
    if (ev.delta < 0): sf = 1/sf

    # scale all objects on canvas
    self.canvas.zoom(cx, cy, sf)

    if self.img:
      imgsc = tuple(int(sf * c) for c in  self.simg.size)
      ox,oy = self.canvas.canvasxy(0,0)
      cw,ch = self.canvas.winfo_reqwidth(),self.canvas.winfo_reqheight()
      cow,coh = self.canvas.canvasxy(cw,ch)

      if imgsc[0] > cw and imgsc[1] > ch:
        isz = (cw,ch)
      else:
        isz = imgsc

      xf = self.canvas.xform()
      xf = deepcopy(xf)

      xf = inverse(xf)
      #self.simg = self.img.transform(self.img.size,Image.AFFINE,data=(xf[0][0],xf[0][1],xf[0][3],xf[1][0],xf[1][1],xf[1][3]))
      self.simg = self.img.transform(imgsc,Image.AFFINE,data=(xf[0][0],0,0,0,xf[1][1],0))

      self.pimg = ImageTk.PhotoImage(self.simg)
      #self.canvas.itemconfig(self.imgcid, image = self.pimg)
      x,y = self.canvas.coords(self.imgcid)
      print(x,y,self.img.size,ox,oy,cow,coh)
      if self.imgcid:
        self.canvas.delete(self.imgcid)
      self.imgcid = self.canvas.create_image(0, 0, image=self.pimg, anchor=tk.NW)
      sys.stdout.flush()
项目:planet-pytorch    作者:kefth    | 项目源码 | 文件源码
def __call__(self, img):
        """
        Args:
            img (PIL.Image): Image to be translated.
        Returns:
            PIL.Image: Randomly translated image.
        """
        if np.random.random() < 0.5:
            hshift = np.random.randint(-self.max_hshift,self.max_hshift)
            vshift = np.random.randint(-self.max_vshift,self.max_vshift)
            return img.transform(img.size, Image.AFFINE, (1, 0, hshift, 0, 1, vshift))
        return img
项目:denet    作者:lachlants    | 项目源码 | 文件源码
def transform_sample(self, sample, rotate=0, scale=[1,1], shear=[0,0], offset=[0,0], mirror = False, bilinear=False):

        fname,im,meta = sample
        rot = numpy.matrix([[math.cos(rotate), math.sin(rotate)], [-math.sin(rotate), math.cos(rotate)]])
        scale = numpy.matrix([[1.0/scale[0], 0], [0, 1.0 / scale[1]]])
        shear_x = numpy.matrix([[1,shear[0]], [0,1]])
        shear_y = numpy.matrix([[1,0], [shear[1],1]])
        tr = rot*scale*shear_x*shear_y
        if self.get_data_type() == "image":

            mode = Image.BILINEAR if bilinear else Image.NEAREST
            center = (im.size[0]/2, im.size[1]/2)
            ox = center[0]-center[0]*tr[0,0]-center[1]*tr[0,1] - offset[0]
            oy = center[1]-center[0]*tr[1,0]-center[1]*tr[1,1] - offset[1]
            im = im.transform(im.size, Image.AFFINE, (tr[0,0],tr[0,1],ox,tr[1,0],tr[1,1],oy), resample=resample)
            if mirror:
                im = ImageOps.mirror(im)

        elif self.get_data_type() == "array":

            order = 1 if bilinear else 0
            center=(im.shape[1]/2, im.shape[2]/2)
            ox=center[0] - center[0]*tr[0,0] - center[1]*tr[0,1] - offset[0]
            oy=center[1] - center[0]*tr[1,0] - center[1]*tr[1,1] - offset[1]
            r = numpy.zeros_like(im)
            r[0,:,:] = scipy.ndimage.interpolation.affine_transform(im[0,:,:], tr[0:2,0:2], [ox,oy], order=order)
            r[1,:,:] = scipy.ndimage.interpolation.affine_transform(im[1,:,:], tr[0:2,0:2], [ox,oy], order=order)
            r[2,:,:] = scipy.ndimage.interpolation.affine_transform(im[2,:,:], tr[0:2,0:2], [ox,oy], order=order)

            if mirror:
                r = r[:,:,::-1]
            im = r

        return (fname, im, meta)

    #random affine distorted images (destructive)