Exemple #1
0
def resize(im, crop, limit):
    """
    Resize image to limit if limit > 0
    if crop_square, and height and width are within 9 % crop to smaller dimension
    """
    width = im.width
    height = im.height

    if width == height:
        size = width
        if 0 < limit < width:
            size = limit
            im = resizeimage.resize_width(im, size)

    elif width > height:
        size = height
        if 0 < limit < height:
            size = limit
        if crop and (width - height) / width < 0.09:
            im = resizeimage.resize_crop(im, [size, size])
        else:
            im = resizeimage.resize_width(im, size)

    elif height > width:
        size = width
        if limit and width > limit:
            size = limit
        if crop and (height - width) / height < 0.09:
            im = resizeimage.resize_crop(im, [size, size])
        else:
            im = resizeimage.resize_height(im, size)
    return im
Exemple #2
0
    def resize(self, width, height, name='', type='width'):
        output = os.path.join(self.cdir, self.name + '-' + str(width) + 'x' + str(height) + '-' + name + self.ext)

        with open(self.src, 'r+b') as f:
            with Image.open(f) as image:
                if type == 'contain':
                    try:
                        result = resizeimage.resize_cover(image, [width, height])
                    except:
                        tmp = resizeimage.resize_contain(image, [width, height])
                        result = resizeimage.resize_cover(tmp, [width, height])

                elif type == 'height':
                    result = resizeimage.resize_height(image, height, validate=False)
                elif type == 'crop':
                    tmp = resizeimage.resize_contain(image, [width + 150, height + 150])
                    result = resizeimage.resize_crop(tmp, [width, height])
                elif type == 'tcrop':
                    tmp = resizeimage.resize_contain(image, [width, height])
                    result = resizeimage.resize_crop(tmp, [width, height])
                elif type == 'thumbnail':
                    result = resizeimage.resize_thumbnail(image, [width, height])
                else:
                    result = resizeimage.resize_width(image, width, validate=False)

                result.save(output, optimize=True)
                return [output, '[{}x{}] {}'.format(width, height, name), self.name + '-' + str(width) + 'x' + str(height) + '-' + name + self.ext, name]
Exemple #3
0
 def test_can_not_resize_crop_larger_size(self):
     """
     Test that resizing an image with resize_crop
     to a size larger than the original raises an error
     """
     with self._open_test_image() as img:
         with self.assertRaises(ImageSizeError):
             resizeimage.resize_crop(img, (801, 534))
 def test_can_not_resize_crop_larger_size(self):
     """
     Test that resizing an image with resize_crop
     to a size larger than the original raises an error
     """
     with self._open_test_image() as img:
         with self.assertRaises(ImageSizeError):
             resizeimage.resize_crop(img, (801, 534))
Exemple #5
0
def resize(imageName, height = 100, width = 200):
    fd_img = open(imageName, 'r')
    img = Image.open(fd_img)
    img = resizeimage.resize_crop(img, [height, width])
    newName = imageName + '_' + str(height) + '_' + str(width) + '.jpg'
    img.save(newName, img.format)
    fd_img.close()
Exemple #6
0
def get_gray_img(frame, data, is_square, img_width, img_height):
    x, y, w, h = data
    img = Image.fromarray(frame[y:y+h, x:x+w])
    if is_square:
        return resizeimage.resize_cover(img, [img_width, img_height])
    else:
        width_scaled_img = resizeimage.resize_width(img, img_width)
        return resizeimage.resize_crop(width_scaled_img, [img_width, img_height])
def resizing(image_size):
    resized_images = []
    for img in picsDir:
        image = Image.open(rootDir + img)
        image = resizeimage.resize_crop(image, image_size)
        # image.thumbnail(image_size)
        resized_images.append(image)

    return resized_images
Exemple #8
0
def crop_profile_picture(input_file, output_file):
    with open(input_file, "rb") as fd_img:
        img = Image.open(fd_img)
        img = resizeimage.resize_height(img, 200)
        img = resizeimage.resize_crop(img, [112, 200])
        img.save(output_file, img.format)
        fd_img.close()

    return True
