Exemplo n.º 1
0
def tweet_image(message):
    font = ImageFont.truetype(font="PlainPensle_BoldItalic.ttf", size=75)
    W, H = (1280, 720)
    w, h = font.getsize(message)
    img = Image.new('RGB', (W, H), color=(240, 226, 179))
    img_w, img_h = img.size

    draw = ImageDraw.Draw(img)
    draw.text(((W - w) / 2, 585), message, font=font, fill='black')

    img2 = Image.open(
        os.path.join("C:/Users/Matthew/PycharmProjects/TwitterBot/botImages",
                     file), 'r')
    img2 = img2.resize((500, 500))

    img3 = img2.convert("RGBA")
    img3.resize((500, 500))

    offset = (390, 65)
    img.paste(img3, offset, mask=img3)

    img.save('temp.png')
    os.remove(
        os.path.join("C:/Users/Matthew/PycharmProjects/TwitterBot/botImages",
                     file))
    api.update_with_media('temp.png', status=message)
Exemplo n.º 2
0
    def __pic2array(self, filepath):
        if self.__type == 'directory':
            image = Image.open(filepath)
        elif self.__type == 'zip':
            __relativepath = self.__relativepath(filepath)
            image = Image.open(self.__archive.open(self.__archive.getinfo(__relativepath)))
        else:
            raise Exception("Unknown type")

        if self.__grayscale:
            return numpy.asarray(image.convert('L').resize((self.__width, self.__height)))
        else:
            raise Exception("loading image except for grayscale not supported yet...")
Exemplo n.º 3
0
def scanline(array):
    '''creates a scanline effect akin to those on old arcade machines and/or old screens
    :param The image as an array:
    :return The image:
    '''
    w = len(array)
    h = len(array[0])
    new_img = Image.new("RGBA", (w, h), "black")  #makes a new blank blue image
    big_pixels = [[1 for _ in range(int(h / 2))] for _ in range(int(w / 2))]
    for i in range(
            0, w,
            2):  #Iterates through each pixel's colors and modifies accordingly
        for j in range(0, h, 2):
            if (i != w - 1 and j != h - 1):
                pixel0 = array[i][j]
                pixel1 = array[i + 1][j]
                pixel2 = array[i][j + 1]
                pixel3 = array[i + 1][j + 1]
                big_pixel_array = [pixel0, pixel1, pixel2, pixel3]
                red = 0
                green = 0
                blue = 0
                for pixel in big_pixel_array:
                    red = red + pixel[0]
                    green = green + pixel[1]
                    blue = blue + pixel[2]
                red = int(red / 4)
                green = int(green / 4)
                blue = int(blue / 4)
                big_pixel = (red, green, blue)
                new_img.putpixel((i, j), big_pixel)
    return new_img
Exemplo n.º 4
0
def getImage():
    '''Asks the user for the image
    :return the image:
    '''
    img_string = imageOpen.prompt_and_get_file_name()
    img = Image.open(img_string)
    return img
Exemplo n.º 5
0
def select_image(index):
    # Disable scientific notation for clarity
    np.set_printoptions(suppress=True)

    # Load the model
    model = tf.contrib.lite.Interpreter(model_path="model_unquant.tflite")

    # Create the array of the right shape to feed into the keras model
    # The 'length' or number of images you can put into the array is
    # determined by the first position in the shape tuple, in this case 1.
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)

    # Replace this with the path to your image
    image = Image.open('image' + str(index) + '.jpg')

    #resize the image to a 224x224 with the same strategy as in TM2:
    #resizing the image to be at least 224x224 and then cropping from the center
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)

    #turn the image into a numpy array
    image_array = np.asarray(image)

    # display the resized image
    image.show()

    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1

    # Load the image into the array
    data[0] = normalized_image_array

    # run the inference
    prediction = model.predict(data)
    print(prediction)
Exemplo n.º 6
0
def is_valid_image_old(path):
    img = Image.open(path)
    try:
        img.verify()
        return img.format in ['JPEG', 'JPEG2000', 'PNG', 'GIF']
    except Exception:
        return False
Exemplo n.º 7
0
def avhash(im):
    if not isinstance(im, Image.Image):
        im = Image.open(im)
    im = im.resize((8, 8), Image.ANTIALIAS).convert('L')
    avg = reduce(lambda x, y: x + y, im.getdata()) / 64.
    return reduce(lambda x, (y, z): x | (z << y),
                  enumerate(map(lambda i: 0
                                if i < avg else 1, im.getdata())), 0)
Exemplo n.º 8
0
def main():
    im = Image.open('dead_parrot.jpg')  # Can be many different formats.
    pix = im.load()
    print
    im.size  # Get the width and hight of the image for iterating over
    print
    pix[x, y]  # Get the RGBA Value of the a pixel of an image
    pix[x, y] = value  # Set the RGBA Value of the image (tuple)
    im.save('alive_parrot.png')  # Save the modified pixels as .png
