예제 #1
0
파일: motion.py 프로젝트: owad/guard
def green_key(canvas,key_image,img_source,mtype=KEY_REG):
    s3 = key_image.split()
    mask = (s3[1].point(lambda i: (i > 254 or 256))) # cut out green area (overlay)
    if(mtype == KEY_BLUR or mtype == KEY_BLUR_BRIGHT or mtype == KEY_BLUR_BRIGHT_MORE):
        mask = mask.filter(ImageFilter.SMOOTH_MORE)
        mask = mask.filter(ImageFilter.BLUR)
        mask = mask.filter(ImageFilter.SMOOTH_MORE)
    if(mtype == KEY_BLUR_BRIGHT):
        mask = (mask.point(lambda k: (k*2)))    
    elif(mtype == KEY_BLUR_BRIGHT_MORE):
        mask = (mask.point(lambda k: k > 20 and (k*k)))
#   mask.show()
#   mask.save("images/saved/mask.jpg")
#   canvas.convert("RGBA") # needed?

    if(canvas.size != img_source.size): # fix image size
        if(canvas.size < img_source.size):
            print "resizing canvas", canvas.size, img_source.size, key_image.size
            canvas = ImageOps.fit(canvas,img_source.size)
        else:
            print "resizing img_source and mask", canvas.size, img_source.size, key_image.size
            img_source = ImageOps.fit(img_source,canvas.size)
            mask = ImageOps.fit(mask,canvas.size)
    image = Image.composite(img_source,canvas,mask)
    return image
예제 #2
0
def green_key(canvas, key_image, img_source, mtype=KEY_REG):
    s3 = key_image.split()
    mask = (s3[1].point(lambda i: (i > 254 or 256))
            )  # cut out green area (overlay)
    if (mtype == KEY_BLUR or mtype == KEY_BLUR_BRIGHT
            or mtype == KEY_BLUR_BRIGHT_MORE):
        mask = mask.filter(ImageFilter.SMOOTH_MORE)
        mask = mask.filter(ImageFilter.BLUR)
        mask = mask.filter(ImageFilter.SMOOTH_MORE)
    if (mtype == KEY_BLUR_BRIGHT):
        mask = (mask.point(lambda k: (k * 2)))
    elif (mtype == KEY_BLUR_BRIGHT_MORE):
        mask = (mask.point(lambda k: k > 20 and (k * k)))


# 	mask.show()
# 	mask.save("images/saved/mask.jpg")
# 	canvas.convert("RGBA") # needed?

    if (canvas.size != img_source.size):  # fix image size
        if (canvas.size < img_source.size):
            print "resizing canvas", canvas.size, img_source.size, key_image.size
            canvas = ImageOps.fit(canvas, img_source.size)
        else:
            print "resizing img_source and mask", canvas.size, img_source.size, key_image.size
            img_source = ImageOps.fit(img_source, canvas.size)
            mask = ImageOps.fit(mask, canvas.size)
    image = Image.composite(img_source, canvas, mask)
    return image
예제 #3
0
	def resizeImage(self, file_path, th_width = 200, th_height = 200, or_width = 1000, or_height = 800):
		image = Image.open(file_path)

		# Crop and make thumbnails
		thumb = ImageOps.fit(image, (th_width, th_height), Image.ANTIALIAS)
		thumb64 = ImageOps.fit(image, (64, 64), Image.ANTIALIAS)

		# Resize original
		image.thumbnail((or_width, or_height), Image.ANTIALIAS)

		old_filename = file_path.rsplit('/', 1)[1]
		thumb_filename = old_filename.rsplit('.', 1)[0] + "_thumb.jpg"

		thumb_filename = thumb_filename.replace(" ", "_")
		new_filename = thumb_filename.replace(" ", "_")

		thumb.save(self.THUMB_DIR + thumb_filename, "JPEG", quality=100)
		thumb64.save(self.THUMB64_DIR + thumb_filename, "JPEG", quality=100)

		image.save(self.NEW_ORIGINAL_DIR + new_filename, "JPEG", quality=100)

		return {
			'original': old_filename,
		    'new_original': new_filename,
		    'thumbnail': thumb_filename
		}
예제 #4
0
def resize(relative_path, size, method):
    image_file = os.path.join(settings.MEDIA_ROOT, relative_path)
    relative_resized_path = resized_path(relative_path, size, method)
    resized_file = os.path.join(settings.MEDIA_ROOT, relative_resized_path)
    relative_url = os.path.join(settings.MEDIA_URL, relative_resized_path)
   
    # Parse size string 'WIDTHxHEIGHT'
    width, height = [int(i) for i in size.split('x')]
   
    if os.path.exists(resized_file):
        return relative_url
    try:
        image = Image.open(image_file)
    except:
        return settings.STATIC_URL + 'g/blank.png'
    if image.mode != 'RGB':
        image = image.convert('RGB')

    # use PIL methods to edit images
    if method == 'scale':
        image.thumbnail((width, height), Image.ANTIALIAS)
        image.save(resized_file, FORMAT, quality=QUALITY)
    elif method == 'crop':
        ImageOps.fit(image, (width, height), Image.ANTIALIAS).save(
            resized_file, FORMAT, quality=QUALITY)

    return relative_url
 def update(self, control):
     Effect.update(self, control)
     img = Image.new("RGB", self.providers[0].size)
     src_img = self.providers[0].getImage(self.currentFrame)
     size = self.providers[0].size
     x = 0
     for i in range(self.sliceCount):
         w = int(size[0] * (float(self.percentages[i]) / float(100)))
         l = x
         x += w
         r = x
         if i > self.__current_slice:
             tmpimg = ImageOps.fit(src_img, (w,img.size[1]))
             img.paste(tmpimg, (l,0,r,tmpimg.size[1]))
         if i == self.__current_slice + 1:
             self.__end_x = l 
     if self.__current_slice >= 0:
         start_x = int(self.__x)
         # paste left half
         tmpimg = ImageOps.fit(src_img, (start_x, img.size[1]))
         img.paste(tmpimg, (0,0,start_x, tmpimg.size[1]))
         # paste right half
         tmpimg = ImageOps.fit(src_img, ((self.__end_x - start_x), img.size[1]))
         img.paste(tmpimg, (start_x, 0, self.__end_x, tmpimg.size[1]))
         #self.__x += int(self.step_size[self.__current_slice])
         self.__x += self.__step_size
         if self.__x >= self.pixels[self.__current_slice]:
             self.__x = 0.00
             self.__current_slice -= 1
     self.keeper.setImage(img)
예제 #6
0
def generate_thumbnail(path, size, method):
    try:
        import Image
    except ImportError:
        try:
            from PIL import Image
        except ImportError:
            raise ImportError('Cannot import the Python Image Library.')

    image = Image.open(path)

    # normalize image mode
    if image.mode != 'RGB':
        image = image.convert('RGB')

    # parse size string 'WIDTHxHEIGHT'
    width, height = [int(i) for i in size.split('x')]

    # use PIL methods to edit images
    if method == 'scale':
        image.thumbnail((width, height), Image.ANTIALIAS)
        image.save(thumbnail_path(path, size, method), MEDIA_IMAGE_FORMAT, quality=MEDIA_IMAGE_QUALITY)

    elif method == 'crop':
        try:
            import ImageOps
        except ImportError:
            from PIL import ImageOps

        ImageOps.fit(
            image, (width, height), Image.ANTIALIAS
        ).save(thumbnail_path(path, size, method), MEDIA_IMAGE_FORMAT, quality=MEDIA_IMAGE_QUALITY)
예제 #7
0
 def _store_image_and_transformations(self, original):
     self._store_image(original)
     self._store_image(
         original, 'thumbnail', lambda
         (image): ImageOps.fit(image, (260, 260), Image.ANTIALIAS))
     self._store_image(
         original, 'large', lambda
         (image): ImageOps.fit(image, (612, 612), Image.ANTIALIAS))
