Example #1
0
def alineacion():
    # raiz="C:\Users\SIR\Desktop\UNIVERSIDAD DE BARCELONA\Curso 15-16\Procesamiento de imagenes\Practica\Practica1"
    # LOAD IMAGES
    raiz = os.getcwd()
    img1 = Image.open(raiz + "\human.png")
    img2 = Image.open(raiz + "\cat.png")
    # RESIZE
    size1 = int(round(img1.size[0] * (4 / 3.0)))
    size2 = int(round(img1.size[1] * (4 / 3.0)))
    img1 = img1.resize((size1, size2), Image.ANTIALIAS)
    # CROP
    left = 50
    top = 50
    right = 51 + img2.size[0] - 1
    bottom = 51 + img2.size[1] - 1
    img1 = img1.crop((left, top, right, bottom))
    # VISUALIZATION ---------------
    plt.show()
    plt.imshow(img1)
    plt.show()
    plt.figure(1)
    plt.subplot(131)
    imgplot1 = plt.imshow(img1)
    imgplot1.set_cmap("gray")
    plt.subplot(132)
    imgplot1 = plt.imshow(img2)
    imgplot1.set_cmap("gray")

    return img1, img2
Example #2
0
 def testThumbnail(self, author_testimg_bad, author_testimg_big):
     thumb = self.image.getThumbnail()
     tfile = StringIO(thumb)
     thumb = Image.open(tfile)  # Raises if invalid
     thumb.verify()  # Raises if invalid
     assert thumb.format == "JPEG"
     assert thumb.size == (64, 64)
     thumb = self.image.getThumbnail(96)
     tfile = StringIO(thumb)
     thumb = Image.open(tfile)  # Raises if invalid
     thumb.verify()  # Raises if invalid
     assert thumb.size == (96, 96)
     thumb = self.image.getThumbnail((128, 96))
     tfile = StringIO(thumb)
     thumb = Image.open(tfile)  # Raises if invalid
     thumb.verify()  # Raises if invalid
     assert thumb.size == (128, 96)
     badimage = author_testimg_bad  # no pixels
     assert badimage.getThumbnail() is None
     # Big image (4k x 4k and up) thumb
     bigimage = author_testimg_big
     thumb = bigimage.getThumbnail()
     tfile = StringIO(thumb)
     thumb = Image.open(tfile)  # Raises if invalid
     thumb.verify()  # Raises if invalid
     assert thumb.format == "JPEG"
     assert thumb.size == (64, 64)
Example #3
0
    def printTrix(self, output):

        txt = Image.new("RGBA", self.image.size, (255, 255, 255, 0))

        fnt = ImageFont.truetype("lumitables/" + self.lumitable.fontName + ".ttf", self.lumitable.fontSize)
        d = ImageDraw.Draw(txt)

        for currtrix in self.trixtable:
            if len(currtrix) > 0:
                for i in range(0, self.blockPerChar.__int__()):
                    if len(currtrix[1]) > i:
                        for tuple in currtrix[1][i]:
                            x = tuple[0] * self.lumitable.blockWidth
                            y = tuple[1] * self.lumitable.blockHeight
                            if self.imagetable.colorMode == "colors":
                                red = self.imagetable.colorTable[tuple[0]][tuple[1]][0]
                                green = self.imagetable.colorTable[tuple[0]][tuple[1]][1]
                                blue = self.imagetable.colorTable[tuple[0]][tuple[1]][2]
                                d.text((x, y), chr(currtrix[0]), font=fnt, fill=(red, green, blue, 255))
                            else:
                                d.text((x, y), chr(currtrix[0]), font=fnt, fill=(0, 0, 0, 255))

        out = Image.alpha_composite(self.image, txt)

        out.save("output/" + output)

        v_print(2, "Trix saved!")
