Python Image.ANTIALIAS Examples

The following are 30 code examples of Image.ANTIALIAS(). 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 Image , or try the search function .
Example #1
Source File: Title.py    From NSC_BUILDER with MIT License 6 votes vote down vote up
def getResizedImage(self, filePath, width = None, height = None):
		if not width and not height:
			return filePath

		base, name = os.path.split(filePath)
		path = os.path.join(base, '.' + str(width) + 'x' + str(height) + '_' + name)

		if not os.path.isfile(path):
			os.makedirs(base, exist_ok=True)
			im = Image.open(filePath)
			ar = im.size[0] / im.size[1]
			if height == None:
				height = int(width / ar)
			elif width == None:
				width = int(height * ar)

			out = im.resize((width, height), Image.ANTIALIAS)
			out.save(path, quality=100)

		return path 
Example #2
Source File: preprocessing.py    From saliency-2016-cvpr with MIT License 6 votes vote down vote up
def loadiSUNTest():    
    NumSample = 2000
    names = loadNameListSUN(MAT_TEST_SUN,NumSample,'testing')
    Xt = np.zeros((NumSample, 3, 96, 96), dtype='float32')
    for i in range(NumSample):
        img = Image.open('/imatge/jpan/work/iSUN/images/'+names[i]+'.jpg')
        img = ImageOps.fit(img, (96, 96), Image.ANTIALIAS)
        img = np.asarray(img, dtype = 'float32') / 255.
        
        if(cmp(img.shape , (96,96,3)) == 0):
            img = img.transpose(2,0,1).reshape(3, 96, 96)
            Xt[i] = img
        else:
            print names[i]
            aux=to_rgb(img)
            aux = aux.transpose(2,0,1).reshape(3, 96, 96)
            Xt[i]=aux
            
    data_to_save = Xt
    f = file('data_iSUN_Test.cPickle', 'wb')
    pickle.dump(data_to_save, f, protocol=pickle.HIGHEST_PROTOCOL)
    f.close() 
Example #3
Source File: DataSetPrep.py    From 3D-IWGAN with MIT License 6 votes vote down vote up
def resize(): # for resizing images to 256 by 256  and zooming in on the objects 
	for s in wanted_classes: 
		files = glob('data/overlays/' + labels[s]+'/*') 
		for f in tqdm(files):
			images = glob(f+'/*')
			for im in images:
				# here I am maintianing the origional images and renaming them with a large_ prefix 
				actual = im
				new = f+'/orig_' + im.split('/')[-1]
				shutil.move(actual,new)
				im = Image.open(new)
				x,y = im.size
				diff = (x-y)/2
				im = im.crop((diff+100,100, x-diff-100, y-100)) # getting a square aspect ratio and zooming in on object by 100 pixels 
				im = ImageOps.fit(im, (256,256), Image.ANTIALIAS) # reshaping to 256 by 256 
				im.save(actual) 
Example #4
Source File: render.py    From seeing3d with MIT License 6 votes vote down vote up
def render_to_file(fname):
    alt_texture.clear()
    base.graphicsEngine.renderFrame()
    base.graphicsEngine.renderFrame()
    #base.graphicsEngine.extractTextureData(tex, base.win.getGsg())
    #tex = alt_buffer.getTexture()
    pnm = PNMImage()
    #base.win.getScreenshot(pnm)
    alt_texture.store(pnm)
    ss = StringStream()
    pnm.write(ss, 'pnm')
    sio = StringIO.StringIO(ss.getData())
    img = Image.open(sio)
    # poor man's antialiasing
    img = img.resize((WIDTH, HEIGHT), Image.ANTIALIAS)
    img.save(fname) 