Exemple #9
0
def save_cover_image(img, article_slug):
    img_name = f"{article_slug}-cover-image.jpg"
    new_height = int(img.height * (max_width / img.width))
    img = img.resize((max_width, new_height))
    img = resizeimage.resize_crop(img, [1920, 900])
    img.save(f"{static_file_path}{cover_image_path}{img_name}",
             optimize=True,
             quality=65)
    return f"{cover_image_path}{img_name}"
def resize():
    for item in dirs:
        if os.path.isfile(path + item):
            im = Image.open(path + item)
            f, e = os.path.splitext(path + item)
            im = resizeimage.resize_crop(im, [700, 700])
            imResize = im.resize((127, 127), Image.ANTIALIAS)
            imResize.save(f + ' reshaped.png', 'png', quality=90)
            im = plt.imread(f + ' reshaped.png')
            print(im.shape)
 def test_resize_crop(self):
     """
     Test that the image resized with resize_crop
     has the expected size
     """
     with self._open_test_image() as img:
         img = resizeimage.resize_crop(img, [200, 200])
         filename = self._tmp_filename('crop.jpeg')
         img.save(filename, img.format)
         with Image.open(filename) as image:
             self.assertEqual(image.size, (200, 200))
Exemple #12
0
 def test_resize_crop(self):
     """
     Test that the image resized with resize_crop
     has the expected size
     """
     with self._open_test_image() as img:
         img = resizeimage.resize_crop(img, [200, 200])
         filename = self._tmp_filename('crop.jpeg')
         img.save(filename, img.format)
         with Image.open(filename) as image:
             self.assertEqual(image.size, (200, 200))
Exemple #13
0
    def resize(self, width, height, name='', type='width'):
        output = os.path.join(
            self.cdir, self.name + '-' + str(width) + 'x' + str(height) + '-' +
            name + self.ext)

        with open(self.src, 'r+b') as f:
            with Image.open(f) as image:
                if type == 'contain':
                    try:
                        result = resizeimage.resize_cover(
                            image, [width, height])
                    except:
                        tmp = resizeimage.resize_contain(
                            image, [width, height])
                        result = resizeimage.resize_cover(tmp, [width, height])

                elif type == 'height':
                    result = resizeimage.resize_height(image,
                                                       height,
                                                       validate=False)
                elif type == 'crop':
                    tmp = resizeimage.resize_contain(
                        image, [width + 150, height + 150])
                    result = resizeimage.resize_crop(tmp, [width, height])
                elif type == 'tcrop':
                    tmp = resizeimage.resize_contain(image, [width, height])
                    result = resizeimage.resize_crop(tmp, [width, height])
                elif type == 'thumbnail':
                    result = resizeimage.resize_thumbnail(
                        image, [width, height])
                else:
                    result = resizeimage.resize_width(image,
                                                      width,
                                                      validate=False)

                result.save(output, optimize=True)
                return [
                    output, '[{}x{}] {}'.format(width, height, name),
                    self.name + '-' + str(width) + 'x' + str(height) + '-' +
                    name + self.ext, name
                ]
def resize(infolder, outfolder, imagefile, size):
    """
        infolder: folder that input image lives
        outfolder: folder that output image will live
        imagefile: image filename, like img.png
        size: list: [150,150]
    """
    fd_img = open(os.path.join(infolder,imagefile),'r')
    img = Image.open(fd_img)
    img = resizeimage.resize_crop(img, size)
    img.save(os.path.join(outfolder,imagefile), img.format)
    fd_img.close()
def resize(infolder, outfolder, imagefile, size):
    """
        infolder: folder that input image lives
        outfolder: folder that output image will live
        imagefile: image filename, like img.png
        size: list: [150,150]
    """
    fd_img = open(os.path.join(infolder, imagefile), 'r')
    img = Image.open(fd_img)
    img = resizeimage.resize_crop(img, size)
    img.save(os.path.join(outfolder, imagefile), img.format)
    fd_img.close()