예제 #8
0
파일: media.py 프로젝트: Sebski/Answer.tv
def uploadBkgImg(Bkgpic, oldname, newname):
    try:
        Bkgpicname = newname
        'Save tmp file'
        tmp_filepath = "atv/tmp/bkg/" + Bkgpicname
        tmp_output_file = open(tmp_filepath, 'wb')
        Bkgpic.seek(0)
        while True:
            data = Bkgpic.read(2 << 16)
            if not data:
                break
            tmp_output_file.write(data)
        tmp_output_file.close()
        'resize'
        size = 942, 225
        im = Image.open(tmp_filepath)
        im = ImageOps.fit(im, size, Image.ANTIALIAS)
        im.save(tmp_filepath, "PNG")
        'Save main img to S3'
        k = Key(b)
        k.key = "permbks/" + Bkgpicname
        k.set_contents_from_filename(tmp_filepath, policy='public-read')
        'resize mini'
        size = 230, 55
        im = Image.open(tmp_filepath)
        im = ImageOps.fit(im, size, Image.ANTIALIAS)
        im.save(tmp_filepath, "PNG")
        'Save main mini img to S3'
        k = Key(b)
        k.key = "minipermbks/" + Bkgpicname
        k.set_contents_from_filename(tmp_filepath, policy='public-read')
        'delete tmp file'
        os.remove(tmp_filepath)
        status = ""
        'delete old img files'
        do_not_delete_list = [
            "birdbox.png", "blueflower.png", "cars.png", "cartographer.png",
            "default.png", "elastoplast.png", "fireheart.png", "food.png",
            "glammer.png", "greyfloral.png", "knittednetting.png",
            "molten.png", "norwegianrose.png", "pineapple.png",
            "purplecrown.png", "reddrop.png", "redflower.png", "retroleaf.png",
            "seamless.png", "shattered.png", "stardust.png", "stripes.png",
            "whitebrick.png", "wood.png"
        ]
        if oldname in do_not_delete_list:
            pass
        else:
            k = Key(b)
            k.key = "permbks/" + oldname
            b.delete_key(k)
            k = Key(b)
            k.key = "minipermbks/" + oldname
            b.delete_key(k)
            return status
    except:
        status = """File could not be uploaded - please check the file extension
                 and try again."""
        return status
예제 #9
0
def scale(imagefield, method='scale'):
    """ 
    Template filter used to scale an image
    that will fit inside the defined area.

    Returns the url of the resized image.

    {% load image_tags %}
    {{ profile.picture|scale }}
    """

    if not imagefield:
		return None

    # imagefield can be a dict with "path" and "url" keys
    if imagefield.__class__.__name__ == 'dict':
        imagefield = type('imageobj', (object,), imagefield)

    image_path = resized_path(imagefield.path, method)

    #thumb_path = os.path.join(settings.MEDIA_ROOT, "%s_%s_%s.%s" % (imagefield.name.rsplit('.', 1)[0], method, EXT))
    #thumb_url = "%s_%s_%s.%s" % (imagefield.url.rsplit('.', 1)[0], method, EXT)

    #print thumb_path, thumb_url

    if not os.path.exists(image_path):
        try:
            import Image
        except ImportError:
            try:
                from PIL import Image
            except ImportError:
                raise ImportError('Cannot import the Python Image Library.')

        image = Image.open(imagefield.path)

        # normalize image mode
        if image.mode != 'RGB':
            image = image.convert('RGB')

        # use PIL methods to edit images
        if method == 'scale':
            width, height = [int(i) for i in IMAGE_SIZE.split('x')]
            image.thumbnail((width, height), Image.ANTIALIAS)
            image.save(image_path, FMT, quality=QUAL)

        elif method == 'crop':
            try:
                import ImageOps
            except ImportError:
                from PIL import ImageOps

            width, height = [int(i) for i in THUMBNAIL_SIZE.split('x')]
            ImageOps.fit(image, (width, height), Image.ANTIALIAS
                        ).save(image_path, FMT, quality=QUAL)
       
    return resized_path(imagefield.url, method)
예제 #10
0
파일: media.py 프로젝트: incerto/Answer.tv
def uploadBkgImg(Bkgpic, oldname, newname):
    try:
        Bkgpicname  = newname
        'Save tmp file'
        tmp_filepath = "atv/tmp/bkg/" + Bkgpicname
        tmp_output_file = open(tmp_filepath, 'wb')
        Bkgpic.seek(0)
        while True:
            data = Bkgpic.read(2<<16)
            if not data:
                break
            tmp_output_file.write(data)
        tmp_output_file.close()
        'resize'
        size = 942, 225
        im = Image.open(tmp_filepath)
        im = ImageOps.fit(im, size, Image.ANTIALIAS)
        im.save(tmp_filepath, "PNG")
        'Save main img to S3'
        k = Key(b)
        k.key = "permbks/" + Bkgpicname
        k.set_contents_from_filename(tmp_filepath, policy='public-read')
        'resize mini'
        size = 230, 55
        im = Image.open(tmp_filepath)
        im = ImageOps.fit(im, size, Image.ANTIALIAS)
        im.save(tmp_filepath, "PNG")
        'Save main mini img to S3'
        k = Key(b)
        k.key = "minipermbks/" + Bkgpicname
        k.set_contents_from_filename(tmp_filepath, policy='public-read')
        'delete tmp file'
        os.remove(tmp_filepath)
        status = ""
        'delete old img files'
        do_not_delete_list=["birdbox.png","blueflower.png","cars.png","cartographer.png","default.png","elastoplast.png",
                            "fireheart.png","food.png","glammer.png","greyfloral.png","knittednetting.png","molten.png",
                            "norwegianrose.png","pineapple.png","purplecrown.png","reddrop.png","redflower.png","retroleaf.png",
                            "seamless.png","shattered.png","stardust.png","stripes.png","whitebrick.png","wood.png"]
        if oldname in do_not_delete_list:
            pass
        else:
            k = Key(b)
            k.key = "permbks/" + oldname
            b.delete_key(k)
            k = Key(b)
            k.key = "minipermbks/" + oldname
            b.delete_key(k)
            return status
    except:
        status = """File could not be uploaded - please check the file extension
                 and try again."""
        return status
예제 #11
0
파일: ajax.py 프로젝트: FRYerOK/tweeria
	def resizeImage(self, buffer_filepath, local_filepath, params, cropped_image = False):

		image = Image.open(buffer_filepath)

		width, height = image.size
		imgData = {
			"width" : width,
			"height": height
		}

		need_resize = False

		createSmallItemSpell = False
		if "type_of_form" in params and params['type_of_form'] == "create_artwork":
			checkWidth = self.core.MAX_ARTWORK_WIDTH
			checkHeight = self.core.MAX_ARTWORK_HEIGHT

		elif "type_of_form" in params and (params['type_of_form'] == "create_item" or params['type_of_form'] == "create_spell"):
			checkWidth = self.core.MAX_ITEM_SPELL_WIDTH
			checkHeight = self.core.MAX_ITEM_SPELL_HEIGHT
			createSmallItemSpell = True
		else:
			checkWidth = self.core.MAX_AVA_WIDTH
			checkHeight = self.core.MAX_AVA_HEIGHT

		if width > checkWidth:
			width = checkWidth
			need_resize = True

		if height > checkHeight:
			height = checkHeight
			need_resize = True

		#need_resize = False

		if need_resize:
			if params['type_of_form'] == "create_artwork":
				thumb = ImageOps.fit(cropped_image, (self.core.THUMB_ARTWORK_WIDTH, self.core.THUMB_ARTWORK_HEIGHT), Image.ANTIALIAS)
			else:
				thumb = ImageOps.fit(cropped_image, (width,height), Image.ANTIALIAS)
			thumb.save(local_filepath+"_fit.png", "PNG")
		elif params['type_of_form'] == "create_artwork":
			thumb = ImageOps.fit(cropped_image, (self.core.THUMB_ARTWORK_WIDTH, self.core.THUMB_ARTWORK_HEIGHT), Image.ANTIALIAS)
			thumb.save(local_filepath+"_fit.png", "PNG")
		else:
			image.save(local_filepath+"_fit.png", "PNG")


		if createSmallItemSpell:
			thumb = ImageOps.fit(cropped_image, (self.core.THUMB_ITEM_SPELL_WIDTH, self.core.THUMB_ITEM_SPELL_HEIGHT), Image.ANTIALIAS)
			thumb_local_filpath = local_filepath+"_thumb.png"
			thumb.save(thumb_local_filpath,"PNG")
		return imgData