Example #5
Source File: gen_rst.py    From tensorlib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    # 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 = width / float(width_in)
    scale_h = height / float(height_in)

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

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

    # resize the image
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

    # insert centered
    thumb = Image.new('RGB', (width, height), (255, 255, 255))
    pos_insert = ((width - width_sc) // 2, (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:
            warnings.warn('Install optipng to reduce the size of the generated images') 
Example #6
Source File: TestMyself_Multithreading.py    From MTCNN-VGG-face with MIT License 5 votes vote down vote up
def CropFace(image, eye_left, eye_right, offset_pct=(0.2, 0.2), dest_sz=(70, 70)):
        # calculate offsets in original image 计算在原始图像上的偏移。
        offset_h = math.floor(float(offset_pct[0]) * dest_sz[0])
        offset_v = math.floor(float(offset_pct[1]) * dest_sz[1])
        # get the direction  计算眼睛的方向。
        eye_direction = (eye_right.x - eye_left.x, eye_right.y - eye_left.y)
        # calc rotation angle in radians  计算旋转的方向弧度。
        rotation = -math.atan2(float(eye_direction[1]), float(eye_direction[0]))
        # distance between them  # 计算两眼之间的距离。
        dist = Distance(eye_left, eye_right)
        # calculate the reference eye-width    计算最后输出的图像两只眼睛之间的距离。
        reference = dest_sz[0] - 2.0 * offset_h
        # scale factor   # 计算尺度因子。
        scale = float(dist) / float(reference)
        # rotate original around the left eye  # 原图像绕着左眼的坐标旋转。
        eyeleft_yuanzu=(eye_left.x,eye_left.y)
        image = ScaleRotateTranslate(image, center=eyeleft_yuanzu, angle=rotation)
        # crop the rotated image  # 剪切
        # crop_xy = (eye_left.x - scale * offset_h, eye_left.y - scale * offset_v)  # 起点
        # crop_size = (dest_sz[0] * scale, dest_sz[1] * scale)  # 大小
        # image = image.crop(
        #     (int(crop_xy[0]), int(crop_xy[1]), int(crop_xy[0] + crop_size[0]), int(crop_xy[1] + crop_size[1])))
        # # resize it 重置大小
        # image = image.resize(dest_sz, Image.ANTIALIAS)
        # image.show()
        return image 
Example #7
Source File: GetAffinePic.py    From MTCNN-VGG-face with MIT License 5 votes vote down vote up
def CropFace(image, eye_left, eye_right, offset_pct=(0.2, 0.2), dest_sz=(70, 70)):
    # calculate offsets in original image 计算在原始图像上的偏移。
    offset_h = math.floor(float(offset_pct[0]) * dest_sz[0])
    offset_v = math.floor(float(offset_pct[1]) * dest_sz[1])
    # get the direction  计算眼睛的方向。
    eye_direction = (eye_right['x'] - eye_left['x'], eye_right['y'] - eye_left['y'])
    # calc rotation angle in radians  计算旋转的方向弧度。
    rotation = -math.atan2(float(eye_direction[1]), float(eye_direction[0]))
    # distance between them  # 计算两眼之间的距离。
    dist = Distance(eye_left, eye_right)
    # calculate the reference eye-width    计算最后输出的图像两只眼睛之间的距离。
    reference = dest_sz[0] - 2.0 * offset_h
    # scale factor   # 计算尺度因子。
    scale = float(dist) / float(reference)
    # rotate original around the left eye  # 原图像绕着左眼的坐标旋转。
    eyeleft_yuanzu = (eye_left['x'], eye_left['y'])
    image = ScaleRotateTranslate(image, center=eyeleft_yuanzu, angle=rotation)
    # crop the rotated image  # 剪切
    # crop_xy = (eye_left['x'] - scale * offset_h, eye_left['y'] - scale * offset_v)  # 起点
    # crop_size = (dest_sz[0] * scale, dest_sz[1] * scale)  # 大小
    # image = image.crop(
    #     (int(crop_xy[0]), int(crop_xy[1]), int(crop_xy[0] + crop_size[0]), int(crop_xy[1] + crop_size[1])))
    # # resize it 重置大小
    # image = image.resize(dest_sz, Image.ANTIALIAS)
    # image.show()
    return image 
Example #8
Source File: TestMyself_KNN.py    From MTCNN-VGG-face with MIT License 5 votes vote down vote up
def CropFace(image, eye_left, eye_right, offset_pct=(0.2, 0.2), dest_sz=(70, 70)):
        # calculate offsets in original image 计算在原始图像上的偏移。
        offset_h = math.floor(float(offset_pct[0]) * dest_sz[0])
        offset_v = math.floor(float(offset_pct[1]) * dest_sz[1])
        # get the direction  计算眼睛的方向。
        eye_direction = (eye_right.x - eye_left.x, eye_right.y - eye_left.y)
        # calc rotation angle in radians  计算旋转的方向弧度。
        rotation = -math.atan2(float(eye_direction[1]), float(eye_direction[0]))
        # distance between them  # 计算两眼之间的距离。
        dist = Distance(eye_left, eye_right)
        # calculate the reference eye-width    计算最后输出的图像两只眼睛之间的距离。
        reference = dest_sz[0] - 2.0 * offset_h
        # scale factor   # 计算尺度因子。
        scale = float(dist) / float(reference)
        # rotate original around the left eye  # 原图像绕着左眼的坐标旋转。
        eyeleft_yuanzu=(eye_left.x,eye_left.y)
        image = ScaleRotateTranslate(image, center=eyeleft_yuanzu, angle=rotation)
        # crop the rotated image  # 剪切
        # crop_xy = (eye_left.x - scale * offset_h, eye_left.y - scale * offset_v)  # 起点
        # crop_size = (dest_sz[0] * scale, dest_sz[1] * scale)  # 大小
        # image = image.crop(
        #     (int(crop_xy[0]), int(crop_xy[1]), int(crop_xy[0] + crop_size[0]), int(crop_xy[1] + crop_size[1])))
        # # resize it 重置大小
        # image = image.resize(dest_sz, Image.ANTIALIAS)
        # image.show()
        return image 
Example #9
Source File: TestMyselfWithMTCNN.py    From MTCNN-VGG-face with MIT License 5 votes vote down vote up
def CropFace(image, eye_left, eye_right, offset_pct=(0.2, 0.2), dest_sz=(70, 70)):
        # calculate offsets in original image 计算在原始图像上的偏移。
        offset_h = math.floor(float(offset_pct[0]) * dest_sz[0])
        offset_v = math.floor(float(offset_pct[1]) * dest_sz[1])
        # get the direction  计算眼睛的方向。
        eye_direction = (eye_right.x - eye_left.x, eye_right.y - eye_left.y)
        # calc rotation angle in radians  计算旋转的方向弧度。
        rotation = -math.atan2(float(eye_direction[1]), float(eye_direction[0]))
        # distance between them  # 计算两眼之间的距离。
        dist = Distance(eye_left, eye_right)
        # calculate the reference eye-width    计算最后输出的图像两只眼睛之间的距离。
        reference = dest_sz[0] - 2.0 * offset_h
        # scale factor   # 计算尺度因子。
        scale = float(dist) / float(reference)
        # rotate original around the left eye  # 原图像绕着左眼的坐标旋转。
        eyeleft_yuanzu=(eye_left.x,eye_left.y)
        image = ScaleRotateTranslate(image, center=eyeleft_yuanzu, angle=rotation)
        # crop the rotated image  # 剪切
        # crop_xy = (eye_left.x - scale * offset_h, eye_left.y - scale * offset_v)  # 起点
        # crop_size = (dest_sz[0] * scale, dest_sz[1] * scale)  # 大小
        # image = image.crop(
        #     (int(crop_xy[0]), int(crop_xy[1]), int(crop_xy[0] + crop_size[0]), int(crop_xy[1] + crop_size[1])))
        # # resize it 重置大小
        # image = image.resize(dest_sz, Image.ANTIALIAS)
        # image.show()
        return image 
Example #10
Source File: TestMyself_NEWSVM.py    From MTCNN-VGG-face with MIT License 5 votes vote down vote up
def CropFace(image, eye_left, eye_right, offset_pct=(0.2, 0.2), dest_sz=(70, 70)):
        # calculate offsets in original image 计算在原始图像上的偏移。
        offset_h = math.floor(float(offset_pct[0]) * dest_sz[0])
        offset_v = math.floor(float(offset_pct[1]) * dest_sz[1])
        # get the direction  计算眼睛的方向。
        eye_direction = (eye_right.x - eye_left.x, eye_right.y - eye_left.y)
        # calc rotation angle in radians  计算旋转的方向弧度。
        rotation = -math.atan2(float(eye_direction[1]), float(eye_direction[0]))
        # distance between them  # 计算两眼之间的距离。
        dist = Distance(eye_left, eye_right)
        # calculate the reference eye-width    计算最后输出的图像两只眼睛之间的距离。
        reference = dest_sz[0] - 2.0 * offset_h
        # scale factor   # 计算尺度因子。
        scale = float(dist) / float(reference)
        # rotate original around the left eye  # 原图像绕着左眼的坐标旋转。
        eyeleft_yuanzu=(eye_left.x,eye_left.y)
        image = ScaleRotateTranslate(image, center=eyeleft_yuanzu, angle=rotation)
        # crop the rotated image  # 剪切
        # crop_xy = (eye_left.x - scale * offset_h, eye_left.y - scale * offset_v)  # 起点
        # crop_size = (dest_sz[0] * scale, dest_sz[1] * scale)  # 大小
        # image = image.crop(
        #     (int(crop_xy[0]), int(crop_xy[1]), int(crop_xy[0] + crop_size[0]), int(crop_xy[1] + crop_size[1])))
        # # resize it 重置大小
        # image = image.resize(dest_sz, Image.ANTIALIAS)
        # image.show()
        return image 
Example #11
Source File: base.py    From webterminal with GNU General Public License v3.0 5 votes vote down vote up
def _img_resize(self, im, target, width, height, keepProportions = False, resizeByBiggerSide = True, destformat = None):
        """
        Resize image and return the new image.
        """
    
        s = im.size
        size_w = width
        size_h = height

        if keepProportions:
            orig_w, orig_h = s[0], s[1]
            
            #Resizing by biggest side
            if resizeByBiggerSide:
                if (orig_w > orig_h):
                    size_h = orig_h * width / orig_w
                    size_w = width
                else:
                    size_w = orig_w * height / orig_h
                    size_h = height
            elif orig_w > orig_h:
                size_w = orig_w * height / orig_h
                size_h = height
            else:
                size_h = orig_h * width / orig_w
                size_w = width

        resized = im.resize((int(size_w), int(size_h)), Image.ANTIALIAS)
        
        if target:
            self._saveimage(resized, target, destformat if destformat else im.format)
        
        return resized 
Example #12
Source File: gen_rst.py    From polylearn with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    # 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 = width / float(width_in)
    scale_h = height / float(height_in)

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

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

    # resize the image
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

    # insert centered
    thumb = Image.new('RGB', (width, height), (255, 255, 255))
    pos_insert = ((width - width_sc) // 2, (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:
            warnings.warn('Install optipng to reduce the size of the generated images') 
Example #13
Source File: gen_rst.py    From deeppy with MIT License 5 votes vote down vote up
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    # 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 = width / float(width_in)
    scale_h = height / float(height_in)

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

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

    # resize the image
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

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

    thumb.save(out_fname) 
Example #14
Source File: graphicalInterfaceSF.py    From music21-tools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def initializeName(self):
        self.newSize = [self.x, self.y]
        for i in range(self.totalPagesScore):
            numberLength = len(str(self.totalPagesScore))
            namePage = '%s%s.%s' % (str(self.scoreNameSong),
                                    str(i + 1).zfill(numberLength),
                                    self.format)
            self.listNamePages.append(namePage)
            pilPage = PILImage.open(namePage) # @UndefinedVariable
            if pilPage.mode != "RGB":
                pilPage = pilPage.convert("RGB")
            pilPage = self.cropBorder(pilPage)
            self.pagesScore.append(pilPage.resize(self.newSize, PILImage.ANTIALIAS)) # @UndefinedVariable
            self.phimage.append(PILImageTk.PhotoImage(self.pagesScore[i])) # @UndefinedVariable
        environLocal.printDebug("initializeName finished") 
Example #15
Source File: base.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def _img_resize(self, im, target, width, height, keepProportions = False, resizeByBiggerSide = True, destformat = None):
        """
        Resize image and return the new image.
        """
    
        s = im.size
        size_w = width
        size_h = height

        if keepProportions:
            orig_w, orig_h = s[0], s[1]
            
            #Resizing by biggest side
            if resizeByBiggerSide:
                if (orig_w > orig_h):
                    size_h = orig_h * width / orig_w
                    size_w = width
                else:
                    size_w = orig_w * height / orig_h
                    size_h = height
            elif orig_w > orig_h:
                size_w = orig_w * height / orig_h
                size_h = height
            else:
                size_h = orig_h * width / orig_w
                size_w = width

        resized = im.resize((size_w, size_h), Image.ANTIALIAS)
        
        if target:
            self._saveimage(resized, target, destformat if destformat else im.format)
        
        return resized 
Example #16
Source File: cleanup.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle(self, *args, **options):
        size = 128, 128
        logging.info("Building avatar thumbnails")
        for infile in glob("servo/uploads/avatars/*.jpg"):
            logging.info(infile)
            im = Image.open(infile)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(infile, "JPEG")

        logging.info("Cleaning up unused attachments")
        for infile in glob("servo/uploads/attachments/*"):
            fn = infile.decode('utf-8')
            fp = os.path.join("attachments", os.path.basename(fn))
            try:
                Attachment.objects.get(content=fp)
            except Attachment.DoesNotExist:
                os.remove(infile) 
Example #17
Source File: gen_rst.py    From artview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    img = Image.open(in_fname)
    width_in, height_in = img.size
    scale_w = width / float(width_in)
    scale_h = height / float(height_in)

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

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

    # resize the image
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

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

    thumb.save(out_fname) 
Example #18
Source File: demo.py    From saliency-2016-cvpr with MIT License 5 votes vote down vote up
def loadImage():
    xt = np.zeros((num_img, 3, 96, 96), dtype='float32')
    i = 0
    for file in glob.glob(url+"*.jpg"):   
        img = Image.open(file)  
        img = ImageOps.fit(img, (96, 96), Image.ANTIALIAS)
        img = np.asarray(img, dtype = 'float32') / 255.       
        if(cmp(img.shape , (96,96,3)) == 0):
            img = img.transpose(2,0,1).reshape(3, 96, 96)
            xt[i]=img
        else:
            aux=to_rgb(img)
            aux = aux.transpose(2,0,1).reshape(3, 96, 96)
            xt[i]=aux
        i = i + 1
        return xt 
Example #19
Source File: images_stub.py    From python-compat-runtime with Apache License 2.0 4 votes vote down vote up
def _Resize(self, image, transform):
    """Use PIL to resize the given image with the given transform.

    Args:
      image: PIL.Image.Image object to resize.
      transform: images_service_pb.Transform to use when resizing.

    Returns:
      PIL.Image.Image with transforms performed on it.

    Raises:
      ApplicationError: The resize data given was bad.
    """
    width = 0
    height = 0

    if transform.has_width():
      width = transform.width()
      if width < 0 or 4000 < width:
        raise apiproxy_errors.ApplicationError(
            images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)

    if transform.has_height():
      height = transform.height()
      if height < 0 or 4000 < height:
        raise apiproxy_errors.ApplicationError(
            images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)

    crop_to_fit = transform.crop_to_fit()
    allow_stretch = transform.allow_stretch()

    current_width, current_height = image.size
    new_width, new_height = self._CalculateNewDimensions(
        current_width, current_height, width, height, crop_to_fit,
        allow_stretch)
    new_image = image.resize((new_width, new_height), Image.ANTIALIAS)
    if crop_to_fit and (new_width > width or new_height > height):

      left = int((new_width - width) * transform.crop_offset_x())
      top = int((new_height - height) * transform.crop_offset_y())
      right = left + width
      bottom = top + height
      new_image = new_image.crop((left, top, right, bottom))

    return new_image 
Example #20
Source File: vis.py    From retrieval-2016-deepvision with MIT License 4 votes vote down vote up
def create_thumb(self,im):
    
        x = 800
        y = 800
        size = (y,x)
        image = Image.fromarray(im)
        
        image.thumbnail(size, Image.ANTIALIAS)
        background = Image.new('RGBA', size, "black")
        background.paste(image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
        
        return np.array(background)[:,:,0:3] 
Example #21
Source File: base.py    From adminset with GNU General Public License v2.0 4 votes vote down vote up
def tmb(self, hash_):
        """
        Create thumbnail for the required file ``hash_`` and return
        its name. It will raise an ``Exception`` on fail.
        """
        
        path = self.decode(hash_)
        stat = self.file(hash_)
        name = self._tmb_name(stat)
        
        if 'tmb' in stat and stat['tmb'] != 1:
            return stat['tmb']
        
        if not self._can_create_tmb(path, stat):
            raise PermissionDeniedError
        
        #copy the image to the thumbnail
        tmb  = self._join_path(self._options['tmbPath'], name)
        tmb_size = self._options['tmbSize']
        
        try:
            im = self._openimage(path)
            if im.mode == "CMYK":
                im = im.convert("RGB")
            s = im.size
        except:
            raise NotAnImageError
    
        # If image smaller or equal thumbnail size - just fitting to thumbnail square 
        if s[0] <= tmb_size and s[1]  <= tmb_size:
            self._img_square_fit(im, tmb, tmb_size, tmb_size, self._options['tmbBgColor'], 'png')
        elif self._options['tmbCrop']:
            #Resize and crop if image bigger than thumbnail
            if s[0] > tmb_size and s[1] > tmb_size:
                resized = self._img_resize(im, None, tmb_size, tmb_size, True, False, 'png')
                s = resized.size
                self._img_crop(resized, tmb, tmb_size, tmb_size, int((s[0] - tmb_size)/2), int((s[1] - tmb_size)/2), 'png')
            else:
                fit = self._img_square_fit(im, None, s[0] if s[0] > s[1] else s[1], s[0] if s[0] > s[1] else s[1], self._options['tmbBgColor'], 'png')
                self._img_crop(fit, tmb, tmb_size, tmb_size, 
                    int((s[0] - tmb_size)/2) if s[0] > tmb_size else 0,
                    int((s[1] - tmb_size)/2) if s[1] > tmb_size else 0, 'png')
        else:
            try:
                im.thumbnail((tmb_size, tmb_size), Image.ANTIALIAS)
                self._img_square_fit(im, tmb, tmb_size, tmb_size, self._options['tmbBgColor'], 'png' )
            except:
                self._unlink(tmb)
                raise

        if hasattr(im, 'fp') and im.fp:
            im.fp.close()

        self._clear_cached_stat(path)
        return name 
Example #22
Source File: gen_rst.py    From spectrum with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

    # 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:
            warnings.warn('Install optipng to reduce the size of the \
                          generated images') 
Example #23
Source File: preprocessing.py    From saliency-2016-cvpr with MIT License 4 votes vote down vote up
def loadiSUNVAL():
    NumSample = 926;
    X2 = np.zeros((NumSample, 3, 96, 96), dtype='float32')
    y2 = np.zeros((NumSample,48*48), dtype='float32')
    names = loadNameListSUN(MAT_VAL_SUN,NumSample,'validation')
    for i in range(NumSample):
        img = Image.open('/imatge/jpan/work/iSUN/images/'+names[i]+'.jpg')
        img = ImageOps.fit(img, (96, 96), Image.ANTIALIAS)
        img = np.asarray(img, dtype = 'float32') /255.

        if(cmp(img.shape , (96,96,3)) == 0):
            img = img.transpose(2,0,1).reshape(3, 96, 96)
            X2[i] = img
        else:
            print names[i]
            aux=to_rgb(img)
            aux = aux.transpose(2,0,1).reshape(3, 96, 96)
            X2[i]=aux
            
        label = loadSaliencyMapSUN(names[i])
        label = misc.imresize(label,(48,48)) / 127.5
        label = label -1.
        y2[i] =  label.reshape(1,48*48)    
  
    data_to_save = (X2, y2)
    f = file('data_iSun_VAL.cPickle', 'wb')
    pickle.dump(data_to_save, f, protocol=pickle.HIGHEST_PROTOCOL)
    f.close() 
Example #24
Source File: preprocessing.py    From saliency-2016-cvpr with MIT License 4 votes vote down vote up
def loadSUN():
    NumSample = 6000;
    X1 = np.zeros((NumSample, 3, 96, 96), dtype='float32')
    y1 = np.zeros((NumSample,48*48), dtype='float32')

    names = loadNameListSUN(MAT_TRAIN_SUN,NumSample,'training')
    for i in range(NumSample):
        img = Image.open('/imatge/jpan/work/iSUN/images/'+names[i]+'.jpg')
        img = ImageOps.fit(img, (96, 96), Image.ANTIALIAS)
        img = np.asarray(img, dtype = 'float32') /255.

        if(cmp(img.shape , (96,96,3)) == 0):
            img = img.transpose(2,0,1).reshape(3, 96, 96)
            X1[i] = img
        else:
            print names[i]
            aux=to_rgb(img)
            aux = aux.transpose(2,0,1).reshape(3, 96, 96)
            X1[i]=aux
            
        label = loadSaliencyMapSUN(names[i])
        label = misc.imresize(label,(48,48)) / 127.5
        label = label -1.
        y1[i] =  label.reshape(1,48*48)  
  
    data_to_save = (X1, y1)
    f = file('data_iSun_T.cPickle', 'wb')
    pickle.dump(data_to_save, f, protocol=pickle.HIGHEST_PROTOCOL)
    f.close() 
Example #25
Source File: views.py    From dzhops with Apache License 2.0 4 votes vote down vote up
def imageResize(img, username):
    '''
    Image resize to 58 * 58;
    :param img:
    :return:
    '''
    try:
        standard_size = (58, 58)
        file_type = '.jpg'
        user_pic_list = [username, file_type]
        log.debug(str(user_pic_list))
        user_pic_str = ''.join(user_pic_list)
        log.debug('37')
        log.debug('user_pic_path: %s' % str(settings.STATICFILES_DIRS))
        user_pic_path = os.path.join(settings.STATICFILES_DIRS[0], 'img', user_pic_str)
        im = Image.open(img)
        im_new = im.resize(standard_size, Image.ANTIALIAS)
        im_new.save(user_pic_path, 'JPEG', quality=100)
        log.info('The user pic resize successed')
        try:
            all_static = settings.STATIC_ROOT
            all_static_url = os.path.join(all_static, 'img')
        except AttributeError, e:
            all_static_url = ''
            log.info('The config settings.py no STATIC_ROOT attribute')
        if all_static_url and os.path.exists(all_static_url):
            shutil.copy(user_pic_path, all_static_url)
            log.info('The user picture copy to all_static_url')
        else:
            log.debug('The all_static_url is None or do not exist') 
Example #26
Source File: base.py    From webterminal with GNU General Public License v3.0 4 votes vote down vote up
def tmb(self, hash_):
        """
        Create thumbnail for the required file ``hash_`` and return
        its name. It will raise an ``Exception`` on fail.
        """
        
        path = self.decode(hash_)
        stat = self.file(hash_)
        name = self._tmb_name(stat)
        
        if 'tmb' in stat and stat['tmb'] != 1:
            return stat['tmb']
        
        if not self._can_create_tmb(path, stat):
            raise PermissionDeniedError
        
        #copy the image to the thumbnail
        tmb  = self._join_path(self._options['tmbPath'], name)
        tmb_size = self._options['tmbSize']
        
        try:
            im = self._openimage(path)
            if im.mode == "CMYK":
                im = im.convert("RGB")
            s = im.size
        except:
            raise NotAnImageError
    
        # If image smaller or equal thumbnail size - just fitting to thumbnail square 
        if s[0] <= tmb_size and s[1]  <= tmb_size:
            self._img_square_fit(im, tmb, tmb_size, tmb_size, self._options['tmbBgColor'], 'png')
        elif self._options['tmbCrop']:
            #Resize and crop if image bigger than thumbnail
            if s[0] > tmb_size and s[1] > tmb_size:
                resized = self._img_resize(im, None, tmb_size, tmb_size, True, False, 'png')
                s = resized.size
                self._img_crop(resized, tmb, tmb_size, tmb_size, int((s[0] - tmb_size)/2), int((s[1] - tmb_size)/2), 'png')
            else:
                fit = self._img_square_fit(im, None, s[0] if s[0] > s[1] else s[1], s[0] if s[0] > s[1] else s[1], self._options['tmbBgColor'], 'png')
                self._img_crop(fit, tmb, tmb_size, tmb_size, 
                    int((s[0] - tmb_size)/2) if s[0] > tmb_size else 0,
                    int((s[1] - tmb_size)/2) if s[1] > tmb_size else 0, 'png')
        else:
            try:
                im.thumbnail((tmb_size, tmb_size), Image.ANTIALIAS)
                self._img_square_fit(im, tmb, tmb_size, tmb_size, self._options['tmbBgColor'], 'png' )
            except:
                self._unlink(tmb)
                raise

        if hasattr(im, 'fp') and im.fp:
            im.fp.close()

        self._clear_cached_stat(path)
        return name 
Example #27
Source File: cropall.py    From cropall with GNU General Public License v3.0 4 votes vote down vote up
def update_preview(self, widget):
		if self.item:
			#get a crop for the preview
			#box = tuple((int(round(v)) for v in widget.coords(self.item)))
			box = self.getRealBox()
			pbox = self.getPreviewBox()
			if fast_preview:
				preview = self.image.crop(pbox) # region of interest
			else:
				preview = self.imageOrig.crop(box) # region of interest

			#add black borders for correct aspect ratio
			#if preview.size[0] > 512:
			preview.thumbnail(self.image.size, Image.ANTIALIAS) #downscale to preview rez
			paspect = preview.size[0]/float(preview.size[1])
			aspect = self.image.size[0]/float(self.image.size[1])
			if paspect < aspect:
				bbox = (0, 0, int(preview.size[1] * aspect), preview.size[1])
			else:
				bbox = (0, 0, preview.size[0], int(preview.size[0] / aspect))
			preview = ImageOps.expand(preview, border=((bbox[2]-preview.size[0])//2, (bbox[3]-preview.size[1])//2))
			#preview = ImageOps.fit(preview, size=self.image.size, method=Image.ANTIALIAS, bleed=-10.0)

			#resize to preview rez (if too small)
			self.preview = preview.resize(self.image.size, Image.ANTIALIAS)
			self.previewPhoto = ImageTk.PhotoImage(self.preview)
			self.previewLabel.configure(image=self.previewPhoto)

			print str(box[2]-box[0])+"x"+str(box[3]-box[1])+"+"+str(box[0])+"+"+str(box[1]) 
Example #28
Source File: cropall.py    From cropall with GNU General Public License v3.0 4 votes vote down vote up
def load_imgfile(self, filename):
		self.currentName = filename
		fullFilename = os.path.join(self.inDir, filename)
		print "Loading " + fullFilename
		img = Image.open(fullFilename)

		self.imageOrig = img
		self.imageOrigSize = (img.size[0], img.size[1])
		print "Image is " + str(self.imageOrigSize[0]) + "x" + str(self.imageOrigSize[1])

		basewidth = 512
		wpercent = (basewidth/float(img.size[0]))
		hsize = int((float(img.size[1])*float(wpercent)))
		if fast_preview:
			#does NOT create a copy so self.imageOrig is the same as self.image
			img.thumbnail((basewidth,hsize), Image.NEAREST)
		else:
			if antialiase_original_preview:
				img = img.resize((basewidth,hsize), Image.ANTIALIAS)
			else:
				img = img.copy()
				img.thumbnail((basewidth,hsize), Image.NEAREST)
		self.image = img
		print "Resized preview"

		#self.geometry("1024x"+str(hsize + 100))
		self.configure(relief='flat', background='gray')

		self.imagePhoto = ImageTk.PhotoImage(self.image)
		self.imageLabel.configure(width=self.imagePhoto.width(), height=self.imagePhoto.height())
		self.imageLabel.create_image(0, 0, anchor=NW, image=self.imagePhoto)

		self.previewPhoto = ImageTk.PhotoImage(self.image)
		self.previewLabel.configure(image=self.previewPhoto)

		self.item = None

		self.verti_aux_item = None
		self.horiz_aux_item = None

		self.on_aspect_changed(None, None, None) #update aspect ratio with new image size

		#self.imageLabel.pack(side = "left", fill = "both", expand = "yes")
		#self.previewLabel.pack(side = "left", fill = "both", expand = "yes")
		#self.c.pack(side = "bottom", fill = "both", expand = "yes")

		#self.c.xview_moveto(0)
		#self.c.yview_moveto(0)
		#self.c.config(scrollregion=self.c.bbox('all')) 
Example #29
Source File: cropall.py    From cropall with GNU General Public License v3.0 4 votes vote down vote up
def clamp(x, a, b):
	return min(max(x, a), b)

# open a SPIDER image and convert to byte format
#im = Image.open(allImages[0])
#im = im.resize((250, 250), Image.ANTIALIAS)

#root = Tkinter.Tk()
# A root window for displaying objects

# Convert the Image object into a TkPhoto object
#tkimage = ImageTk.PhotoImage(im)

#Tkinter.Label(root, image=tkimage).pack()
# Put it in the display window 
Example #30
Source File: gen_rst.py    From tick with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    # 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 = width / float(width_in)
    scale_h = height / float(height_in)

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

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

    # resize the image
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

    # insert centered
    thumb = Image.new('RGB', (width, height), (255, 255, 255))
    pos_insert = ((width - width_sc) // 2, (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:
            warnings.warn('Install optipng to reduce the size of the generated images')