Exemple #16
0
def add_background_on_image(pil_image, background_pil):
    """
    Add background on image
    :param pil_image: PIL Image
    :param background_pil: background to add PIL Image
    :return: PIL Image
    """
    background_pil = _resize_to_max(pil_image.size, background_pil)
    background_pil = resize_crop(background_pil, pil_image.size)

    background_pil.paste(pil_image, (0, 0), pil_image)

    return background_pil
def resize_file(csv_file, source_dir, target_dir, target_size, ratio):
    df = pd.read_csv(csv_file)
    for index, row in df.iterrows():
        file_name = row['FileName']

        file_path = os.path.join(target_dir, file_name)
        source_path = os.path.join(source_dir, file_name)

        with open(source_path, 'r+b') as f:
            with Image.open(f) as image:
                width = int(image.width * ratio)
                image = resizeimage.resize_crop(image, [width, width])
                cover = resizeimage.resize_width(image, target_size)

                cover.save(file_path, image.format)
def zoomin_image(im, ratio):
    if len(im.shape) == 3:
        height, width, nChannels = im.shape[:3]
    else:
        height, width = im.shape[:2]
        nChannels = 1

    height_zoom = int(ratio * height)
    width_zoom = int(ratio * width)

    # Note that im is by default a numpy.ndarray, need to be converted to PIL.Image format
    im = Image.fromarray(im)
    im_zoom = im.resize((width_zoom, height_zoom))
    im_zoom = resizeimage.resize_crop(im_zoom, [width, height, nChannels])
    return np.array(im_zoom)
Exemple #19
0
def edit_crop():
    s = request.args.get('s')
    d = s.split('*')
    filename = request.args.get('filename')
    filename_crop = current_app.config['ROOT_DIR'] + filename[0:filename.rfind(".")] + '_crop' + \
                   filename[filename.rfind("."):]

    filename = current_app.config['ROOT_DIR'] + filename
    print(filename)
    print(filename_crop)
    if request.method == 'GET' and s != '':
        with open(filename, 'r+b') as f:
            with Image.open(f) as img:
                img = resizeimage.resize_crop(img, [int(d[0]), int(d[1])])
                img.save(filename_crop, img.format)

    return redirect(('gallery/user'))
def resize():
    '''
    Resize images found in the "large" images directory.
    
    medium: 1200px wide
    small: 300px wide
    '''

    images_directory = os.path.join('static', 'images')

    # First clear out any resizing work we may have done.
    clear_resized_images(images_directory)

    try:
        for entry in os.scandir(images_directory):
            orig_images = os.path.join(images_directory, entry.name, 'large')

            for orig_image in os.scandir(orig_images):
                with open(os.path.join(orig_images, orig_image.name),
                          'r+b') as f:
                    with Image.open(f) as large_image:
                        med_image = resizeimage.resize_width(large_image, 1200)
                        med_image.save(
                            os.path.join(images_directory, entry.name,
                                         'medium', orig_image.name))

                        # small ones need to be a uniform 300px by 199px (WxH) so portrait ones will be center cropped
                        if large_image.height > large_image.width:
                            small_image = resizeimage.resize_width(
                                large_image, 300)
                            small_image = resizeimage.resize_crop(
                                small_image, [300, 199])
                        else:
                            small_image = resizeimage.resize_width(
                                large_image, 300)

                        small_image.save(
                            os.path.join(images_directory, entry.name, 'small',
                                         orig_image.name))

    except OSError as ex:
        raise Exception(
            "Error encountered while trying to resize images. {0}".format(ex))

    return