Example #4
0
    def upload_cover(self, path, filename, metadata, filepath):
        try:
            from PIL import Image, ImageDraw

            Image, ImageDraw
        except ImportError:
            import Image, ImageDraw

        coverdata = getattr(metadata, "thumbnail", None)
        if coverdata and coverdata[2]:
            cover = Image.open(cStringIO.StringIO(coverdata[2]))
        else:
            coverdata = open(I("library.png"), "rb").read()

            cover = Image.new("RGB", (96, 144), "black")
            im = Image.open(cStringIO.StringIO(coverdata))
            im.thumbnail((96, 144), Image.ANTIALIAS)

            x, y = im.size
            cover.paste(im, ((96 - x) / 2, (144 - y) / 2))

            draw = ImageDraw.Draw(cover)
            draw.text((1, 15), metadata.get("title", _("Unknown")).encode("ascii", "ignore"))
            draw.text((1, 115), metadata.get("authors", _("Unknown")).encode("ascii", "ignore"))

        data = cStringIO.StringIO()
        cover.save(data, "JPEG")
        coverdata = data.getvalue()

        with open("%s.jpg" % os.path.join(path, filename), "wb") as coverfile:
            coverfile.write(coverdata)
            fsync(coverfile)
Example #5
0
def _save(im, fp, tile, bufsize=0):
    """Helper to save image based on tile list

    :param im: Image object.
    :param fp: File object.
    :param tile: Tile list.
    :param bufsize: Optional buffer size
    """

    im.load()
    if not hasattr(im, "encoderconfig"):
        im.encoderconfig = ()
    tile.sort(key=_tilesort)
    # FIXME: make MAXBLOCK a configuration parameter
    # It would be great if we could have the encoder specify what it needs
    # But, it would need at least the image size in most cases. RawEncode is
    # a tricky case.
    bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4)  # see RawEncode.c
    if fp == sys.stdout:
        fp.flush()
        return
    try:
        fh = fp.fileno()
        fp.flush()
    except (AttributeError, io.UnsupportedOperation):
        # compress to Python file-compatible object
        for e, b, o, a in tile:
            e = Image._getencoder(im.mode, e, a, im.encoderconfig)
            if o > 0:
                fp.seek(o, 0)
            e.setimage(im.im, b)
            if e.pushes_fd:
                e.setfd(fp)
                l, s = e.encode_to_pyfd()
            else:
                while True:
                    l, s, d = e.encode(bufsize)
                    fp.write(d)
                    if s:
                        break
            if s < 0:
                raise IOError("encoder error %d when writing image file" % s)
            e.cleanup()
    else:
        # slight speedup: compress to real file object
        for e, b, o, a in tile:
            e = Image._getencoder(im.mode, e, a, im.encoderconfig)
            if o > 0:
                fp.seek(o, 0)
            e.setimage(im.im, b)
            if e.pushes_fd:
                e.setfd(fp)
                l, s = e.encode_to_pyfd()
            else:
                s = e.encode_to_file(fh, bufsize)
            if s < 0:
                raise IOError("encoder error %d when writing image file" % s)
            e.cleanup()
    if hasattr(fp, "flush"):
        fp.flush()
Example #6
0
def save(height, name):
    cols = os.listdir(OUTPUT_ROOT)
    l = []
    for i in cols:
        if not "col_" in i:
            l.append(i)
    for i in l:
        cols.remove(i)

    cols = [int(i.replace("col_", "").replace(".png", "")) for i in cols]
    cols.sort()
    w, h = height, height
    try:
        result = Image.new("RGBA", (w, h))
        for i in cols:
            p = "col_%d.png" % i
            f = Image.open(os.path.join(OUTPUT_ROOT, p))
            result.paste(f, (cols.index(i) * TILE_WIDTH, 0))
            print("column %d OK" % cols.index(i))

        p = os.path.join(OUTPUT_ROOT, name)
        p = os.path.abspath(p)
        result.save(p)
    except:
        print(traceback.format_exc())