Exemplo n.º 9
0
def calculate_image_size(image):
    """Calculates width and height of image in pixels.

    Args:
        image as string (path to image).
    Returns:
        tuple (int image width in pixels, int image height in pixels).
    """
    img = Image.open(image)  # Pillow Image Class Method (open).
    return img.size  # Pillow Image Class Attribute (size).
Exemplo n.º 10
0
    def save(self, *args, **kwargs):
        """
        Create slug based on title

        If a zip file is uploaded, extract images from it and add
        them to the gallery.
        Removes zip file afterwards
        """
        self.slug = slugify(self.title)

        super(BaseGallery, self).save(*args, **kwargs)
        if self.zip_import:
            zip_file = ZipFile(self.zip_import)
            for name in zip_file.namelist():
                data = zip_file.read(name)
                try:
                    # backwards compatibile with PIL
                    from Pillow import Image
                    image = Image.open(BytesIO(data))
                    image.load()
                    image = Image.open(BytesIO(data))
                    image.verify()
                except ImportError:
                    pass
                except:
                    continue
                name = os.path.split(name)[1]
                # This is a way of getting around the broken nature of
                # os.path.join on Python 2.x. See also the comment below.
                if isinstance(name, bytes):
                    encoding = charset_detect(name)['encoding']
                    tempname = name.decode(encoding)
                else:
                    tempname = name

                # A gallery with a slug of "/" tries to extract files
                # to / on disk
                slug = self.slug if self.slug != "/" else ""
                path = os.path.join(UPLOAD_DIR, slug, tempname)
                saved_path = default_storage.save(path, ContentFile(data))
                self.images.create(file=saved_path)
            zip_file.close()
            self.zip_import.delete(save=True)
Exemplo n.º 11
0
def modImage(array, mod="", threshold=100):
    '''takes an array of an image and modifies the image based on parameters
    :param An array of integers coresponding to an image:
    :param A modifier for what operation will be performed on the pixels:
    :param A threshold for some operations:
    :returns An image made from the modified array'''
    w = len(array)
    h = len(array[0])
    new_img = Image.new("RGBA", (w, h), "blue")  #makes a new blank blue image
    for i in range(
            w):  #Iterates through each pixel's colors and modifies accordingly
        for j in range(h):
            red = array[i][j][0]
            green = array[i][j][1]
            blue = array[i][j][2]
            #Chooses formula based on given parameter
            if mod == "sepia":
                '''Uses Formula for Sepia'''
                new_red = int((red * 0.393) + (green * 0.796) + (blue * 0.189))
                new_green = int((red * 0.349) + (green * 0.686) +
                                (blue * 0.161))
                new_blue = int((red * 0.272) + (green * 0.534) +
                               (blue * 0.131))
            elif mod == "greyscale":
                '''Uses Luminosity Formula for Greyscale'''
                new_red = int((red * 0.21) + (green * 0.72) + (blue * 0.07))
                new_green = int((red * 0.21) + (green * 0.72) + (blue * 0.07))
                new_blue = int((red * 0.21) + (green * 0.72) + (blue * 0.07))
            elif mod == "dog":
                new_rgb = dogVision(red, green, blue)
                new_red = new_rgb[0]
                new_green = new_rgb[1]
                new_blue = new_rgb[2]
            elif mod == "dalton":
                new_rgb = daltonize(red, green, blue)
                new_red = new_rgb[0]
                new_green = new_rgb[1]
                new_blue = new_rgb[2]
            elif mod == "lighten":
                new_red = int(red + threshold)
                new_green = int(green + threshold)
                new_blue = int(blue + threshold)
            elif mod == "darken":
                '''Decreases each color by given threshold'''
                new_red = int(red - threshold)
                new_green = int(green - threshold)
                new_blue = int(blue - threshold)
            else:
                new_red = red
                new_green = green
                new_blue = blue

            new_img.putpixel((i, j), (new_red, new_green, new_blue))
    return new_img
Exemplo n.º 12
0
	def create_thumbnail(self, size, force_crop=False):
		""" Creates a thumbnail for an image at the specified size """
	
		if not size.auto_size:
			try:
				crop = self.get_crop(size)
				
				cropped_image = utils.create_cropped_image(
					self.image.path, 
					crop.crop_x, 
					crop.crop_y, 
					crop.crop_w, 
					crop.crop_h
				)
			except Crop.DoesNotExist:
				# auto-crop if no crop is defined
				cropped_image = pil.open(self.image.path)
		else:
			cropped_image = pil.open(self.image.path)
		
		self.rescale(cropped_image=cropped_image, size=size, force_crop=force_crop)