def create_textures():

    image_dir = '{0}'.format(IMAGE_DIRECTORY)
    style_dir = '{0}'.format(STYLE_DIRECTORY)

    images = sorted(
        [image for image in os.listdir(image_dir) if image not in BLACKLIST])
    styles = sorted(
        [style for style in os.listdir(style_dir) if style not in BLACKLIST])
    #print('Creating Background %s' % images[i])
    content_layer_ids = [4]
    style_layer_ids = list(range(13))
    for i in tqdm(range(len(images))):
        vgg16.maybe_download()
        #print (images[i], labels[i], backgrounds[i])
        style_current = random.choice(styles)
        print("current style " + style_current)
        content_image = Image.open('{0}/{1}'.format(IMAGE_DIRECTORY,
                                                    images[i]))
        style_image = Image.open('{0}/{1}'.format(STYLE_DIRECTORY,
                                                  style_current))
        style_image = resizeimage.resize_crop(style_image, [WIDTH, HEIGHT])
        iterations = random.randint(15, 25)
        print("ok")
        #print (list(im_bk.getdata()))
        content_image = np.float32(content_image)
        style_image = np.float32(style_image)
        #%%time
        img = style_transfer(
            content_image=content_image,
            style_image=style_image,
            content_layer_ids=content_layer_ids,
            style_layer_ids=style_layer_ids,
            weight_content=1.5,
            weight_style=10.0,
            weight_denoise=0.3,
            num_iterations=iterations,  #60
            step_size=10.0)
        print("image created")
        save_image(img, 'results/' + images[i] + ".png")
Exemple #22
0
    def resize_image(self):
        name, extension = os.path.splitext(self.file.name)
        extension = extension.lower()
        pil_image_obj = Image.open(self.file)

        new_image = resizeimage.resize_width(pil_image_obj, self.banner.width)
        new_image = resizeimage.resize_crop(
            new_image, [self.banner.width, self.banner.height])

        if extension in ['.jpeg', '.jpg']:
            format_type = 'JPEG'
        elif extension == '.png':
            format_type = 'PNG'

        new_image_io = BytesIO()
        new_image.save(new_image_io, format=format_type)
        temp_name = self.file.name

        self.file.delete(save=False)

        self.file.save(temp_name,
                       content=ContentFile(new_image_io.getvalue()),
                       save=False)
Exemple #23
0
def chiffrementImage(image_claire, key):
    (largeur, hauteur) = image_claire.size  # get size image
    while largeur % 3 != 0:  # ajouter des pixels si la taille en longeur ne corespond pas a la cle de chiffrement
        image_claire = resizeimage.resize_crop(image_claire,
                                               (largeur + 1, hauteur))
        image_claire = image_claire.convert("RGB")
        largeur = largeur + 1

    # get image array
    imageArray = np.asarray(image_claire)
    imageArray.setflags(write=True)

    # get color array
    rouge = np.asarray(imageArray[:, :, 0])
    vert = np.asarray(imageArray[:, :, 1])
    bleu = np.asarray(imageArray[:, :, 2])

    # parcourir pour crypté
    for x in range(hauteur):
        for y in range(0, largeur, 3):
            # part 1 rouge
            P1rouge, P2rouge, P3rouge = getP(key, rouge, x, y)
            # part 2 vert
            P1vert, P2vert, P3vert = getP(key, vert, x, y)
            # part 3 bleu
            P1bleu, P2bleu, P3bleu = getP(key, bleu, x, y)
            # part save changement
            imageArray[x, y] = (P1rouge, P1vert, P1bleu)
            imageArray[x, y + 1] = (P2rouge, P2vert, P2bleu)
            imageArray[x, y + 2] = (P3rouge, P3vert, P3bleu)

    # get image crypte
    image_crypte = img.fromarray(imageArray)
    image_crypte = image_crypte.convert("RGB")

    return image_crypte
import pandas as pd
import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
import os
from PIL import Image
from resizeimage import resizeimage

train_image_list_parasitized = os.listdir('./train/Parasitized/')
# print(train_image_list_parasitized)
for image in train_image_list_parasitized:
    full_path = './train/Parasitized/' + image
    print(full_path)
    save_path = './train/Parasitized/done/' + image
    if ('.png' in full_path):
        #     img = cv2.imread(full_path)
        #     with open(full_path, 'r+b') as f:
        #         with Image.open(f) as img:
        #             cover = resizeimage.resize_cover(img, [100, 100])
        #             cover.save(full_path, img.format)
        #     resized_img = cv2.resize(img, (100, 100), interpolation=(cv2.INTER_AREA))
        fd_img = open(full_path, 'r')
        img = Image.open(fd_img)
        img = resizeimage.resize_crop(img, [120, 120])
        img.save(save_path, img.format)
        fd_img.close()