Example #7
0
def imageResize(imagefile, largestside):
    """Resize an image to what is specified as the long side"""
    # check for string or a mongo gridfs file object
    if isinstance(imagefile, str):
        if not os.path.isfile(imagefile):
            log.error("imagefile " + imagefile + " does not exist", extra=tags)
            return None, ExitCode.FileNotExists
        image = Image.open(imagefile)
    else:
        image = Image.open(StringIO.StringIO(imagefile.read()))

    (x, y) = image.size

    # Find cleaner way to structure this
    # Is ANTIALIAS right? Maybe that messes with the color too much, os using BILINEAR
    if max(image.size) is not x:
        ratio = (y + 0.0) / (x + 0.0)
        smallside = largestside / ratio
        newimage = image.resize((smallside, largestside), Image.BILINEAR)
    else:
        ratio = (x + 0.0) / (y + 0.0)
        smallside = largestside / ratio
        newimage = image.resize((largestside, smallside), Image.BILINEAR)

    return newimage
Example #8
0
    def test_save_cjpeg(self):
        img = Image.open(TEST_FILE)

        tempfile = self.tempfile("temp.jpg")
        JpegImagePlugin._save_cjpeg(img, 0, tempfile)
        # Default save quality is 75%, so a tiny bit of difference is alright
        self.assert_image_similar(img, Image.open(tempfile), 17)
Example #9
0
    def test_ne(self):
        # Arrange
        im1 = Image.new("RGB", (25, 25), "black")
        im2 = Image.new("RGB", (25, 25), "white")

        # Act / Assert
        self.assertTrue(im1 != im2)
def stitch_two_images(image1, image2, filename):
    """Takes two .jpg pictures and a string filename and returns a stitched together picture"""
    im = Image.open(image1)
    im2 = Image.open(image2)
    width1, height1 = im.size
    width2, height2 = im2.size

    if height1 >= height2:
        heightfinal = im.size[1]
    else:
        heightfinal = im2.size[1]
    widthfinal = im.size[0] + im2.size[0]

    finalim = Image.new("RGB", ((widthfinal, heightfinal)))

    for w in range(width1):
        for h in range(height1):
            finalim.putpixel((w, h), im.getpixel((w, h)))

    for w in range(width2):
        for h in range(height2):
            if h - 1 < 0:  # shift one pixel up
                finalim.putpixel((w + width1, h), im2.getpixel((w, h)))  # because input picture is different
            else:
                finalim.putpixel((w + width1, h - 1), im2.getpixel((w, h)))

    finalim.save(filename + ".jpg", format="jpeg")

    return
Example #11
0
def tint_image(vargs=None):
    if vargs is None:
        vargs = sys.argv
    file, ext = os.path.splitext(vargs[1])
    image = Image.open("%s" % vargs[1])
    newImage = ImageChops.multiply(image, Image.new("RGB", image.size, vargs[2]))
    newImage.save(file + "n", "JPEG")
Example #12
0
def waterMark(**args):
    """
    为图片加水印
    :param args:
    :return:
    """
    args_key = {"ori_img": "", "dst_img": "", "mark_img": "", "water_opt": ""}
    arg = {}
    for key in args_key:
        if key in args:
            arg[key] = args[key]

    im = Image.open(arg["ori_img"])
    ori_w, ori_h = im.size

    mark_im = Image.open(arg["mark_img"])
    mark_w, mark_h = mark_im.size
    option = {
        "leftup": (0, 0),
        "rightup": (ori_w - mark_w, 0),
        "leftlow": (0, ori_h - mark_h),
        "rightlow": (ori_w - mark_w, ori_h - mark_h),
    }

    im.paste(mark_im, option[arg["water_opt"]], mark_im.convert("RGBA"))
    im.save(arg["dst_img"])
Example #13
0
def test_palette_is_gray():
    from PIL import Image

    gray = Image.open(os.path.join(data_dir, "palette_gray.png"))
    assert _palette_is_grayscale(gray)
    color = Image.open(os.path.join(data_dir, "palette_color.png"))
    assert not _palette_is_grayscale(color)