예제 #12
0
def scaleByWidth(imagefield, size, method='scale'):
    """
    Template filter used to scale an image
    that will fit inside the defined area.

    Returns the url of the resized image.

    {% load image_tags %}
    {{ profile.picture|scale:"48x48" }}
    """

    # imagefield can be a dict with "path" and "url" keys
    if imagefield.__class__.__name__ == 'dict':
        imagefield = type('imageobj', (object, ), imagefield)

    image_path = resized_path(imagefield.path, size, method)

    if not os.path.exists(image_path):
        try:
            import Image
        except ImportError:
            try:
                from PIL import Image
            except ImportError:
                raise ImportError('Cannot import the Python Image Library.')

        image = Image.open(imagefield.path)

        # normalize image mode
        if image.mode != 'RGB':
            image = image.convert('RGB')

        # parse size string 'WIDTHxHEIGHT'
        # width, height = [int(i) for i in size.split('x')]
        width = int(size)
        wpercent = (width / float(image.size[0]))
        height = int((float(image.size[1]) * float(wpercent)))

        # use PIL methods to edit images
        if method == 'scale':
            image.thumbnail((width, height), Image.ANTIALIAS)
            image.save(image_path, FMT, quality=QUAL)

        elif method == 'crop':
            try:
                import ImageOps
            except ImportError:
                from PIL import ImageOps

            ImageOps.fit(image, (width, height),
                         Image.ANTIALIAS).save(image_path, FMT, quality=QUAL)

    return resized_path(imagefield.url, size, method)
예제 #13
0
def scaleByWidth(imagefield, size, method='scale'):
    """
    Template filter used to scale an image
    that will fit inside the defined area.

    Returns the url of the resized image.

    {% load image_tags %}
    {{ profile.picture|scale:"48x48" }}
    """

    # imagefield can be a dict with "path" and "url" keys
    if imagefield.__class__.__name__ == 'dict':
        imagefield = type('imageobj', (object,), imagefield)

    image_path = resized_path(imagefield.path, size, method)

    if not os.path.exists(image_path):
        try:
            import Image
        except ImportError:
            try:
                from PIL import Image
            except ImportError:
                raise ImportError('Cannot import the Python Image Library.')

        image = Image.open(imagefield.path)

        # normalize image mode
        if image.mode != 'RGB':
            image = image.convert('RGB')

        # parse size string 'WIDTHxHEIGHT'
        # width, height = [int(i) for i in size.split('x')]
        width = int(size)
        wpercent =(width / float(image.size[0]))
        height = int((float(image.size[1]) * float(wpercent)))

        # use PIL methods to edit images
        if method == 'scale':
            image.thumbnail((width, height), Image.ANTIALIAS)
            image.save(image_path, FMT, quality=QUAL)

        elif method == 'crop':
            try:
                import ImageOps
            except ImportError:
                from PIL import ImageOps

            ImageOps.fit(image, (width, height), Image.ANTIALIAS
                        ).save(image_path, FMT, quality=QUAL)

    return resized_path(imagefield.url, size, method)
예제 #14
0
def scale_image(image_path, size, method='scale'):
    """
    Return generated or cached thumbnail relative path

    image_path - a full path in file system
    size - an array or tuple of width and height
    """
    (original_path, file_name, file_ext) = split_filepath(image_path)
    cached_filename = '%s.%s.%dx%d_%s.jpg' % (file_name, file_ext, size[0], size[1], method)
    cached_file_path = '%s/%s' % (original_path, cached_filename)

    if not os.path.exists(image_path):
        return False

    if not os.path.exists(cached_file_path):
        try:
            import Image
        except ImportError:
            try:
                from PIL import Image
            except ImportError:
                raise ImportError('Cannot import the Python Image Library.')

        image = Image.open(image_path)

        # normalize image mode
        if image.mode != 'RGBA':
            image = image.convert('RGBA')

        if format == 'PNG':
            pixdata = image.load()
            for y in xrange(image.size[1]):
                for x in xrange(image.size[0]):
                    if pixdata[x, y] == (0, 0, 0, 0):
                        pixdata[x, y] = (255, 255, 255, 0)

        if method == 'scale':
            image.thumbnail(size, Image.ANTIALIAS)
            image.save(cached_file_path, 'JPEG')
        elif method == 'crop':
            try:
                import ImageOps
            except ImportError:
                from PIL import ImageOps

            ImageOps.fit(image, size, Image.ANTIALIAS).save(cached_file_path, 'JPEG', quality=80)

    #return os.path.abspath(cached_file_path).replace(os.path.abspath(settings.BASE_PATH), '')
    return cached_filename
예제 #15
0
 def resize_image(cls, image_body, size, fit_to_size=False):
     """Takes a raw image (in image_body) and resizes it to fit given
     dimensions. Returns a  file-like object in the form of a StringIO. 
     This must happen in this function because PIL is transforming the 
     original as it works."""
     
     image_file = StringIO(image_body)
     try:
         image = Image.open(image_file)
     except IOError:
         # Invalid image file
         return False
                     
     # Get the image format early, as we lose it after perform a `thumbnail` or `fit`.
     format = image.format
     
     # Check for rotation
     image = cls.adjust_image_orientation(image)
     
     if not fit_to_size:
         image.thumbnail(PROFILE_PICTURE_SIZES[size], Image.ANTIALIAS)
     else:
         image = PILOps.fit(image, PROFILE_PICTURE_SIZES[size], 
                            method=Image.ANTIALIAS, 
                            centering=(0.5, 0.5))
     
     output = StringIO()
     if format.lower() == 'jpg':
         format = 'jpeg'
     image.save(output, format=format, quality=95)
     
     return output
예제 #16
0
    def render_and_save_variation(self, name, content, variation):
        """
        Renders the image variations and saves them to the storage
        """
        resample = variation['resample'] or Image.ANTIALIAS

        content.seek(0)

        img = Image.open(content)

        if self.is_smaller(img, variation):
            factor = 1
            while (img.size[0] / factor > 2 * variation['width'] and
                                   img.size[1] * 2 / factor > 2 * variation['height']):
                factor *= 2
            if factor > 1:
                img.thumbnail((int(img.size[0] / factor),
                               int(img.size[1] / factor)), resample=resample)

            if variation['crop']:
                img = ImageOps.fit(img, (variation['width'], variation['height']), method=resample)
            else:
                img.thumbnail((variation['width'], variation['height']), resample=resample)
        variation_name = self.get_variation_name(self.instance, self.field, variation)
        file_buffer = StringIO()
        format = self.get_file_extension(name).lower().replace('jpg', 'jpeg')
        img.save(file_buffer, format)
        self.storage.save(variation_name, ContentFile(file_buffer.getvalue()))
        file_buffer.close()