Exemple #25
0
    #if os.path.isdir(SAVE_DIR):
    #    shutil.rmtree(SAVE_DIR)

    #os.mkdir(SAVE_DIR)

    files = glob.glob(SRC_DIR + str(dirid+1) + "/*.png")

    fileid = 1

    for file in files:
        with open(file, 'r+b') as f:
            with Image.open(f) as img:
                w, h = img.size

                if w==IMAGE_SIZE and h==IMAGE_SIZE:
                    pass
                else:
                    if w < h:
                        img = resizeimage.resize_width(img, IMAGE_SIZE)
                    else:
                        img = resizeimage.resize_height(img, IMAGE_SIZE)

                    img = resizeimage.resize_crop(img, [IMAGE_SIZE, IMAGE_SIZE])

                if fileid > 80:
                    img.save(TEST_DIR + '/' +str(dirid) + '_' + str(fileid) + '.png', img.format)
                else:
                    img.save(TRAIN_DIR + '/' +str(dirid) + '_' + str(fileid) + '.png', img.format)
                fileid = fileid + 1
# replace eg.json with your own file name
with open('eg.json', encoding='utf-8') as file:
    data = file.read()

json_data = json.loads(data)

bot = Bot()

bot.login(username=config.USERNAME,
          password=config.PASSWORD)

for j_data in json_data.items():
    caption = j_data[1]['caption']

    for image_path in (j_data[1]['images']):
        print("Caption:", caption)
        print(image_path)
        response = requests.get(image_path)
        file = open("1.jpg", "wb")
        file.write(response.content)
        file.close()
        fd_img = open('1.jpg', 'rb')
        img = Image.open(fd_img)
        img = resizeimage.resize_crop(img, [1080, 1080])
        img.save('1.jpg', img.format)
        fd_img.close()
        bot.upload_photo('1.jpg', caption=caption)
        os.remove("1.jpg.REMOVE_ME")
    print()
if is_valid:
    with Image.open('/home/antz/0Python/image/File.jpg') as image:
        resizeimage.resize_cover.validate(image, [200, 100], validate=False)
        cover = resizeimage.resize_cover(image, [200, 100])
        cover.save('test-image-cover1.jpeg', image.format)

##########################################################
# Crop an image with a 200x200 cented square:
##########################################################
from PIL import Image
from resizeimage import resizeimage