Example #14
0
def handle_message(sock, write=False, outdir="", imtype="png", prefix=""):
    info = sock.recv()
    nstr = sock.recv()
    narray = np.asarray(Image.open(StringIO(nstr)).convert("RGB"))
    ostr = sock.recv()
    oarray = np.asarray(Image.open(StringIO(ostr)).convert("RGB"))
    imstr = sock.recv()
    imarray = np.asarray(Image.open(StringIO(imstr)).convert("RGB"))
    im = Image.fromarray(imarray)
    imo = Image.fromarray(oarray)
    if write:
        if not os.path.exists(outdir):
            os.mkdir(outdir)
        im.save(os.path.join(outdir, "image_%s.%s" % (prefix, imtype)))
        # imo.save(os.path.join(outdir, 'objects_%s.%s' % (prefix, imtype)))
        # with open(os.path.join(outdir, 'image_%s.%s' % (prefix, imtype)), 'w') as _f:
        #    _f.write(imstr)
        # with open(os.path.join(outdir, 'objects_%s.%s' % (prefix, imtype)), 'w') as _f:
        #    _f.write(ostr)
        # with open(os.path.join(outdir, 'normals_%s.%s' % (prefix, imtype)), 'w') as _f:
        #    _f.write(nstr)
        if prefix == "0_0":
            with open(os.path.join(outdir, "info_%s.json" % prefix), "w") as _f:
                _f.write(info)
    return [info, narray, oarray, imarray]
Example #15
0
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    img = Image.open(in_fname)
    width_in, height_in = img.size
    scale_w = width / float(width_in)
    scale_h = height / float(height_in)

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

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

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

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

    thumb.save(out_fname)
Example #16
0
    def test_alpha_composite(self):
        # http://stackoverflow.com/questions/3374878
        # Arrange
        from PIL import ImageDraw

        expected_colors = sorted(
            [
                (1122, (128, 127, 0, 255)),
                (1089, (0, 255, 0, 255)),
                (3300, (255, 0, 0, 255)),
                (1156, (170, 85, 0, 192)),
                (1122, (0, 255, 0, 128)),
                (1122, (255, 0, 0, 128)),
                (1089, (0, 255, 0, 0)),
            ]
        )

        dst = Image.new("RGBA", size=(100, 100), color=(0, 255, 0, 255))
        draw = ImageDraw.Draw(dst)
        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))
        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))
        src = Image.new("RGBA", size=(100, 100), color=(255, 0, 0, 255))
        draw = ImageDraw.Draw(src)
        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))
        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))

        # Act
        img = Image.alpha_composite(dst, src)

        # Assert
        img_colors = sorted(img.getcolors())
        self.assertEqual(img_colors, expected_colors)
Example #17
0
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    img = Image.open(in_fname)
    width_in, height_in = img.size
    scale_w = width / float(width_in)
    scale_h = height / float(height_in)

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

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

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

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

    thumb.save(out_fname)
    # Use optipng to perform lossless compression on the resized image if
    # software is installed
    if os.environ.get("SKLEARN_DOC_OPTIPNG", False):
        try:
            subprocess.call(["optipng", "-quiet", "-o", "9", out_fname])
        except Exception:
            warnings.warn("Install optipng to reduce the size of the generated images")
Example #18
0
    def save_weights_to_grey_files(self, identifier):
        # save 4 sets of weights:

        # filters_hs
        def arrange_for_show(filters_hs, filters_hs_shape):
            n_filters_hs_modules, n_filters_hs_per_modules, fcolors, n_filters_hs_rows, n_filters_hs_cols = (
                filters_hs_shape
            )
            filters_fs_for_show = filters_hs.reshape(
                (n_filters_hs_modules * n_filters_hs_per_modules, fcolors, n_filters_hs_rows, n_filters_hs_cols)
            )
            fn = theano.function([], filters_fs_for_show)
            rval = fn()
            return rval

        filters_fs_for_show = arrange_for_show(self.filters_hs, self.filters_hs_shape)
        Image.fromarray(tile_conv_weights(filters_fs_for_show, flip=False), "L").save("filters_hs_%s.png" % identifier)

        if self.conf["lambda_logdomain"]:
            raise NotImplementedError()
        else:
            conv_lambda_for_show = arrange_for_show(self.conv_lambda, self.filters_hs_shape)
            Image.fromarray(tile_conv_weights(conv_lambda_for_show, flip=False), "L").save(
                "conv_lambda_%s.png" % identifier
            )