예제 #17
0
def settings(request):
	if not request.user.is_authenticated():
		return HttpResponseForbidden("<h1>Forbidden</h1><p>user not authenticated</p>")
	
	c={}
	c.update(csrf(request))
	
	if request.method == 'POST':
		settingsForm = SettingsForm(request.POST, request.FILES)
		if settingsForm.is_valid():
			avatarFile = settingsForm.cleaned_data['avatarFile']
			if avatarFile:
				userProfile = UserProfile.objects.get(user=request.user)
				if userProfile.avatar:
					userProfile.avatar.delete(save=False) # deleting old avatar
				# creating new one, with sha1'ed name
				hashingFunc = sha1()
				hashingFunc.update(hashSalt + str(request.user.id))
				avatarFileName = "%s.%s" % (hashingFunc.hexdigest(), avatarFile.content_type.split('/')[1])
				
				originalImage = Image.open(avatarFile)
				resizedImage = ImageOps.fit(originalImage, (300, 300), Image.ANTIALIAS)
				
				tmpDest = os.path.join(MEDIA_ROOT, 'avatars', 'tmp' + avatarFileName)
				resizedImage.save(tmpDest)
				f = open(tmpDest)
				avatarResizedFile = File(f)
				userProfile.avatar.save(avatarFileName, avatarResizedFile)
				avatarResizedFile.close()
				os.remove(tmpDest)
		########
			user = request.user
			user.first_name = settingsForm.cleaned_data['first_name']
			user.last_name = settingsForm.cleaned_data['last_name']
			user.email = settingsForm.cleaned_data['email_address']
			user.userprofile.bio = settingsForm.cleaned_data['bio']
			if settingsForm.cleaned_data['old_password']:
				if settingsForm.cleaned_data['new_password']:
					user.set_password(settingsForm.cleaned_data['new_password'])
			user.save()
			user.userprofile.save()

			return HttpResponseRedirect('/settings/')

	else:
		settingsForm = SettingsForm(
				{
					'userId': str(request.user.id),
					'first_name':request.user.first_name,
					'last_name':request.user.last_name,
					'email_address':request.user.email,
					'bio' :request.user.userprofile.bio
				})

	sectionTitle = inspect.stack()[0][3]
	c.update({'sectionTitle' : sectionTitle, 'sections' : sections, 'settingsForm': settingsForm})
	return render_to_response('%s.html' % sectionTitle, c, context_instance=RequestContext(request))
	
	
	
예제 #18
0
def creIma(Hum):
    wrNumb(Hum)
    highlight = Image.open('/usr/share/ingweather/data/square.png')
    mask = Image.open('/usr/share/ingweather/data/square-mask.png')
    icon = Image.open('/tmp/ingweather/numb.png').convert('RGBA')
    button = Image.new('RGBA', mask.size)
 
    # Resize Icon
    icon = ImageOps.fit(
        icon, highlight.size, method=Image.ANTIALIAS, centering=(0.5, 0.5)
        )
 
    # Create a helper image that will hold the icon after the reshape
    helper = button.copy()
    # Cut the icon by the shape of the mask
    helper.paste(icon, mask=mask)
 
    # Fill with a solid color by the mask's shape
    button.paste((255, 255, 255), mask=mask)
    # Get rid of the icon's alpha band
    icon = icon.convert('RGB')
    # Paste the icon on the solid background
    # Note we are using the reshaped icon as a mask
    button.paste(icon, mask=helper)
 
    # Get a copy of the highlight image without the alpha band
    overlay = highlight.copy().convert('RGB')
    button.paste(overlay, mask=highlight)
 
    button.save('/tmp/ingweather/button.png')
예제 #19
0
    def _resize_image(self, filename, size):
        """Resizes the image to specified width, height and force option
            - filename: full path of image to resize
            - size: dictionary containing:
                - width: new width
                - height: new height
                - force: if True, image will be cropped to fit the exact size,
                    if False, it will have the bigger size that fits the
                    specified size, but without cropping, so it could be
                    smaller on width or height
        """
        WIDTH, HEIGHT = 0, 1
        # from PIL import Image, ImageOps #@UnresolvedImport
        import Image
        import ImageOps  # @UnresolvedImport

        img = Image.open(filename)
        if img.size[WIDTH] > size["width"] or img.size[HEIGHT] > size["height"]:
            if size["force"]:
                img = ImageOps.fit(img, (size["width"], size["height"]), Image.ANTIALIAS)
            else:
                img.thumbnail((size["width"], size["height"]), Image.ANTIALIAS)
            try:
                img.save(filename, optimize=1)
            except IOError:
                img.save(filename)
예제 #20
0
    def resize(self, img=None, orientation=None):
        size = 640, 640
        try:
            if not img:
                img = Image.open(self.image)

            # Rotate/Flip image according to orientation
            if orientation:
                if orientation == 1:
                    pass
                elif orientation == 2:
                    img = img.transpose(Image.FLIP_LEFT_RIGHT)
                elif orientation == 3:
                    img = img.transpose(Image.ROTATE_180)
                elif orientation == 4:
                    img = img.transpose(Image.FLIP_TOP_BOTTOM)
                elif orientation == 5:
                    img = img.transpose(Image.FLIP_LEFT_RIGHT).transpose(
                        Image.ROTATE_90)
                elif orientation == 6:
                    img = img.transpose(Image.ROTATE_270)
                elif orientation == 7:
                    img = img.transpose(Image.ROTATE_270).transpose(
                        Image.FLIP_LEFT_RIGHT)
                elif orientation == 8:
                    img = img.transpose(Image.ROTATE_90)

            img = ImageOps.fit(img, size, Image.ANTIALIAS, 0, (0.5, 0.5))
            img.save(self.original_path(), "PNG")

        except IOError:
            print "Cannot create resized image for ", self.image
예제 #21
0
def scale(imagefield, size, method='scale'):
    """ 
    Template filter used to scale an image
    that will fit inside the defined area.

    Returns the url of the resized image.

    {% load image_format %}
    {{ profile.picture|scale:"48x48" }}
    """

    # imagefield can be a dict with "path" and "url" keys
    if imagefield.__class__.__name__ == 'dict':
        imagefield = type('imageobj', (object,), imagefield)

    image_path = resized_path(imagefield.path, size, method)

    need_resize = True

    if not os.path.exists(image_path):
        try:
            import Image
        except ImportError:
            try:
                from PIL import Image
            except ImportError:
                raise ImportError('Cannot import the Python Image Library.')

        image = Image.open(imagefield.path)

        # normalize image mode
        if image.mode != 'RGBA' or image.mode != 'RGB':
            image = image.convert('RGBA')

        # parse size string 'WIDTHxHEIGHT'
        width, height = [int(i) for i in size.split('x')]

        need_resize = width != image.size[0] or height != image.size[1]

        # use PIL methods to edit images
        if method == 'scale' and need_resize:
            premultiply(image)
            image.thumbnail((width, height), Image.ANTIALIAS)
            unmultiply(image)
            image.save(image_path, FMT, quality=QUAL)

        elif method == 'crop' and need_resize:
            try:
                import ImageOps
            except ImportError:
                from PIL import ImageOps

            premultiply(image)
            image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
            unmultiply(image)
            image.save(image_path, FMT, quality=QUAL)

    if need_resize:
        return resized_path(imagefield.url, size, method)
    return imagefield.url
예제 #22
0
    def resize_image(cls, image_body, size, fit_to_size=False):
        """Takes a raw image (in image_body) and resizes it to fit given
        dimensions. Returns a  file-like object in the form of a StringIO. 
        This must happen in this function because PIL is transforming the 
        original as it works."""

        image_file = StringIO(image_body)
        try:
            image = Image.open(image_file)
        except IOError:
            # Invalid image file
            return False

        # Get the image format early, as we lose it after perform a `thumbnail` or `fit`.
        format = image.format

        # Check for rotation
        image = cls.adjust_image_orientation(image)

        if not fit_to_size:
            image.thumbnail(PROFILE_PICTURE_SIZES[size], Image.ANTIALIAS)
        else:
            image = PILOps.fit(image,
                               PROFILE_PICTURE_SIZES[size],
                               method=Image.ANTIALIAS,
                               centering=(0.5, 0.5))

        output = StringIO()
        if format.lower() == 'jpg':
            format = 'jpeg'
        image.save(output, format=format, quality=95)

        return output