Exemplo n.º 13
0
def handle_uploaded_file(f, name=None):
    if name is None: name = str(f)
    full_path = os.path.join(BASE_DIR, 'static', 'uploads', name)
    with open(full_path, 'w+b') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
    im = Image.open(full_path)
    img = im.resize((250, 250), Image.ANTIALIAS)
    imgIcon = im.resize((50, 50), Image.ANTIALIAS)
    img.save(full_path, 'PNG')
    imgIcon.save(full_path + 'tiny', 'PNG')
    return full_path
Exemplo n.º 14
0
def image_data(filename: str):
    """ return image data for filename """
    try:
        im = Image.open(filename)
    except IOError:
        print("failed to identify", filename)
    else:
        print("image format:", im.format)
        print("image mode:", im.mode)
        print("image size:", im.size)
        if "description" in im.info:
            print("image description:", im.info["description"])
Exemplo n.º 15
0
def make_thumbnail(old_path, new_path, f, w, h, quality):
    path = old_path + '/' + f
    # convert('RGB')这个必须加上, 否则可能会报错: cannot write mode P as JPEG
    icon = Image.open(path).convert('RGB')
    width, height = icon.size
    print width, height
    # 只切高度大于宽度的图片, 宽度大于高度的图片复制到另一个目录
    if width < height:
        icon = icon.resize((500, int(500 * height / width)), Image.ANTIALIAS)
    else:
        icon = icon.resize((int(500 * width / height), 500), Image.ANTIALIAS)
    icon = icon.crop((0, 0, int(w), int(h)))
    print new_path + '/' + f
    icon.save(new_path + '/' + f, 'jpeg', quality=quality)
Exemplo n.º 16
0
 def get_merge_image(self, image_mix, location_list):
     im = image.open(image_mix)
     im_list_upper = []
     im_list_down = []
     for location in location_list:
         if location['y'] == -58:
             im_list_upper.append(
                 im.crop((abs(location['x']), 58, abs(location['x']) + 10,
                          166)))
         if location['y'] == 0:
             im_list_down.append(
                 im.crop(
                     (abs(location['x']), 0, abs(location['x']) + 10, 58)))
     new_im = image.new('RGB', (260, 116))
     x_offset = 0
     for im in im_list_upper:
         new_im.paste(im, (x_offset, 0))
         x_offset += im.size[0]
     x_offset = 0
     for im in im_list_down:
         new_im.paste(im, (x_offset, 58))
         x_offset += im.size[0]
     return new_im
Exemplo n.º 17
0
    def convert_dir(in_dir, out_dir):

        if not os.path.exists(out_dir):
            os.system("mkdir -p " + out_dir)

        for img_file in tqdm.tqdm(os.listdir(in_dir)):
            img_path = os.path.join(in_dir, img_file)
            r_image = Image.open(img_path)

            c_image = ImageProcessor.resize_file(
                r_image, 32, 32
            ).convert("RGBA")
            out_path = os.path.join(out_dir, img_file)
            c_image.save(out_path.split(".")[0] + ".png")
Exemplo n.º 18
0
def create_cropped_image(path=None, x=0, y=0, width=0, height=0):
	""" 
		Crop image given a starting (x, y) position and a width and height of the cropped area 
	"""
	
	if path is None:
		raise ValueError("A path must be specified")

	img = Image.open(path)
	img.copy()
	img.load()
	img = img.crop((x, y, x + width, y + height))
	img.load()
	
	return img
Exemplo n.º 19
0
    def is_img_uniform_size(self, img_content):
        """
        判断图片格式大小是否符合要求

        :param img_content: Stream2bin 2进制流文件

        :return: Boole True/False
        """
        try:
            img = Image.open(io.BytesIO(img_content))
        except:
            print 'Image.open io.BytesIO failed'
            return
        height, width = img.size
        img_flag = True
        if height < 150 or width < 150:
            img_flag = False
        return img_flag
Exemplo n.º 20
0
    def is_img_uniform_size(self, img_content, heigth=150, width=150):
        """
        判断图片格式大小是否符合要求

        :param img_content: Stream2bin 2进制流文件

        :return: Boole True/False
        """
        try:
            img = Image.open(io.BytesIO(img_content))
        except:
            print('Image.open io.BytesIO failed')
            return
        img_h, img_w = img.size
        img_flag = True
        if img_h < heigth or img_w < width:
            img_flag = False
        return img_flag
Exemplo n.º 21
0
        def _dump_image(x):
            (index, p_list) = x
            w_dir = os.path.join(out_dir, str(index))

            if not os.path.exists(w_dir):
                os.system("mkdir -p " + w_dir)

            out_list = []
            for r_path in p_list:
                name = ("-".join(r_path.split("-")[1:])).replace("/", "$")
                w_path = os.path.join(w_dir, name)

                image = Image.open(r_path)
                image.save(w_path)

                out_list.append(w_path)

            return out_list