Example #19
0
    def hash_image_string(self, fp):
        """Returns hash based on image data

        Args:
            fp (str): path to image file

        Returns:
            Hash of image data as string
        """
        # FIXME: Output directory is hardcoded
        try:
            return hashlib.md5(Image.open(fp).tobytes()).hexdigest()
        except IOError:
            # Encountered a file format that PIL can't handle. Convert
            # file to something usable, hash, then delete the derivative.
            print "Hashing jpeg derivative..."
            fn = os.path.basename(fp)
            jpeg = os.path.splitext(fn)[0] + ".jpg"
            cmd = 'iconvert "{}" "{}"'.format(fp, jpeg)  # FIXME
            return_code = subprocess.call(cmd, cwd=r"D:\embedded")
            if return_code:
                self.logfile.write("Error: {}: Bad return code ({})\n".format(fp, return_code))
            dst = os.path.join(r"D:\embedded", jpeg)
            h = hashlib.md5(Image.open(dst).tobytes()).hexdigest()
            os.remove(dst)
            return h
Example #20
0
    def __init__(self, name, sprite):
        """Image constructor

        :param name: Image name.
        :param sprite: :class:`~Sprite` instance for this image."""
        self.x = None
        self.y = None
        self.name = name
        self.sprite = sprite
        self.filename, self.format = name.rsplit(".", 1)

        pseudo = set(self.filename.split("_")).intersection(PSEUDO_CLASSES)
        self.pseudo = ":%s" % list(pseudo)[-1] if pseudo else ""

        image_path = os.path.join(sprite.path, name)
        image_file = open(image_path, "rb")

        try:
            source_image = PImage.open(image_file)
            source_image.load()
            self.image = PImage.new("RGBA", source_image.size, (0, 0, 0, 0))

            if source_image.mode == "L":
                alpha = source_image.split()[0]
                mask = PImage.eval(alpha, lambda a: 0 if a == source_image.info.get("transparency", 0) else 255)
                self.image.paste(source_image, (0, 0), mask=mask)
            else:
                self.image.paste(source_image, (0, 0))

        except IOError, e:
            raise PILUnavailableError(e.args[0].split()[1])
Example #21
0
    def test_12bit_rawmode(self):
        """ Are we generating the same interpretation
        of the image as Imagemagick is? """

        # Image.DEBUG = True
        im = Image.open("Tests/images/12bit.cropped.tif")

        # to make the target --
        # convert 12bit.cropped.tif -depth 16 tmp.tif
        # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif
        # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,
        # so we need to unshift so that the integer values are the same.

        im2 = Image.open("Tests/images/12in16bit.tif")

        if Image.DEBUG:
            print(im.getpixel((0, 0)))
            print(im.getpixel((0, 1)))
            print(im.getpixel((0, 2)))

            print(im2.getpixel((0, 0)))
            print(im2.getpixel((0, 1)))
            print(im2.getpixel((0, 2)))

        self.assert_image_equal(im, im2)
Example #22
0
def create_derived_image(image, pilDerivedImage, type, eraseOldVersions=True):

    if eraseOldVersions:
        image.derived_images.filter(type=type).delete()

    (directory, basename, extension) = image.splitPath()

    derivedImageFilename = basename + "_" + type + "." + extension
    derivedImagePath = directory + "/" + derivedImageFilename

    cnt = 1

    while os.path.exists(derivedImagePath):
        derivedImageFilename = basename + "_" + type + ("_%d" % cnt) + "." + extension
        derivedImagePath = directory + "/" + derivedImageFilename
        cnt += 1

    derivedImageUrl = settings.FILE_UPLOAD_URL + "/" + derivedImageFilename

    pilDerivedImage.save(derivedImagePath)

    derivedImage = Image()
    derivedImage.path = derivedImagePath
    derivedImage.user = image.user
    derivedImage.base_image = image
    derivedImage.type = type
    derivedImage.url = derivedImageUrl
    derivedImage.width = pilDerivedImage.size[0]
    derivedImage.height = pilDerivedImage.size[1]
    derivedImage.save()

    return derivedImage