예제 #23
0
    def render_and_save_variation(self, name, content, variation):
        """
        Renders the image variations and saves them to the storage
        """
        content.seek(0)

        img = Image.open(content)

        if self.is_smaller(img, variation):
            factor = 1
            while (img.size[0] / factor > 2 * variation['width'] and
                                   img.size[1] * 2 / factor > 2 * variation['height']):
                factor *= 2
            if factor > 1:
                img.thumbnail((int(img.size[0] / factor),
                               int(img.size[1] / factor)), resample=resample)

            if variation['crop']:
                img = ImageOps.fit(img, (variation['width'], variation['height']), method=resample)
            else:
                img.thumbnail((variation['width'], variation['height']), resample=resample)
        variation_name = self.get_variation_name(self.instance, self.field, variation)
        file_buffer = StringIO()
        format = self.get_file_extension(name).lower().replace('jpg', 'jpeg')
        img.save(file_buffer, format)
        self.storage.save(variation_name, ContentFile(file_buffer.getvalue()))
        file_buffer.close()
예제 #24
0
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()
예제 #25
0
	def resize(self, img=None, orientation=None):
		size = 640,640
		try:
			if not img:
				img = Image.open(self.image)
				
			# Rotate/Flip image according to orientation
			if orientation:
				if orientation == 1: 
					pass
				elif orientation == 2: 
					img = img.transpose(Image.FLIP_LEFT_RIGHT)
				elif orientation == 3: 
					img = img.transpose(Image.ROTATE_180)                
				elif orientation == 4: 
					img = img.transpose(Image.FLIP_TOP_BOTTOM) 
				elif orientation == 5: 
					img = img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_90)
				elif orientation == 6: 
					img = img.transpose(Image.ROTATE_270)
				elif orientation == 7: 
					img = img.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)
				elif orientation == 8: 
					img = img.transpose(Image.ROTATE_90) 
				
			img = ImageOps.fit(img, size, Image.ANTIALIAS, 0, (0.5,0.5))
			img.save(self.original_path(), "PNG")

		except IOError:
			print "Cannot create resized image for ", self.image
예제 #26
0
def create_photo_strips():
    '''using the original images we build a color and black and white photo strip and save it to photos/strips'''
    strip = Image.new('RGB', (PHOTO_HEIGHT + (BORDER_WIDTH * 2) + FOOTER_HEIGHT, (PHOTO_WIDTH * PHOTO_COUNT) + (BORDER_WIDTH * 2)), BG_COLOR)    

    for i in range(PHOTO_COUNT):
        photo = Image.open(PHOTO_FOLDER + str(i+1) + '.' + PHOTO_FILE_EXTENSION)
        
        w, h = map(lambda x: x/2, photo.size)
        
        photo = ImageOps.fit(photo, (PHOTO_WIDTH, PHOTO_HEIGHT), centering=(0.5, 0.5))
        photo = photo.rotate(270)
        photo = ImageOps.autocontrast(photo, cutoff=0)
        
        strip.paste(photo, (FOOTER_HEIGHT, (i * PHOTO_WIDTH) + (i * BORDER_WIDTH)))

    #append footer

    font = ImageFont.truetype('font_1.ttf', 40)

    footer_img = Image.new("RGB", ((PHOTO_COUNT * PHOTO_WIDTH) + (PHOTO_COUNT * BORDER_WIDTH), FOOTER_HEIGHT), BG_COLOR)
    draw = ImageDraw.Draw(footer_img)
    draw.text((220, 40), "ashley & david's wedding, july 28, 2012", font=font, fill=(100,100,0))
    strip.paste(footer_img.rotate(270), (0,0))

    strip.save(COLOR_FOLDER + current_timestamp() + '.png', PHOTO_FORMAT)
    ImageOps.grayscale(strip).save(GREYSCALE_FOLDER + current_timestamp() + '.png', PHOTO_FORMAT)

    strip_to_print = Image.new('RGB', (PAGE_WIDTH, PAGE_HEIGHT), BG_COLOR)
    strip_to_print.paste(ImageOps.grayscale(strip), (-BORDER_WIDTH, -BORDER_WIDTH))

    strip_to_print.save('to_print.png', PHOTO_FORMAT)
    
    return 'to_print.png'
예제 #27
0
파일: models.py 프로젝트: frac/foodsite
    def create_thumb(self):
        """
        Reformat and create small and thumbnail images.
        All pictures are squared for artistic reasons :)
        """
        self.image.seek(0)
        original = Image.open(self.image)
        if original.mode not in ('L', 'RGB'):
            original = original.convert('RGB')

        quality_val = 95
        dpi_val = (150, 150)

        format = original.format
        min_dim = min(original.size)
        #original = original.crop((0,0,min_dim,min_dim))

        #make it square
        original = ImageOps.fit(original, (min_dim, min_dim), centering=(0.5, 0.5))

        #make large
        im = original.resize((MAX_SIZE, MAX_SIZE), Image.ANTIALIAS)
        im.save(self.image.path, format, quality=quality_val, dpi=dpi_val)

        #make small
        im = original.resize((SMALL_SIZE, SMALL_SIZE), Image.ANTIALIAS)
        im.save(self.get_path(thumb=False), format, quality=quality_val, dpi=dpi_val)

        # Make Thumb
        im = original.resize((THUMB_SIZE, THUMB_SIZE), Image.ANTIALIAS)
        im.save(self.get_path(thumb=True), format, quality=quality_val, dpi=dpi_val)
예제 #28
0
    def snap(self, file):
        self.camera.capture(file, use_video_port=True)
        Time.sleep(0.1)

        im = Image.open(file)
        smaller = ImageOps.fit(im, self.normal_size, Image.ANTIALIAS, (0.5, 0.5))
        smaller.save(file, 'JPEG', quality=98)
예제 #29
0
파일: media.py 프로젝트: Sebski/Answer.tv
def uploadImg(Profilepic, oldname, newname):
    try:
        Profilepicname = newname
        'Save tmp file'
        tmp_filepath = "atv/tmp/profile/" + Profilepicname
        tmp_output_file = open(tmp_filepath, 'wb')
        Profilepic.seek(0)
        while True:
            data = Profilepic.read(2 << 16)
            if not data:
                break
            tmp_output_file.write(data)
        tmp_output_file.close()
        'resize'
        size = 200, 200
        im = Image.open(tmp_filepath)
        im = ImageOps.fit(im, size, Image.ANTIALIAS)
        im.save(tmp_filepath, "PNG")
        'Save img to S3'
        k = Key(b)
        k.key = "profileimg/" + Profilepicname
        k.set_contents_from_filename(tmp_filepath, policy='public-read')
        status = ""
        'resize mini'
        size = 25, 25
        im = Image.open(tmp_filepath)
        im = ImageOps.fit(im, size, Image.ANTIALIAS)
        im.save(tmp_filepath, "PNG")
        'Save mini img to S3'
        k = Key(b)
        k.key = "miniprofileimg/" + Profilepicname
        k.set_contents_from_filename(tmp_filepath, policy='public-read')
        'delete tmp file'
        os.remove(tmp_filepath)
        status = ""
        'delete old img files'
        k = Key(b)
        k.key = "profileimg/" + oldname
        b.delete_key(k)
        k = Key(b)
        k.key = "miniprofileimg/" + oldname
        b.delete_key(k)
        return status
    except:
        status = """File could not be uploaded - please check the file extension
                 and try again."""
        return status