fd_img = open('/home/antz/0Python/image/File.jpg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_crop(img, [200, 200])
img.save('test-image-crop2.jpeg', img.format)
fd_img.close()

##########################################################
# Resize and crop (from center) the image so that it covers 
# a 200x100 rectangle
##########################################################
from PIL import Image
from resizeimage import resizeimage

fd_img = open('/home/antz/0Python/image/File.jpg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_cover(img, [200, 100])
img.save('test-image-cover3.jpeg', img.format)
fd_img.close()
Exemple #28
0
def rand_crop_real(img):
    ratio = (random.randint(6, 9) / 10)
    w, h = int(img.width * ratio), int(img.height * ratio)
    img = resizeimage.resize_crop(img, [w, h])
    return (img)
Exemple #29
0
from PIL import Image
from resizeimage import resizeimage
import matplotlib.pyplot as plt

image_path = 'deconvnet/images/tesla_fat_3ch.png'

img_pil_read = Image.open(image_path)  # original image
img_pil_resized = img_pil_read.resize((224, 224), Image.ANTIALIAS)

img_crop_resized = resizeimage.resize_crop(img_pil_read, [224, 224])
img_cover_resized = resizeimage.resize_cover(img_pil_read, [224, 224])
img_contain_resized = resizeimage.resize_contain(img_pil_read, [224, 224])
img_thumbnail_resized = resizeimage.resize_thumbnail(img_pil_read, [224, 224])

# image show
fig = plt.figure()
ax1 = fig.add_subplot(231)
plt.imshow(img_pil_read)
plt.title('origin')
ax2 = fig.add_subplot(232)
plt.imshow(img_pil_resized)
plt.title('PIL resize')
ax3 = fig.add_subplot(233)
plt.imshow(img_crop_resized)
plt.title('crop')
ax4 = fig.add_subplot(234)
plt.imshow(img_cover_resized)
plt.title('cover')
ax5 = fig.add_subplot(235)
plt.imshow(img_contain_resized)
plt.title('contain')
Exemple #30
0
def save_image_with_resize(path: str, im: Image):
    make_path(path)
    im.thumbnail([IMSIZE, IMSIZE], Image.ANTIALIAS)
    im = resizeimage.resize_crop(im, [IMSIZE, IMSIZE])
    #print(f"Scaving scaled image at: {path}")
    im.save(path, im.format)
Exemple #31
0
# This script accepts two command line arguments which are the filenames of the images to blended together.
# If the images are not of the same size, the larger image will be cropped to fit into the smaller image
# sample way to usage :
# python image_blend.py 1.png, 2.png

from PIL import Image
from resizeimage import resizeimage
import sys

arguments = sys.argv
arguments.pop(0)
first_image, second_image = arguments
background = Image.open(first_image)
overlay = Image.open(second_image)

background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

if background.size != overlay.size:
    new_size = min(background.size, overlay.size)

    if new_size == overlay.size:
        background = resizeimage.resize_crop(background, list(new_size))
    else:
        overlay = resizeimage.resize_crop(overlay, list(new_size))

new_img = Image.blend(background, overlay, 0.5)
new_img.save("blended.png", background.format)
Exemple #32
0
def make_image_square(image_file_name):
    image = Image.open(image_file_name)
    x, y = image.size
    size = min(x, y, 1080)
    image = resizeimage.resize_crop(image, [size, size])
    image.save(image_file_name, image.format)
Exemple #33
0
          password=config.PASSWORD)

for j_data in json_data:
    caption = j_data['caption']

    for image_path in (j_data['images']):
        print("Caption:", caption)
        print(image_path)
        response = requests.get(image_path)
        filename = str(random.randint(0,10000)) + '.jpg'
        file = open(filename, "wb")
        file.write(response.content)
        file.close()
        fd_img = open(filename, 'rb')
        img = Image.open(fd_img)
        width, height = img.size
        # If image width is greater than 1080, just upload it
        if(width > 1080): 
          img = resizeimage.resize_crop(img, [width, width])
          img.save(filename, img.format)
          fd_img.close()
        #If image width is not equal to height crop image to match width x width(as height)
        if(width != height):
            size = width, width
            img = resizeimage.resize_crop(img, size)
            img.save(filename, img.format)
            fd_img.close()
        bot.upload_photo(filename, caption=caption)
        os.remove(filename+".REMOVE_ME")
    print()
    def get_image(self, rpc_request):

        try:
            url = rpc_request.try_get_value_from_params('url', str)
            access_token = rpc_request.try_get_value_from_params(
                'access_token', str)
            network_type = rpc_request.try_get_value_from_params(
                'network_type', str)

        except Exception as ex:
            return HttpResponse(ex, status=502)

        try:
            height = rpc_request.try_get_value_from_params('height', int)
            width = rpc_request.try_get_value_from_params('width', int)
        except:
            height = None
            width = None

        try:
            self.check_auth_service.check_auth(access_token=access_token)
        except RPCException as ex:
            return HttpResponse(ex, status=401)

        if network_type == NetworkTypes.YAMMER.value:

            file_downloader = urllib3.PoolManager()
            download_response = file_downloader.request(
                'GET',
                url=url,
                headers={
                    "Authorization":
                    "Bearer %s" % self.yammer_service.get_access_token(),
                })

            if download_response.status == 200:
                file_data = download_response.data

                if height != None and width != None:

                    try:
                        image = Image.open(io.BytesIO(file_data))
                    except:
                        image = None

                    if image != None:
                        image = resizeimage.resize_crop(image, [width, height])
                        image_byttes = io.BytesIO()
                        image.save(image_byttes, format='JPEG')
                        file_data = image_byttes.getvalue()

                response = HttpResponse(file_data,
                                        content_type='application/file')
                response['Content-Disposition'] = 'attachment; filename=attach'

                return response
            else:
                return HttpResponse('Не удалось загрузить изображение',
                                    status=502)
        else:
            return HttpResponse('Тип соц сети не поддерживается', status=502)