Example #23
0
 def __init__(self, master, func):
     Tkinter.Toplevel.__init__(self, master, relief=Tkinter.SOLID, highlightthickness=1, highlightcolor=fg)
     self.root = master
     self.root.withdraw()
     self.overrideredirect(Tkinter.TRUE)
     self.progress = Progressbar(self)
     if not config.python3:
         self.image1 = Image.open(config.relinuxdir + "/splash.png")
         self.image2 = Image.open(config.relinuxdir + "/splash_glowy.png")
         self.images = []
         for i in range(0, 11):
             percent = float(float(i) / 10)
             self.images.append(ImageTk.PhotoImage(Image.blend(self.image1, self.image2, percent)))
         # self.image = ImageTk.PhotoImage(Image.blend(self.image1, self.image2, 0.0))
         self.image = self.images[0]
         self.imgw = self.image.width()
         self.imgh = self.image.height()
     else:
         self.image = Tkinter.PhotoImage(file=config.relinuxdir + "/splash.ppm")
         self.imgw = self.image.width()
         self.imgh = self.image.height()
     self.textvar = Tkinter.StringVar()
     self.progresstext = Label(self, textvariable=self.textvar, height=15, width=480, anchor=Tkinter.W)
     self.w = self.imgw
     self.h = self.imgh + 32
     self.x = self.root.winfo_screenwidth() / 2 - self.w / 2
     self.y = self.root.winfo_screenheight() / 2 - self.h / 2
     self.geometry("%dx%d+%d+%d" % (self.w, self.h, self.x, self.y))
     self.panel = Label(self, image=self.image)
     self.panel.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=True)
     self.progress.pack(side=Tkinter.BOTTOM, fill=Tkinter.X, expand=True)
     self.progresstext.pack(side=Tkinter.BOTTOM, fill=Tkinter.X, expand=True)
     self.update()
     self.thread = FuncThread(func, self.endSplash, self)
     self.thread.start()
Example #24
0
    def array_to_stimulus(self, array_or_image, spatial_extend, starting_point, velocity):
        if type(array_or_image) == np.ndarray:
            if self.intensity_dim == 1:
                try:
                    im = Image.fromarray(array_or_image[:, :, 0] * 255)
                except:
                    im = Image.fromarray(array_or_image * 255)
            else:
                im = Image.fromarray(array_or_image * 255, "RGB")
        else:
            im = array_or_image

        px_spatial_extend = [
            int(spatial_extend[0] * self.intensities.shape[0]),
            int(spatial_extend[1] * self.intensities.shape[1]),
        ]
        px_start = [
            int(starting_point[0] * self.intensities.shape[0]),
            int(starting_point[1] * self.intensities.shape[1]),
        ]
        px_velocity = [int(velocity[0] * self.intensities.shape[0]), int(velocity[1] * self.intensities.shape[1])]

        stim = stimulus.ImgStimulus(self.intensity_dim, im, px_spatial_extend, px_start, px_velocity)

        self.stimuli.append(stim)
Example #25
0
    def resizedMerge(self, background, stylepath):
        isatv2 = 0

        renderwidth, renderheight = self.getRendersize(self.cfg["resolution"])
        if str(renderheight) == "720":
            height = int(self.cfg["resolution"])
            if height == 720:
                isatv2 = 1
                width = 1920
                height = 1080
            elif height == 1080:
                width = 1920
        else:
            width = renderwidth
            height = renderheight

        im = Image.new("RGB", (width, height), "black")
        background = background.resize((width, height), Image.ANTIALIAS)

        # Blur BG
        if self.cfg["imageBlur"] != None and self.cfg["imageBlur"] != "" and self.cfg["imageBlur"] > 0:
            for i in range(0, int(self.cfg["imageBlur"])):
                background = background.filter(ImageFilter.BLUR)
        im.paste(background, (0, 0), 0)
        # Layers
        layerrange = range(0, len(self.cfg["layers"]))
        for layercounter in layerrange:
            if self.cfg["layers"][layercounter] != None:
                layer = Image.open(stylepath + "/images/" + self.cfg["layers"][layercounter] + ".png")
                layer = layer.resize((width, height), Image.ANTIALIAS)
                im.paste(layer, (0, 0), layer)

        if isatv2 > 0:
            im = im.resize((1280, 720), Image.ANTIALIAS)
        return im