예제 #30
0
파일: media.py 프로젝트: incerto/Answer.tv
def uploadImg(Profilepic, oldname, newname):
    try:
        Profilepicname = newname
        'Save tmp file'
        tmp_filepath = "atv/tmp/profile/" + Profilepicname
        tmp_output_file = open(tmp_filepath, 'wb')
        Profilepic.seek(0)
        while True:
            data = Profilepic.read(2<<16)
            if not data:
                break
            tmp_output_file.write(data)
        tmp_output_file.close()
        'resize'
        size = 200, 200
        im = Image.open(tmp_filepath)
        im = ImageOps.fit(im, size, Image.ANTIALIAS)
        im.save(tmp_filepath, "PNG")
        'Save img to S3'
        k = Key(b)
        k.key = "profileimg/" + Profilepicname 
        k.set_contents_from_filename(tmp_filepath, policy='public-read')
        status = ""
        'resize mini'
        size = 25, 25
        im = Image.open(tmp_filepath)
        im = ImageOps.fit(im, size, Image.ANTIALIAS)
        im.save(tmp_filepath, "PNG")
        'Save mini img to S3'
        k = Key(b)
        k.key = "miniprofileimg/" + Profilepicname
        k.set_contents_from_filename(tmp_filepath, policy='public-read')
        'delete tmp file'
        os.remove(tmp_filepath)      
        status = ""
        'delete old img files'
        k = Key(b)
        k.key = "profileimg/" + oldname
        b.delete_key(k)
        k = Key(b)
        k.key = "miniprofileimg/" + oldname
        b.delete_key(k)
        return status
    except:
        status = """File could not be uploaded - please check the file extension
                 and try again."""
        return status
 def __init__(self, size, default=None):
     self.size = size
     if default:
         self.__default = Image.open(default)
         if self.__default.mode != "RGB":
             self.__default = self.__default.convert("RGB")
         if self.__default.size != size:
             self.__default = ImageOps.fit(self.__default,self.size)
 def getImage(self, frame_num):
     """ try helps us loop to begining of sequence
     if we reach the end start providing frames from the begining"""
     try:
         image = Image.open(self.__src % (frame_num - self.__offset))
     except IOError:
         self.__offset = frame_num - 1
         image = Image.open(self.__src % (frame_num - self.__offset))
     return ImageOps.fit(image, self.size)
 def get_pilscreens(self,screens,screensdir,number_thumbs,image_size):
     method = Image.ANTIALIAS
     bleed = 0
     centering = (0.5,0.5)
     
     defaulthumbpath = self.get_defaulthumbpath()
     defaulthumb = ImageOps.fit(Image.open(defaulthumbpath),image_size,method,bleed,centering)
     pilscreens = [defaulthumb] * number_thumbs
     
     #random.shuffle(screens)
     i = 0
     for screen in screens:
         if i < number_thumbs:
             im = Image.open(os.path.join(screensdir,screen))
             thumb = ImageOps.fit(im,image_size,method,bleed,centering)
             pilscreens[i] = thumb
             i += 1
     return pilscreens
예제 #34
0
    def __call__(self, image, x, y, sheet_xdensity, sheet_ydensity, width=1.0, height=1.0):
        self.image=image

        # JPALERT: Right now this ignores all options and just fits the image into given array.
        # It needs to be fleshed out to properly size and crop the
        # image given the options. (maybe this class needs to be
        # redesigned?  The interface to this function is pretty inscrutable.)
        im = ImageOps.fit(self.image,x.shape,self.sampling_method)
        return array(im,dtype=Float)
예제 #35
0
파일: image.py 프로젝트: ceball/imagen
    def __call__(self, image, x, y, sheet_xdensity, sheet_ydensity, width=1.0, height=1.0):
        self.image=image

        # JPALERT: Right now this ignores all options and just fits the image into given array.
        # It needs to be fleshed out to properly size and crop the
        # image given the options. (maybe this class needs to be
        # redesigned?  The interface to this function is pretty inscrutable.)
        im = ImageOps.fit(self.image,x.shape,self.sampling_method)
        return array(im,dtype=Float)
예제 #36
0
    def push_history_frame(self, frame):
        """ Push a frame to the top of the history images. """

        # Shift back.
        for n in range(len(self._ui_history_frames) - 1):
            self._ui_history_frames[n][:,:] = self._ui_history_frames[n+1][:,:]
        # Update.
        h, w = self._ui_history_frame_size
        img = np.array(ImageOps.fit(PIL.Image.fromarray(frame), (w, h)))
        self._ui_history_frames[-1][:,:] = img
예제 #37
0
	def run(self):
		Output.debug("PhotoLoadThread " + str(self.index) + " starting...")
		# Load the photo
		Output.debug("PhotoLoadThread " + str(self.index) + ": Opening...")
		self.image = Image.open(self.filename)
		Output.debug("PhotoLoadThread " + str(self.index) + ": Fitting...")
		self.image = ImageOps.fit(self.image, (Display.image_size(self.fullsize), Display.image_size(self.fullsize)))
		Output.debug("PhotoLoadThread " + str(self.index) + ": TKing...")
		images()[self.index] = ImageTk.PhotoImage(self.image)
		Output.debug("PhotoLoadThread " + str(self.index) + " finished.")
예제 #38
0
def make_thumbnail(photo_url, width=None, height=None, aspect=None,
                   root=settings.MEDIA_ROOT, url_root=settings.MEDIA_URL):
    """ create thumbnail """

    # one of width/height is required
    assert (width is not None) or (height is not None)

    if not photo_url:
        return None

    th_url = _get_thumbnail_path(photo_url, width, height, aspect)
    th_path = get_path_from_url(th_url, root, url_root)
    photo_path = get_path_from_url(photo_url, root, url_root)

    if _has_thumbnail(photo_url, width, height, root, url_root, aspect):
        # thumbnail already exists
        if not (os.path.getmtime(photo_path) > os.path.getmtime(th_path)):
            # if photo mtime is newer than thumbnail recreate thumbnail
            return th_url

    # make thumbnail

    # get original image size
    orig_w, orig_h = get_image_size(photo_url, root, url_root)
    if (orig_w is None) and (orig_h is None):
        # something is wrong with image
        return photo_url

    # make proper size
    if (width is not None) and (height is not None):
        if (orig_w == width) and (orig_h == height):
            # same dimensions
            return None
        size = (width, height)
    elif width is not None:
        if orig_w == width:
            # same dimensions
            return None
        size = (width, orig_h)
    elif height is not None:
        if orig_h == height:
            # same dimensions
            return None
        size = (orig_w, height)

    try:
        img = Image.open(photo_path).copy()
        if aspect:
            img = ImageOps.fit(img, size, Image.ANTIALIAS, (0.5, 0.5))
        img.thumbnail(size, Image.ANTIALIAS)
        img.save(th_path, quality=settings.THUMBNAIL_QUALITY)
    except Exception, err:
        # this goes to webserver error log
        print >> sys.stderr, '[MAKE THUMBNAIL] error %s for file %r' % (err, photo_url)
        return photo_url
 def update(self, control):
     Effect.update(self, control)
     src_img = self.providers[0].getImage(self.currentFrame)
     img = self.providers[1].getImage(self.currentFrame)
     size = self.providers[1].size
     x = 0
     for i in range(self.sliceCount):
         w = int(size[0] * (float(self.percents[i]) / float(100)))
         l = x
         x += w
         r = x
         if not(self.truths) or (self.truths and self.truths[i]):
             tmpimg = ImageOps.fit(src_img, (w,img.size[1]))
             if self.maskProvider:
                 mask = self.maskProvider.getImage(self.currentFrame)
                 mask = ImageOps.fit(mask, tmpimg.size) 
                 img.paste(tmpimg, (l,0,r,img.size[1]), mask)
             else:
                 img.paste(tmpimg, (l,0,r,img.size[1]))
     self.keeper.setImage(img)