def dd_helper(image, layer, iterations, lr):

    input = Variable(preprocess(image).unsqueeze(0).cuda(), requires_grad=True)
    vgg.zero_grad()
    for i in range(iterations):
        #         print('Iteration: ', i)
        out = input
        for j in range(layer):
            out = module_list[j + 1](out)
        loss = out.norm()
        loss.backward()
        input.data = input.data + lr * input.grad.data

    input = input.data.squeeze()
    input.transpose_(0, 1)
    input.transpose_(1, 2)
    input = np.clip(deprocess(input), 0, 1)
    im = Image.fromarray(np.uint8(input * 255))
    return im
Exemplo n.º 23
0
	def clean(self):
		""" Additional file validation for saving """
	
		if self.image:
			# Check for valid file extension
			if os.path.splitext(self.image.name)[1] == '':
				raise ValidationError("Please make sure images have file extensions before uploading")
		
			# Check for valid file
			try:
				pil_image = pil.open(self.image)
			except:
				raise ValidationError("Unable to open image file")
			
			# Check for minimum size requirement 
			if self.validate_image_size:
				for size in self.size_set.size_set.all().order_by("-width"):
					if size.width > pil_image.size[0] or size.height > pil_image.size[1]:
						raise ValidationError("Uploaded image (%s x %s) is smaller than a required thumbnail size: %s" % (pil_image.size[0], pil_image.size[1], size))
						
		return super(Image, self).clean()
Exemplo n.º 24
0
def reflect(array, axis="x"):
    ''' reflects the image over the selected axis
    :param The image array:
    :param The axis to reflect the image upon:
    :return The new Image:
    '''
    w = len(array)
    h = len(array[0])
    new_img = Image.new("RGBA", (w, h), "blue")
    for i in range(w):
        for j in range(h):
            '''swaps the pixels around in desired way'''
            red = array[i][j][0]
            green = array[i][j][1]
            blue = array[i][j][2]
            if axis == "x":
                new_img.putpixel((-i, j)(red, green, blue))
            elif axis == "y":
                new_img.putpixel((i, -j)(red, green, blue))
            else:
                new_img.putpixel((j, i), (red, green, blue))
    return new_img
Exemplo n.º 25
0
    def __getitem__(self, idx):
        # load the image as a PIL Image

        img_dict = self.obj['images'][idx]
        image = Image.open(img_dict['file_name'])

        w, h = img_dict['width'], img_dict['height']
        img_id = img_dict['id']

        # load the bounding boxes as a list of list of boxes
        # in this case, for illustrative purposes, we use
        # x1, y1, x2, y2 order.
        anns = [ann for ann in obj['annotations'] if ann['image_id'] == img_id]

        boxes = [ann['bbox'] for ann in anns]
        boxes = [[x[1], x[0], x[3], x[2]] for x in boxes]

        labels = torch.tensor([ann['category_id'] for ann in anns])

        masks = [ann['segmentation'] for ann in anns]

        for i, obj in enumerate(masks):
            for j, poly in enumerate(obj):
                for k in range(0, len(poly), 2):
                    masks[i][j][k], masks[i][j][k + 1] = poly[k + 1], poly[k]

        # create a BoxList from the boxes
        boxlist = BoxList(boxes, image.size, mode="xyxy")
        # add the labels to the boxlist
        boxlist.add_field("labels", labels)
        boxlist.add_field("masks", SegmentationMask(masks, (w, h),
                                                    mode='poly'))

        if self.transforms:
            image, boxlist = self.transforms(image, boxlist)

        # return the image, the boxlist and the idx in your dataset
        return image, boxlist, idx