Example #26
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")
Example #27
0
    def isThumbOk(self):
        #  1 : thumb seems good with original (same orientation)
        #  0 : not same orientation
        # -1 : no thumb
        isThumbOk = None

        im = Image.open(self.__file)
        im.verify()
        w, h = im.size
        isImageHorizon = w > h

        t = self.__getThumbnail()
        if t:
            f = StringIO.StringIO()
            f.write(t)
            f.seek(0)
            tw, th = Image.open(f).size
            isTImageHorizon = tw > th

            if isImageHorizon == isTImageHorizon:
                isThumbOk = 1
            else:
                isThumbOk = 0
        else:
            isThumbOk = -1

        assert (
            self.__info["Exif.Image.DateTime"]
            == self.__info["Exif.Photo.DateTimeOriginal"]
            == self.__info["Exif.Photo.DateTimeDigitized"]
        )

        return isThumbOk
Example #28
0
 def set_wallpaper(self):
     """Save map as bmp format and set it as the wallpaper"""
     # Check if file has been saved and execute accordingly
     if self.saved:
         # Open image
         crop_img = Image.open(self.save_file)
     else:
         # Raise error if figure or filename do not exist
         if self._figure == None:
             raise Exception("Map not yet generated!")
         # Convert image
         canvas = plt.get_current_fig_manager().canvas
         agg = canvas.switch_backends(FigureCanvasAgg)
         agg.draw()
         crop_img = Image.fromstring("RGB", self._figure.canvas.get_width_height(), agg.tostring_rgb())
         # plt.close()
     # Determine crop coordinates
     w, h = crop_img.size
     wDiff = int((w - self._screen_size[0]) * 0.5)
     hDiff = int((h - self._screen_size[1]) * 0.5)
     cropBox = (wDiff, hDiff, self._screen_size[0] + wDiff, self._screen_size[1] + hDiff)
     # Crop image
     crop_img = crop_img.crop(cropBox)
     # Try to save temporary file,  otherwise convert to correct image format and save again
     try:
         crop_img.save(self.save_file, "PNG")
     except:
         crop_img = crop_img.convert("RGB")
         crop_img.save(self.save_file, "PNG")
Example #29
0
def convert_to_nametable(image_file):
    colors = []
    original = Image.open(image_file)
    original = original.convert("RGB")

    template = Image.new("P", original.size)
    template.putpalette(create_pil_palette())

    converted = original.quantize(palette=template, colors=4)
    pixels = converted.load()

    assert converted.size[0] == 256
    assert converted.size[1] == 256

    cnt = Counter()
    for i in range(converted.size[0]):
        for j in range(converted.size[1]):
            if pixels[i, j] not in colors:
                colors.append(pixels[i, j])
            cnt[pixels[i, j]] += 1
        break

    # cnt.most_common(4)

    sprs, indexes = convert_chr(converted, optimize_repeated=True)
    nametable = convert_nametable(converted, indexes)

    write_bin_code(sprs, "sprite.chr")
    write_bin_code(nametable, "nametable.bin")

    return nametable, sprs
Example #30
0
    def scale_image(self, in_fname, out_fname, max_width, max_height):
        """Scales an image with the same aspect ratio centered in an
           image with a given max_width and max_height
           if in_fname == out_fname the image can only be scaled down
        """
        # local import to avoid testing dependency on PIL:
        try:
            from PIL import Image
        except ImportError:
            import Image
        img = Image.open(in_fname)
        width_in, height_in = img.size
        scale_w = max_width / float(width_in)
        scale_h = max_height / float(height_in)

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

        if scale >= 1.0 and in_fname == out_fname:
            return

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

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

        # insert centered
        thumb = Image.new("RGB", (max_width, max_height), (255, 255, 255))
        pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)
        thumb.paste(img, pos_insert)

        thumb.save(out_fname)