예제 #40
0
파일: filters.py 프로젝트: gonicus/clacks
    def process(self, obj, key, valDict, *sizes):

        # Sanity check
        if len(sizes) == 0:
            raise ElementFilterException(C.make_error("USER_IMAGE_SIZE_MISSING"))

        # Do we have an attribute to process?
        if key in valDict and valDict[key]['value']:

            # Check if a cache entry exists...
            entry = self.db.cache.find_one({'uuid': obj.uuid, 'attribute': key}, {'modified': 1})
            if entry:

                # Nothing to do if it's unmodified
                if obj.modifyTimestamp == entry['modified']:
                    return key, valDict

            # Create new cache entry
            else:
                c_entry = {
                    'uuid': obj.uuid,
                    'attribute': key
                    }
                self.db.cache.save(c_entry)

            # Convert all images to all requested sizes
            data = {
                    'uuid': obj.uuid,
                    'attribute': key,
                    'modified': obj.modifyTimestamp
                    }
            for idx in range(0, len(valDict[key]['value'])):
                image = StringIO(valDict[key]['value'][idx].get())
                try:
                    im = Image.open(image) #@UndefinedVariable
                except IOError:
                    continue

                for size in sizes:
                    s = int(size)
                    tmp = ImageOps.fit(im, (s, s), Image.ANTIALIAS) #@UndefinedVariable
                    tgt = StringIO()
                    tmp.save(tgt, "JPEG")

                    # Collect all images in [size][] lists
                    if not size in data:
                        data[size] = []

                    data[size].append(Binary(tgt.getvalue()))

            # Update cache
            self.db.cache.update({'uuid': obj.uuid, 'attribute': key}, data)

        return key, valDict
예제 #41
0
    def prepare_image(cls, image):
        if isinstance(image, str):
            image = Image.open(image)

        if isinstance(image, Image.Image):
            if (image.size[0] < cls.kernel_size or
                image.size[1] < cls.kernel_size):
                image = ImageOps.fit(image, (cls.kernel_size, cls.kernel_size))
            image = np.array(image)

        image = image.swapaxes(1, 2).swapaxes(0, 1).astype(np.float32)
        return image
예제 #42
0
    def clientChanged(self, event):
        #print "   ... video Client Changed"
        jpg = self.commQueue.get()
        cv_image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),
                                cv2.CV_LOAD_IMAGE_COLOR)
        cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
        pil_image = PIL.Image.fromarray(cv_image)
        pil_image2 = ImageOps.fit(pil_image, (640, 360), Image.ANTIALIAS)
        tk_image = ImageTk.PhotoImage(image=pil_image2)

        self.hui.image_label.configure(image=tk_image)
        self.hui.image_label._image_cache = tk_image  # avoid garbage collection
        self.hui.root.update()
예제 #43
0
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
예제 #44
0
    def _resize_image(self, filename, size):
        """Resizes the image to specified width, height and force option

        Arguments::

        filename -- full path of image to resize
        size -- dictionary with
            - width: int
            - height: int
            - force: bool
                if True, image will be cropped to fit the exact size,
                if False, it will have the bigger size that fits the specified
                size, but without cropping, so it could be smaller on width
                or height

        """

        width, height = 0, 1
        try:
            import Image, ImageOps
        except ImportError:
            from PIL import Image, ImageOps
        img = Image.open(filename)
        if (img.size[width] > size['width']
                or img.size[height] > size['height']):

            #If the image is big resize it with the cheapest resize algorithm
            factor = 1
            while (img.size[0] / factor > 2 * size['width']
                   and img.size[1] * 2 / factor > 2 * size['height']):
                factor *= 2
            if factor > 1:
                img.thumbnail(
                    (int(img.size[0] / factor), int(img.size[1] / factor)),
                    Image.NEAREST)

            if size['force']:
                img = ImageOps.fit(img, (size['width'], size['height']),
                                   Image.ANTIALIAS)
            else:
                img.thumbnail((size['width'], size['height']), Image.ANTIALIAS)
            try:
                img.save(filename, optimize=1)
            except IOError:
                img.save(filename)
예제 #45
0
파일: models.py 프로젝트: ntwuxc/moocng
    def _resize_image(self, filename, size):
        """
        ripped from:
        https://github.com/humanfromearth/django-stdimage/blob/master/stdimage/fields.py

        Resizes the image to specified width, height and force option

        Arguments::

        filename -- full path of image to resize
        size -- dictionary with
            - width: int
            - height: int
            - force: bool
                if True, image will be cropped to fit the exact size,
                if False, it will have the bigger size that fits the specified
                size, but without cropping, so it could be smaller on width
                or height

        """

        WIDTH, HEIGHT = 0, 1
        img = Image.open(filename)
        if (img.size[WIDTH] > size['width'] or
                img.size[HEIGHT] > size['height']):

            #If the image is big resize it with the cheapest resize algorithm
            factor = 1.61803398875
            while (img.size[0] / factor > 2 * size['width'] and
                    img.size[1] * 2 / factor > 2 * size['height']):
                factor *= 2
            if factor > 1:
                img.thumbnail((int(img.size[0] / factor),
                               int(img.size[1] / factor)), Image.NEAREST)

            if size['force']:
                img = ImageOps.fit(img, (size['width'], size['height']),
                                   Image.ANTIALIAS)
            else:
                img.thumbnail((size['width'], size['height']), Image.ANTIALIAS)
            try:
                img.save(filename, optimize=1)
            except IOError:
                img.save(filename)
예제 #46
0
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)
예제 #47
0
def generate_thumbnail(image_url, preserve_ratio=False, size=(220, 165)):
    """Take an image src, generate a thumbnail, return new path"""

    filename = image_url.rsplit('/', 1)[1]
    path_to_read = 'img/' + filename
    path_to_save = "%smain/static/dev/%s" % (ABSOLUTE_PATH, path_to_read)

    if not os.path.isfile(path_to_save):
        img_file = urllib.urlopen(image_url)
        img = StringIO(img_file.read())
        image = Image.open(img)
        if preserve_ratio:
            width = image.size[0]
            height = image.size[1]
            new_height = size[0] * height / width
            size = (size[0], new_height)
        im = ImageOps.fit(image, size, Image.ANTIALIAS)
        im.save(path_to_save)

    return path_to_read
def read_files(folders):
    size = 28, 28
    features_list = []
    for folderpath in folders:
        for root, dirs, files in os.walk(folderpath):
            path = root.split('/')
            for file in files:
                if "and " in file:
#                     print "@@@", os.path.join(root, file)
                    im = Image.open(os.path.join(root, file))
                    imagefit = ImageOps.fit(im, size, Image.ANTIALIAS)
                    features = list(imagefit.getdata())
                    assert_equal(len(features), 784)  
#                     print features
                    if(is_grayscale(features)):
                        features_list.append(features)
        
#     print features_list    
    print "!!!!!!", len(features_list)    
    return features_list
예제 #49
0
    def prepSizedImage(source, width, height):

        hash = XUtils.hash((source.encode(), width, height))
        bucket = "media/temp/" + hash
        basename = os.path.basename(source)
        if os.path.splitext(basename)[1] == "":
            basename = basename + ".png"
        newSource = bucket + "/" + basename

        if not os.path.exists(newSource) or (
                not source.startswith("http")
                and os.stat(source).st_mtime > os.stat(newSource).st_mtime):

            try:
                os.makedirs(bucket)
            except OSError:
                if os.path.isdir(bucket): pass
                else: raise

            image = None

            if source.startswith("http"):
                image = Image.open(
                    StringIO.StringIO(urllib2.urlopen(source).read()))
            else:
                image = Image.open(source)

            baseWidth, baseHeight = image.size
            if height or width:
                if not height: height = width * baseHeight / baseWidth
                if not width: width = height * baseWidth / baseHeight
                if width != baseWidth and height != baseHeight:
                    image = image.convert("RGBA")
                    image = ImageOps.fit(image, (width, height),
                                         Image.ANTIALIAS, 0, (0.5, 0.5))
            else:
                width, height = image.size
            image.save(newSource)

        source = newSource
        return source