Exemplo n.º 26
0
def main():
    username = request.form['username']
    print(username)
    search_filter = "(&(cn=" + username + ")"

    os.environ.setdefault('DJANGO_SETTINGS_MODULE',
                          'panoramic_trekking_app.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?") from exc
    execute_from_command_line(sys.argv)

    #Open image using Image module
    im = Image.open("images/cuba.jpg")
    #Show actual Image
    im.show()
    #Show rotated Image
    im = im.rotate(45)
    im.show()
Exemplo n.º 27
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#' a test module '
__author__='ZhangLei'
#类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名
#类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc等
#定义为私有的函数
def _private_1(name):
    return 'Hello, %s' % name

def _private_2(name):
	return "Hello,%s" % name;

def greeting(name):
	if(len(name) > 3):
		return _private_1(name);
	else:
		return _private_2(name);

print(greeting("hello"))
#模块
#安装模块
#pip install Pillow
from Pillow import Image;
im = Image.open("test.png");
print(im.format,im.size,im.mode);
im.thumbnail(200,100);
im.save("test_thumbnail.jpg","JPEG");
import numpy as np
#from PIL import Image
from Pillow import Image

from timeit import default_timer as timer
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from ModelLoader import ModelLoader
from PostProcessor import PostProcessor
from preprocess import PreProcessor
import json

model_loader = ModelLoader()
img = Image.open('/home/bilal/Downloads/foto_van_yosra1.jpg')
# print("---------------------------------")
# print("0 for tinyYolo")
# val = input("give your neural network architecture type: ")

preprocessor = PreProcessor(0, img)
img_data = preprocessor.preprocess()

# print("---------------------------------------------")
# load a simple model
session = model_loader.load_session(1)
begin = timer()

# see the input name and shape
input_name = session.get_inputs()[0].name
"""# print("input name = ", input_name)

input_shape = session.get_inputs()[0].shape
Exemplo n.º 29
0
from Pillow import Image
import glob, os

for infile in glob.glob('c:/Users/guest/Desktop/cards/*.jpg'):
    source = Image.open(infile)
    o1 = source.crop((85, 20, 772, 1009))
    o2 = source.crop((771, 20, 1458, 1009))
    o_path = 'c:/Users/guest/Desktop/o_cards/'
    name = os.path.basename(infile)
    o1.save(o_path + name + ".card1.jpg")
    o2.save(o_path + name + ".card2.jpg")
Exemplo n.º 30
0
    time_start = time.time()
    # Data descramblng
    for idx in range(rx_data_size):
        rx_data_buff[idx] = rx_data_buff[idx] ^ SCRAMBLE_SEQ

    # Write data to file
    with open(TEMP_FILE_PATH, 'wb') as temp_file:
        temp_file.write(rx_data_buff[0:rx_data_size])

    # Format and vizualize data
    try:
        rx_data_img = imageio.imread(TEMP_FILE_PATH).astype(np.uint8)

        if rx_data_img.ndim == 2:
            plt.imshow(rx_data_img, cmap='gray')
        else:
            plt.imshow(rx_data_img)
        plt.show()
        plt.pause(0.001)

    except:
        print('RX DATA CORRUPT ...')

    image = Image.open(TEMP_FILE_PATH)
    image.show
    #os.system('gpicview -single-window %s &' % TEMP_FILE_PATH)

    time_elapsed = (time.time() - time_start)
    print('time for image plot %f ' % time_elapsed)
def load_image(path):
    image = Image.open(path)
    plt.imshow(image)
    plt.title('Image loaded successfully')
    return image
Exemplo n.º 32
0
    def save(self, *args, **kwargs):

        changed_image = self.content != self.__original_image

        if not self.id and not self.pub_date:
            self.pub_date = datetime.datetime.today()

        crop_original = kwargs.get('crop_original', False)

        super(MediaContent, self).save(*args, **kwargs)
        self.mimetype = mimetypes.guess_type(self.content.path)[0]

        if self.mimetype:
            content_type = self.mimetype.replace('/', '_')
        else:
            # assume everything else is text/plain
            content_type = 'text_plain'

        i = self.content.name.rindex('/')
        thumbnail = u'%sthumbnail_%s' % (unicode(
            self.content.name[:i + 1]), unicode(self.content.name[i + 1:]))
        gallery = u'%sgallery_%s' % (unicode(
            self.content.name[:i + 1]), unicode(self.content.name[i + 1:]))
        orig = self.content.name

        if (not self.thumbnail or not self.gallery
                or changed_image) and content_type.split('_')[0] == 'image':
            img_path = self.content.path

            if content_type == 'image_svg+xml':
                try:
                    from nebula.mediacontent import svg_to_png
                    svg_to_png.convert(img_path, svg_to_png.new_name(img_path))
                    img_path = svg_to_png.new_name(img_path)
                    self.content.name = self.content.name[:
                                                          -3] + self.content.name[
                                                              -3:].replace(
                                                                  'svg', 'png')
                except:
                    pass

            image = Image.open(img_path)
            image = convert_to_rgb(image)
            image = crop_aspect(image, ratio=1.0)

            # hace el thumb
            image_thumb = resize(image.copy(), size=self.get_sizes()['thumb'])
            image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail))
            self.thumbnail = thumbnail

            # guarda la imagen para gallery
            image_gallery = resize(image.copy(),
                                   size=self.get_sizes()['gallery'])
            image_gallery.save(os.path.join(settings.MEDIA_ROOT, gallery))
            self.gallery = gallery

            # guarda la imagen al tamaño máximo
            if crop_original:
                image_normal = resize(image.copy(),
                                      size=self.get_sizes()['normal'])
                image_normal.save(os.path.join(settings.MEDIA_ROOT, orig))

        elif (not self.thumbnail or not self.gallery
              or changed_image) and content_type == 'application_pdf':

            # Crea una imagen de la primer pagina de un PDF
            from subprocess import call

            cmd = "gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
                    -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \
                    -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 \
                    -sOutputFile=%(fileout)s %(filein)s"

            filein = os.path.join(settings.MEDIA_ROOT, self.content.name)
            filejpg = self.content.name[:-3] + self.content.name[-3:].replace(
                'pdf', 'jpg')
            fileout = os.path.join(settings.MEDIA_ROOT, filejpg)

            if not os.access(filein, os.R_OK):
                raise 'not access %s' % filein

            files = {
                'filein': filein.replace(' ', '\ '),
                'fileout': fileout.replace(' ', '\ '),
            }

            # devuelve 0 si esta OK
            if not call(cmd % files, shell=True):

                i = filejpg.rindex('/')

                thumbnail = u'%sthumbnail_%s' % (unicode(
                    filejpg[:i + 1]), unicode(filejpg[i + 1:]))
                gallery = u'%sgallery_%s' % (unicode(
                    filejpg[:i + 1]), unicode(filejpg[i + 1:]))

                image = Image.open(fileout)
                image = convert_to_rgb(image)
                #image = crop_aspect(image, ratio=1.0)

                # hace el thumb
                image_thumb = resize(image.copy(),
                                     size=None,
                                     max_width=self.get_sizes()['gallery'][0])
                image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail))
                self.thumbnail = thumbnail

                # guarda la imagen para gallery
                #image_gallery = image.copy()
                image_gallery = resize(image.copy(),
                                       size=None,
                                       max_width=self.get_sizes()['normal'][0])
                image.save(os.path.join(settings.MEDIA_ROOT, gallery))
                self.gallery = gallery

                # borra la original porque es un PDF
                try:
                    os.remove(fileout)
                except (OSError, ValueError):
                    pass

        super(MediaContent, self).save(*args, **kwargs)
Exemplo n.º 33
0
    def image_from_array(self, image):
        if self.scheme == 'color':
            return Image.fromarray(image, mode="RGB")

        return Image.fromarray(image, mode="L")
Exemplo n.º 34
0
    def save(self, *args, **kwargs):

        changed_image = self.content != self.__original_image

        if not self.id and not self.pub_date:
            self.pub_date = datetime.datetime.today()
        
        crop_original = kwargs.get('crop_original', False)
        
        super(MediaContent, self).save(*args, **kwargs)
        self.mimetype = mimetypes.guess_type(self.content.path)[0]

        if self.mimetype:
            content_type = self.mimetype.replace('/', '_')
        else:
            # assume everything else is text/plain
            content_type = 'text_plain'
        
        i = self.content.name.rindex('/')
        thumbnail = u'%sthumbnail_%s' % (unicode(self.content.name[:i+1]), unicode(self.content.name[i+1:]))
        gallery = u'%sgallery_%s' % (unicode(self.content.name[:i+1]), unicode(self.content.name[i+1:]))
        orig = self.content.name

        if (not self.thumbnail or not self.gallery or changed_image) and content_type.split('_')[0]=='image':
            img_path = self.content.path

            if content_type == 'image_svg+xml':
                try:
                    from nebula.mediacontent import svg_to_png
                    svg_to_png.convert(img_path, svg_to_png.new_name(img_path))
                    img_path = svg_to_png.new_name(img_path)
                    self.content.name = self.content.name[:-3] + self.content.name[-3:].replace('svg', 'png')
                except:
                    pass

            image = Image.open(img_path)
            image = convert_to_rgb(image)
            image = crop_aspect(image, ratio=1.0)

            # hace el thumb
            image_thumb = resize(image.copy(), size=self.get_sizes()['thumb'])
            image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail))
            self.thumbnail = thumbnail

            # guarda la imagen para gallery
            image_gallery = resize(image.copy(), size=self.get_sizes()['gallery'])
            image_gallery.save(os.path.join(settings.MEDIA_ROOT, gallery))
            self.gallery = gallery

            # guarda la imagen al tamaño máximo
            if crop_original:
                image_normal = resize(image.copy(), size=self.get_sizes()['normal'])
                image_normal.save(os.path.join(settings.MEDIA_ROOT, orig))


        elif (not self.thumbnail or not self.gallery or changed_image) and content_type == 'application_pdf':

            # Crea una imagen de la primer pagina de un PDF
            from subprocess import call

            cmd = "gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
                    -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \
                    -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 \
                    -sOutputFile=%(fileout)s %(filein)s"

            filein = os.path.join(settings.MEDIA_ROOT, self.content.name)
            filejpg = self.content.name[:-3] + self.content.name[-3:].replace('pdf', 'jpg')
            fileout = os.path.join(settings.MEDIA_ROOT, filejpg)

            if not os.access(filein, os.R_OK):
                raise 'not access %s' % filein

            files = { 
                'filein': filein.replace(' ', '\ '),
                'fileout': fileout.replace(' ', '\ '), 
            }

            # devuelve 0 si esta OK
            if not call(cmd % files, shell=True):

                i = filejpg.rindex('/')

                thumbnail = u'%sthumbnail_%s' % (unicode(filejpg[:i+1]), unicode(filejpg[i+1:]))
                gallery = u'%sgallery_%s' % (unicode(filejpg[:i+1]), unicode(filejpg[i+1:]))

                image = Image.open(fileout)
                image = convert_to_rgb(image)
                #image = crop_aspect(image, ratio=1.0)

                # hace el thumb
                image_thumb = resize(image.copy(), size=None, max_width=self.get_sizes()['gallery'][0])
                image_thumb.save(os.path.join(settings.MEDIA_ROOT, thumbnail))
                self.thumbnail = thumbnail

                # guarda la imagen para gallery
                #image_gallery = image.copy()
                image_gallery = resize(image.copy(), size=None, max_width=self.get_sizes()['normal'][0])
                image.save(os.path.join(settings.MEDIA_ROOT, gallery))
                self.gallery = gallery

                # borra la original porque es un PDF
                try:
                    os.remove(fileout)
                except (OSError, ValueError):
                    pass
            
        super(MediaContent, self).save(*args, **kwargs)
Exemplo n.º 35
0
 def showImg(self):
     load = Image.open('Aaron.jpg')
     render = ImageTk.PhotoImage(load)
     img = Label(self, image=render)
     img.image = render
     img.place(x=0, y=0)
Exemplo n.º 36
0
    def _generate_thumbnail(self, video, thumbnail_width, thumbnail_height,
                            crop=True, frames=100):
        histogram_list = []
        framw_average  = []

        path, full_filename = os.path.split(self.path)

        filename, extension = os.path.splitext(full_filename)

        # By default temp frame data is stroed under MEDIA_ROOT/temp
        path = '%s/temp/' % settings.MEDIA_ROOT
        if not os.path.isdir(path):
            os.mkdir(path)

        hashable_value = '%s%s' % (full_filename, int(time.time()))
        filehash = hashlib.md5(hashable_value).hexdigest()

        frame_args = {'path': path, 'filename': filehash, 'frame': '%d'}
        frame = '%(path)s%(filename)s.%(frame)s.jpg' % frame_args

        # Build the ffmpeg shell command and run it via subprocess
        cmd_args = {'frames': frames, 'video_path':video_path, 'output':frame}
        command = 'ffmpeg -i %(video_path)s -y -vframes %(frames)d %(output)s'
        command = command % cmd_args
        response = subprocess.call(command, shell=True, stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)

        # Fail silently if ffmpeg is not installed.
        if reponse != 0:
            return

        # Loop through the generated images, open, and generate the image histogram
        for index in range(1, frames+1):
            frame_name = frame % index

            # If for some reason the frame does not exist, go to next frame.
            if not os.path.exists(frame_name):
                continue

            image = Image.open(frame_name)

            # Convert to RGB if necessary
            if image.mode not in ('L', 'RGB'):
                image = image.convert(image.histogram())

        frames = len(histogram_list)

        # Calculate the accumulated average
        for idx in range(len(histogram_list[0])):
            average = 0.0
            accumulation = 0.0
            for idy in range(frames):
                accumulation += histogram_list[idy][idx]
                average = (float(accumulation) / frames)
            frame_average.append(average)

        minn = -1
        minRMSE = -1

        # Calculate the mean squared error
        for idx in range(frames):
            results = 0.0
            average_count = len(frame_average)

            for idy, average in enumerate(frame_average):
                error = average - float(histogram_list[idx][idy])
                results += float((error*error)) / average_count
            rmse = math.sqrt(results)

            if minn == -1 or rmse < minRMSE:
                minn = (idx + 1)
                minRMSE = rmse

        frame_path = frame % (minn)
        image = Image.open(frame_path)

        # Crop the image if auto_crop is enabled and dimensions are the same.
        if thumbnail_width == thumbnail_height and self.auto_crop:
            width, height = image.size
            min_size = min(width, height)
            new_width = (width - min_size) / 2
            new_height = (height - min_size) / 2
            params = (
                new_width, new_height,
                width - new_width, height - new_height
            )
            image2 = image.crop(params)
            image2.load()
            image2.thumbnail((thumbnail_width, thumbnail_height), Image.ANTIALIAS)
        else:
            image2 = image
            image2.thumbnail((thumbnail_width, thumbnail_height), Image.ANTIALIAS)

        io = cStringIO.StringIO()
        image2.save(io, 'jpeg')

        # Unlink the temp files.
        for idx in range(frames):
            frame_fiel = frame % (idx + 1)
            os.unlink(frame_file)

        return ContentFile(io.getvalue())
Exemplo n.º 37
0
#!/usr/bin/env python
#coding: utf-8

myPath = "C:\\Users\\Lenovo\\Desktop\\"
fontPath = "C:\\Windows\\Fonts\\" #win10上系统的字体位置
inputFile = "1_sirwill.jpg"
outputFile = "output.jpg"

from Pillow import Image, ImageDraw,ImageFont
#打开图片
im = Image.open(myPath + inputFile)  #打开一个照片对象
draw = ImageDraw.Draw(im)            #创建画布

#根据图片大小确定字体大小
fontsize = (min(im.size)/4          #注意truetype方法要整数,需要取整

#加文字
#实例
font = ImageFont.truetype(fontPath + 'ALGER.TTF',fontsize) #其余参数默认 得到字体实例
draw.text((im.size[0]-fontsize,0), '5', font = font, fill = (256, 0, 0)) #确定位置、数字、实例、填充色
#保存图片
im.save(myPath + outputFile,"jpeg")
Exemplo n.º 38
0
def get_main_color(img_path):
    cv2_img = cv2.imread(img_path)  #画像読み込み
    height = cv2_img.shape[0]
    width = cv2_img.shape[1]
    cv2_img = cv2.resize(cv2_img, (int(width * 0.3), int(height * 0.3)))
    cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB)  #BGRとRGBを変換
    cv2_img = cv2_img.reshape(
        (cv2_img.shape[0] * cv2_img.shape[1], 3))  #データ量を3から2へ
    cluster = KMeans(n_clusters=5)  #クラスター数を指定する
    cluster.fit(X=cv2_img)  #クラスタリングを行い、cluster_centers_にRGB値を格納
    cluster_centers_arr = cluster.cluster_centers_.astype(
        int, copy=False)  #格納されたRGB値の小数を消す
    IMG_SIZE = 64  #カラーパレットの一1色分の大きさ
    MARGIN = 15
    width = IMG_SIZE * 5 + MARGIN * 2
    height = IMG_SIZE + MARGIN * 2  # 幅と高さ64px × 横並び5画像 + 上下左右余白15pxずつの画像を作成

    tiled_color_img = Image.new(mode='RGB',
                                size=(width, height),
                                color='#333333')  #作成した画像をグレーにする

    for i, rgb_arr in enumerate(
            cluster_centers_arr):  #iにインデックスの数字(5)、rgb_arrに上で取得したリストの要素(RGB値)
        color_hex_str = '#%02x%02x%02x' % tuple(rgb_arr)  #RGB値をHEXに変換してPILに渡す
        color_hex_rev = '#%02x%02x%02x' % tuple(
            255 - rgb_arr)  #反対色のRGB値をHEXに変換してPILに渡す
        color_img = Image.new(
            mode='RGB',
            size=(IMG_SIZE, IMG_SIZE),  #求めた色の正方形の画像を出力
            color=color_hex_str)
        draw = ImageDraw.Draw(color_img)  #作成した画像の上にImageDrawインスタンスを作る
        draw.text((0, 0), color_hex_str)  #画像にHEXをいれる
        draw.text(
            (21, 54),
            color_hex_rev,
            color_hex_rev,
        )
        tiled_color_img.paste(im=color_img,
                              box=(MARGIN + IMG_SIZE * i,
                                   MARGIN))  #グレーの画像に各クラスタの色の画像をペーストしていく

    new_image = np.array(tiled_color_img, dtype=np.uint8)  #PillowからCV2に変更
    if new_image.ndim == 2:  # モノクロ
        pass
    elif new_image.shape[2] == 3:  # カラー
        new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
    elif new_image.shape[2] == 4:  # 透過
        new_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA)

    path = '/Users/tani/Pictures'  #保存先指定
    cv2.imshow('image', new_image)  #imageというウィンドウで表示
    k = cv2.waitKey(0)  #何かボタンを押すまで待つ
    if k == ord('e'):  #Eを押した場合
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        cv2.waitKey(0)  #保存せずに取り消し
    elif k == ord('s'):  #Sを押した場合
        #名前用に乱数生成 i =str(img_path)
        i = str(random.randint(1, 100))  #名前用に乱数生成
        cv2.imwrite(os.path.join(path, 'colorpalette' + i + '.jpg'),
                    new_image)  #保存
        cv2.waitKey(0)
        cv2.destroyAllWindows()  #表示取り消し
        cv2.waitKey(0)