예제 #50
0
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()
예제 #51
0
def fit(image, size, method, bleed, centering):
    return ImageOps.fit(image, size, method, bleed, centering)
예제 #52
0
    def _execute_hook(self, im, new_im_width, new_im_height):
        fit_im = ImageOps.fit(im, (int(new_im_width), int(new_im_height)))
        fit_im.format = im.format

        return fit_im
예제 #53
0
파일: ajax.py 프로젝트: Adarel/tweeria
    def resizeImage(self,
                    buffer_filepath,
                    local_filepath,
                    params,
                    cropped_image=False):

        image = Image.open(buffer_filepath)

        width, height = image.size
        imgData = {"width": width, "height": height}

        need_resize = False

        createSmallItemSpell = False
        if "type_of_form" in params and params[
                'type_of_form'] == "create_artwork":
            checkWidth = self.core.MAX_ARTWORK_WIDTH
            checkHeight = self.core.MAX_ARTWORK_HEIGHT

        elif "type_of_form" in params and (
                params['type_of_form'] == "create_item"
                or params['type_of_form'] == "create_spell"):
            checkWidth = self.core.MAX_ITEM_SPELL_WIDTH
            checkHeight = self.core.MAX_ITEM_SPELL_HEIGHT
            createSmallItemSpell = True
        else:
            checkWidth = self.core.MAX_AVA_WIDTH
            checkHeight = self.core.MAX_AVA_HEIGHT

        if width > checkWidth:
            width = checkWidth
            need_resize = True

        if height > checkHeight:
            height = checkHeight
            need_resize = True

        #need_resize = False

        if need_resize:
            if params['type_of_form'] == "create_artwork":
                thumb = ImageOps.fit(cropped_image,
                                     (self.core.THUMB_ARTWORK_WIDTH,
                                      self.core.THUMB_ARTWORK_HEIGHT),
                                     Image.ANTIALIAS)
            else:
                thumb = ImageOps.fit(cropped_image, (width, height),
                                     Image.ANTIALIAS)
            thumb.save(local_filepath + "_fit.png", "PNG")
        elif params['type_of_form'] == "create_artwork":
            thumb = ImageOps.fit(cropped_image,
                                 (self.core.THUMB_ARTWORK_WIDTH,
                                  self.core.THUMB_ARTWORK_HEIGHT),
                                 Image.ANTIALIAS)
            thumb.save(local_filepath + "_fit.png", "PNG")
        else:
            image.save(local_filepath + "_fit.png", "PNG")

        if createSmallItemSpell:
            thumb = ImageOps.fit(cropped_image,
                                 (self.core.THUMB_ITEM_SPELL_WIDTH,
                                  self.core.THUMB_ITEM_SPELL_HEIGHT),
                                 Image.ANTIALIAS)
            thumb_local_filpath = local_filepath + "_thumb.png"
            thumb.save(thumb_local_filpath, "PNG")
        return imgData
예제 #54
0
try:
	widthInt = int(width)
except ValueError:
	respondError( "Parameter width can't be parsed to int")
if widthInt < 10 or widthInt > 600:
	respondError( "Parameter width is out of range 10 to 600")

height  = form.getvalue('height')
if not height:
	respondError( "Parameter height is missing in HTTP request")
try:
	heightInt = int(height)
except ValueError:
	respondError( "Parameter height can't be parsed to int")

if heightInt < 10 or heightInt > 600:
	respondError( "Parameter height is out of range 10 to 600")


# if we got this far then we have good parameter and can read the image and scale and crop
im = Image.open( recipePath + filename)
im = ImageOps.fit( im,( widthInt, heightInt ), Image.NEAREST, 0, (0.5,0.5) )
# looks like I need to save the image so that it can be opened and printede
im.save( cachePath + filename )


# print the image to the output stream
print ("Content-type: image/jpeg\n")
file = open(cachePath + filename, "r")
print file.read()
예제 #55
0
	def image2raw(self, imgfilename):
		im = Image.open(imgfilename)
		if im.size[0] != 256 or im.size[1] != 256:
			im = ImageOps.fit(im, (256,256), Image.ANTIALIAS)
		self.wfile.write(im.tostring())
예제 #56
0
import os, sys
import Image,ImageOps

size = 16, 8
'''
for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(outfile, "JPEG")
        except IOError:
            print "cannot create thumbnail for '%s'" % infile'''
			
for path, subdirs, files in os.walk("./Images/"):
	if(not path.endswith("ConvertedImages")):
		i=0
		for file in files:
			#print path+"/ConvertedImages/"+file
			outfile = path+"/ConvertedImages/"+str(i)+".jpg"
			i += 1
			infile = path+"/"+file
			try:
				im = Image.open(infile)
				#im.resize(size)
				img = ImageOps.fit(im, size, Image.ANTIALIAS)
				img.save(outfile, "JPEG")
			except IOError:
				print "cannot create thumbnail for '%s'" % infile
예제 #57
0
            raise


try:
    image_dir = sys.argv[1]
except:
    print "Please specify a directory"
    exit(1)

files = os.listdir(image_dir)
for file in files:
    if IMAGEEXT.match(file):
        f = os.path.join(image_dir, file)
        print f
        img = Image.open(f)

        # rotate landscape images
        if img.size[0] > img.size[1]:
            img = img.rotate(90)

        # resize and crop the image to fit in 600x800 screen
        img = ImageOps.fit(img, SIZE, Image.ANTIALIAS)

        # convert to grayscale
        img = img.convert('L')

        # save to ./ss directory
        ensuredirs(os.path.join(image_dir, 'ss'))
        fout = os.path.join(image_dir, 'ss', file)
        img.save(fout, "JPEG")
예제 #58
0
def format_image(im):
    pixels = ImageOps.fit(im, (40, 40)).convert('L').getdata()
    return pixels
예제 #59
0
def scale(imagefield, size, method='scale'):
    """
    Template filter used to scale an image
    that will fit inside the defined area.

    Returns the url of the resized image.

    {% load image_tags %}
    {{ profile.picture|scale:"48x48" }}
    """

    # imagefield can be a dict with "path" and "url" keys
    if imagefield.__class__.__name__ == 'dict':
        imagefield = type('imageobj', (object, ), imagefield)

    image_path = resized_path(imagefield.path, size, method)

    if not os.path.exists(image_path):
        try:
            import Image
        except ImportError:
            try:
                from PIL import Image
            except ImportError:
                raise ImportError('Cannot import the Python Image Library.')

        image = Image.open(imagefield.path)

        # normalize image mode
        if image.mode != 'RGB':
            image = image.convert('RGB')

        # parse size string 'WIDTHxHEIGHT'
        width, height = [int(i) for i in size.split('x')]

        # use PIL methods to edit images
        if method == 'scale':
            image.thumbnail((width, height), Image.ANTIALIAS)
            image.save(image_path, FMT, quality=QUAL)

        elif method == 'crop':
            try:
                import ImageOps, ExifTags
            except ImportError:
                from PIL import ImageOps, ExifTags

            ImageOps.fit(image, (width, height),
                         Image.ANTIALIAS).save(image_path, FMT, quality=QUAL)

            try:
                for orientation in ExifTags.TAGS.keys():
                    if ExifTags.TAGS[orientation] == 'Orientation': break
                exif = dict(image._getexif().items())

                if exif[orientation] == 3:
                    image = image.rotate(180, expand=True)
                elif exif[orientation] == 6:
                    image = image.rotate(270, expand=True)
                elif exif[orientation] == 8:
                    image = image.rotate(90, expand=True)

                image.save(image_path, FMT, quality=QUAL)

            except ImportError:
                raise ImportError('Cannot rotate.')

    return resized_path(imagefield.url, size, method)