Пример #1
1
def copy_icons(web_path):
    for x in icons:
        bname = x.split("/")[-1]
        wname = os.path.join(web_path, bname)

        try:
            g = Image.open(wname)
        except:
            pass
        else:
            continue

        try:
            f = Image.open(x)
            f2 = f.convert("RGBA")
            d = f2.getdata()
            rr, rg, rb, ra = d[0]
            if ra:
                o = []
                for y in d:
                    if y[0] == rr and y[1] == rg and y[2] == rb:
                        o.append((0, 0, 0, 0))
                    else:
                        o.append(y)
                f2.putdata(o)
                f2.save(wname)
            else:
                raise Exception
        except:
            shutil.copyfile(x, wname)
Пример #2
1
def conn_tests(solver, save_format):
    print ">>>", datetime.now(), "Begin conn tests"
    solver.net.set_phase_test()
    solver.test_nets[0].share_with(solver.net)
    net = solver.test_nets[0]
    save_dir = save_format.format(solver.iter)
    os.mkdir(save_dir)
    hist = np.zeros((2, 2))
    for fname in fnames_val:
        net.forward()
        im = Image.fromarray(net.blobs["left-conn"].data[0].argmax(0).astype(np.uint8), mode="P")
        im.save(os.path.join(save_dir, fname + "-L.png"))
        im = Image.fromarray(net.blobs["top-conn"].data[0].argmax(0).astype(np.uint8), mode="P")
        im.save(os.path.join(save_dir, fname + "-T.png"))
        h, _, _ = np.histogram2d(
            net.blobs["left-gt"].data[0, 0].flatten(),
            net.blobs["left-conn"].data[0].argmax(0).flatten(),
            bins=2,
            range=[[0, 2], [0, 2]],
        )
        hist += h
        h, _, _ = np.histogram2d(
            net.blobs["top-gt"].data[0, 0].flatten(),
            net.blobs["top-conn"].data[0].argmax(0).flatten(),
            bins=2,
            range=[[0, 2], [0, 2]],
        )
        hist += h
    print ">>>", datetime.now(), "Iteration", solver.iter, "overall accuracy", np.diag(hist).sum() / hist.sum()
    print ">>>", datetime.now(), "Iteration", solver.iter, "total IU", hist[1, 1] / (
        hist[0, 1] + hist[1, 0] + hist[1, 1]
    )
    solver.net.set_phase_train()
Пример #3
1
 def takeSnapshot(self, *args):
     """taco"""
     if canTakeSnapshots:
         rawimg = self.device.DevCcdRead(1)
         try:
             img = Image.frombuffer("RGB", (self.getWidth(), self.getHeight()), rawimg)
             pixmap = img.tostring("raw", "BGR")
             img = Image.frombuffer("RGB", img.size, pixmap)
             # img.save(*args)
         except:
             logging.getLogger("HWR").exception("%s: could not save snapshot", self.name())
         else:
             if len(args):
                 try:
                     img.save(*args)
                 except:
                     logging.getLogger("HWR").exception("%s: could not save snapshot", self.name())
                 else:
                     return True
             else:
                 return img
     else:
         logging.getLogger("HWR").error(
             "%s: could not take snapshot: sorry PIL is not available :-(", self.name()
         )
     return False
Пример #4
1
def apply_signature(job):
    # getting the image and signature file names.
    image_file, wm_file = job.data.split(":::")

    # loading the signature
    signature = Image.open(wm_file)
    signature, mode = _wm_mode(signature)

    # loading the image
    image = Image.open(image_file)
    image_format = image.format
    if "RGB" not in image.mode:
        image = image.convert("RGB")

    # injecting signature
    signatureed = inject_wm(signature, image, mode)

    # saving the result
    image_filename, ext = os.path.splitext(image_file)
    target = os.path.join(image_filename + "_wm" + ext)

    if image.format == "JPEG":
        try:
            signatureed.save(target, image.format, quality=95, optimize=1)
        except IOError:
            signatureed.save(target, image.format, quality=95)
    else:
        try:
            signatureed.save(target, image.format, optimize=1)
        except IOError:
            signatureed.save(target, image.format)

    return target
Пример #5
1
def main():
    pool = multiprocessing.Pool()  # For the parallel map()
    if sys.argv[1] == "decode":
        source = Image.open(sys.argv[1])
        print("Decoding the encoded...")
        secret = decode(sys.argv[1], 3, 2, 3)
        output = Image.new("L", source.size)
        output.putdata(secret)
        output.save(sys.argv[2])
    elif sys.argv[1] == "encode":
        im = Image.open(sys.argv[1])
        print("Chopping Bits...")
        secret = hidden(sys.argv[1])
        print("Cooking the Pot...")
        messenger = carrier(sys.argv[2])
        print("Potting the Bits...")
        final = zip(secret, messenger)
        # In the first versions the variables used a disproportionate amount of
        # RAM
        del (secret)
        del (messenger)
        final = list(pool.map(add, final))
        final = list(pool.map(tuple, final))
        output = Image.new("RGB", im.size)
        output.putdata(final)
        output.save(sys.argv[3])
Пример #6
1
def forest_graph(trees, base_filename="tree-%i.png", forest_filename="forest.png"):
    x_spacing = 30
    y_spacing = 30
    filenames = [base_filename % i for i in range(len(trees))]
    thumbnames = []
    for (tree, filename) in zip(trees, filenames):
        tree_graph(tree, filename)
        thumbname = make_thumbnail(filename)
        thumbnames.append(thumbname)
    max_height = 0
    total_width = x_spacing
    thumbnails = []
    for thumbname in thumbnames:
        im = Image.open(thumbname)
        thumbnails.append(im)
        width, height = im.size
        if height > max_height:
            max_height = height
        total_width += width + x_spacing
    forest_im = Image.new("RGB", (total_width, max_height + 2 * y_spacing), color="#fff")
    x = x_spacing
    for thumbnail in thumbnails:
        width, height = thumbnail.size
        y = max_height - height + y_spacing
        forest_im.paste(thumbnail, (x, y))
        x += width + x_spacing
    # ipshell()
    forest_im = forest_im.resize((int(forest_im.size[0] * 0.5), int(forest_im.size[1] * 0.5)), Image.ANTIALIAS)
    forest_im.save(forest_filename)
Пример #7
1
    def image(self, img):
        """ Parse image and prepare it to a printable format """
        pixels = []
        pix_line = ""
        im_left = ""
        im_right = ""
        switch = 0
        img_size = [0, 0]

        if isinstance(img, Image.Image):
            im = img.convert("RGB")
        else:
            im = Image.open(img).convert("RGB")

        if im.size[0] > 512:
            print("WARNING: Image is wider than 512 and could be truncated at print time ")
        if im.size[1] > 255:
            raise ImageSizeError()

        im_border = self._check_image_size(im.size[0])
        if im_border[0] != 0 or im_border[1] != 0:
            new_size = (im.size[0] + (im_border[0] * 2), im.size[1] + (im_border[1] * 2))
            padded = Image.new("RGB", new_size, "white")
            offset = (int(im_border[0]), int(im_border[1]))
            padded.paste(im, offset)
            im = padded
            im_border = (0, 0)

        im = ImageChops.offset(im, -32, 0)

        for i in range(im_border[0]):
            im_left += "0"
        for i in range(im_border[1]):
            im_right += "0"

        for y in range(im.size[1]):
            img_size[1] += 1
            pix_line += im_left
            img_size[0] += im_border[0]
            for x in range(im.size[0]):
                img_size[0] += 1
                RGB = im.getpixel((x, y))
                im_color = RGB[0] + RGB[1] + RGB[2]
                im_pattern = "1X0"
                pattern_len = len(im_pattern)
                switch = (switch - 1) * (-1)
                for x in range(pattern_len):
                    if im_color <= (255 * 3 / pattern_len * (x + 1)):
                        if im_pattern[x] == "X":
                            pix_line += "%d" % switch
                        else:
                            pix_line += im_pattern[x]
                        break
                    elif im_color > (255 * 3 / pattern_len * pattern_len) and im_color <= (255 * 3):
                        pix_line += im_pattern[-1]
                        break
            pix_line += im_right
            img_size[0] += im_border[1]

        self._print_image(pix_line, img_size)
def hide_image(public_img, secret_img):
	s=4
	#the bits we are going to overwrite
	data = Image.open(public_img)
	#the bits we are going to write
	key  = ImageOps.autocontrast(Image.open(secret_img).resize(data.size))
	for x in range(data.size[0]):
		for y in range(data.size[1]):
			p = data.getpixel((x, y))
			q = key.getpixel((x, y))
			red   = p[0] - (p[0] % s) + (s * q[0] / 255)
			if(x > 200 and x < 206 and y > 200 and y < 206):
				print(p[0] - (p[0] % s) + (s * q[0] / 255),
					p[1] - (p[1] % s) + (s * q[1] / 255),
					p[2] - (p[2] % s) + (s * q[2] / 255))
				# print('p[0], q[0]')
				# print(p[0], q[0])
				# print('p[1],q[1]')
				# print(p[1],q[1])
				# print('p[2],q[2]')
				# print(p[2],q[2])
			green = p[1] - (p[1] % s) + (s * q[1] / 255)
			blue  = p[2] - (p[2] % s) + (s * q[2] / 255)
			data.putpixel((x,y), (red,green,blue))
			# if (red > 100 and green < 100 and blue < 100):
				# print('x,y')
				# print(x, y)
				# print('Cover IMG, Hide Image')
				# print(p,q)
				# print('R,G,B')
				# print(red,green,blue)
	return data
Пример #9
1
def generate(filename, w, h):
    print filename
    data = open(filename).read()

    thin_file = open(filename + "SHADOWTHIN", "w")
    thick_file = open(filename + "SHADOWTHICK", "w")
    bloat_file = open(filename + "BLOAT", "w")

    linesize = int(math.ceil(w / 8.0))
    charsize = linesize * h

    chars = [data[i * charsize : (i + 1) * charsize] for i in xrange(len(data) / charsize)]

    for char in chars:
        charimg = PIL.fromstring("1", (w, h), char)
        paste = PIL.new("1", (w + 4, h + 4))
        paste.paste(charimg, (2, 2))
        bloat_file.write(paste.tostring())

        img = Image(paste)
        img = img.convolve([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
        thin = PIL.fromstring("RGB", (w + 4, h + 4), img.toString()).convert("1").tostring()
        thin_file.write(thin)
        img = img.dilate()
        thick = PIL.fromstring("RGB", (w + 4, h + 4), img.toString()).convert("1").tostring()
        thick_file.write(thick)
Пример #10
1
def genVideoThumb(videofile, imagefile):
    (width, height) = get_video_size(videofile)
    frame_step = int(100 / THUMB_FRAME_COUNT)
    ratio = float(width) / float(height)
    if width > LIBRARYFILE_THUMB_WIDTH:
        width = LIBRARYFILE_THUMB_WIDTH
        height = int(width / ratio)
    if height > LIBRARYFILE_THUMB_HEIGHT:
        height = LIBRARYFILE_THUMB_HEIGHT
        width = int(height * ratio)
    width_offset = (LIBRARYFILE_THUMB_WIDTH - width) / 2
    height_offset = int((LIBRARYFILE_THUMB_HEIGHT - height) / 2)
    new_image = pil.new("RGB", (LIBRARYFILE_THUMB_WIDTH * THUMB_FRAME_COUNT, LIBRARYFILE_THUMB_HEIGHT))
    for i in range(THUMB_FRAME_COUNT):
        framefile = "%s%d.jpg" % (imagefile, i)
        # TODO: fix keyframing issue (perhaps flvtool2?)
        os.system(
            "ffmpegthumbnailer -i %s -o %s -t %d%% -q %d -s %d"
            % (videofile, framefile, i * frame_step, JPEG_QUALITY, width)
        )
        img = pil.open(framefile)
        new_image.paste(img, (LIBRARYFILE_THUMB_WIDTH * i + width_offset, height_offset))
        os.remove(framefile)
    new_image.save(imagefile)
    return True
Пример #11
1
    def xtest_smoke(self):
        cam = camera.Camera((389.0, 389.0, 89.23, 323.42, 323.42, 274.95))
        vo = VisualOdometer(cam)
        vo.reset_timers()
        dir = "/u/konolige/vslam/data/indoor1/"

        trail = []
        prev_scale = None

        schedule = [(f + 1000) for f in (range(0, 100) + range(100, 0, -1) + [0] * 10)]
        schedule = range(1507)
        schedule = range(30)
        for f in schedule:
            lf = Image.open("%s/left-%04d.ppm" % (dir, f))
            rf = Image.open("%s/right-%04d.ppm" % (dir, f))
            lf.load()
            rf.load()
            af = SparseStereoFrame(lf, rf)

            vo.handle_frame(af)
            print f, vo.inl
            trail.append(numpy.array(vo.pose.M[0:3, 3].T)[0])

        def d(a, b):
            d = a - b
            return sqrt(numpy.dot(d, d.conj()))

        print "covered   ", sum([d(a, b) for (a, b) in zip(trail, trail[1:])])
        print "from start", d(trail[0], trail[-1]), trail[0] - trail[-1]

        vo.summarize_timers()
        print vo.log_keyframes
Пример #12
1
    def __init__(self, image=None, **kw):

        # Tk compatibility: file or data
        if image is None:
            if kw.has_key("file"):
                image = Image.open(kw["file"])
                del kw["file"]
            elif kw.has_key("data"):
                from StringIO import StringIO

                image = Image.open(StringIO(kw["data"]))
                del kw["data"]

        self.__mode = image.mode
        self.__size = image.size

        if _pilbitmap_check():
            # fast way (requires the pilbitmap booster patch)
            image.load()
            kw["data"] = "PIL:%d" % image.im.id
            self.__im = image  # must keep a reference
        else:
            # slow but safe way
            kw["data"] = image.tobitmap()
        self.__photo = apply(Tkinter.BitmapImage, (), kw)
Пример #13
0
def local_bitmap(source, config, coord, dim):
    """ Return Blit.Bitmap representation of a raw image.
    """
    address = urljoin(config.dirpath, source)
    bytes = urlopen(address).read()
    image = Image.open(StringIO(bytes)).convert("RGBA")

    coord = coord.zoomBy(8)
    w, h, col, row = image.size[0], image.size[1], int(coord.column), int(coord.row)

    x = w * (col / w) - col
    y = h * (row / h) - row

    output = Image.new("RGBA", (dim, dim))

    for (x, y) in product(range(x, dim, w), range(y, dim, h)):
        # crop the top-left if needed
        xmin = 0 if x > 0 else -x
        ymin = 0 if y > 0 else -y

        # don't paste up and to the left
        x = x if x >= 0 else 0
        y = y if y >= 0 else 0

        output.paste(image.crop((xmin, ymin, w, h)), (x, y))

    return Blit.Bitmap(output)
Пример #14
0
def create_css_sprite(image_names, icons_path, sprite_filename):
    sprite_images = []
    external_images = []
    image_width = []
    image_height = []
    for fname in sorted(image_names):
        fpath = os.path.join(icons_path, fname)
        if not os.path.isfile(fpath):
            external_images.append(fname)
            continue

        if ".svg" in fpath:
            image = open_svg_as_image(fpath)
        else:
            image = Image.open(fpath)
        sprite_images.append({"name": fname, "size": image.size, "image": image})
        image_width.append(image.size[0])
        image_height.append(image.size[1])

    if not sprite_images:
        return (sprite_images, external_images)

    sprite_size = (max(image_width), sum(image_height))
    sprite = Image.new(mode="RGBA", size=sprite_size, color=(0, 0, 0, 0))

    offset = 0
    for data in sprite_images:
        data["offset"] = offset
        sprite.paste(data["image"], (0, offset))
        offset += data["size"][1]
    sprite.save(sprite_filename)

    return (sprite_images, external_images)
Пример #15
0
def sprite():
    """Regenerate sprites"""
    import Image

    conf = {
        "imgdir": "content/media/images/l/sprites",
        "sprite": "content/media/images/l/sprite.png",
        "css": "content/media/css/luffy.sprite.less",
        "class": "lf-sprite",
        "spacer": 2,
    }
    images = glob.glob(os.path.join(conf["imgdir"], "*.png"))
    images.sort()

    print "[+] Generate sprites for %s" % ", ".join([os.path.basename(i) for i in images])
    css = """/* -*- css -*- */
/* Autogenerated. */

.%(class)s {
    background: url('%(sprite)s') no-repeat left top;
    display: inline-block;
}
""" % {
        "class": conf["class"],
        "sprite": os.path.relpath(conf["sprite"], os.path.dirname(conf["css"])),
    }

    # Get the total height and max width
    width = 0
    height = 0
    for image in images:
        im = Image.open(image)
        height += im.size[1]
        if im.size[0] > width:
            width = im.size[0]
    height += (len(images) - 1) * conf["spacer"]
    sprite = Image.new("RGBA", (width, height))
    height = 0
    for image in images:
        im = Image.open(image)
        sprite.paste(im, (0, height))
        css += """
.%(class)s-%(name)s {
    .%(class)s;
    background-position: 0px %(offset)spx;
    width: %(width)spx;
    height: %(height)spx;
}
""" % {
            "class": conf["class"],
            "name": os.path.basename(image).split(".")[0],
            "offset": -height,
            "width": im.size[0],
            "height": im.size[1],
        }
        height += im.size[1] + conf["spacer"]
    print "[+] Write sprite to %s" % conf["sprite"]
    sprite.save(conf["sprite"], "PNG", optimize=True)
    print "[+] Write CSS to %s" % conf["css"]
    file(conf["css"], "w").write(css)
Пример #16
0
    def test_derivative_permissions(self):
        Media.objects.filter(record=self.record).delete()
        media = Media.objects.create(record=self.record, name="tiff", mimetype="image/tiff", storage=self.storage)
        with open(os.path.join(os.path.dirname(__file__), "test_data", "dcmetro.tif"), "rb") as f:
            media.save_file("dcmetro.tif", f)

        user1 = User.objects.create(username="test1890723589075")
        user2 = User.objects.create(username="test2087358972359")

        AccessControl.objects.create(content_object=self.collection, user=user1, read=True)
        AccessControl.objects.create(content_object=self.collection, user=user2, read=True)

        AccessControl.objects.create(content_object=self.storage, user=user1, read=True)
        AccessControl.objects.create(
            content_object=self.storage, user=user2, read=True, restrictions=dict(width=200, height=200)
        )

        result1 = get_image_for_record(self.record, width=400, height=400, user=user1)
        result2 = get_image_for_record(self.record, width=400, height=400, user=user2)

        self.assertEqual(400, Image.open(result1).size[0])
        self.assertEqual(200, Image.open(result2).size[0])

        result3 = get_image_for_record(self.record, width=400, height=400, user=user2)
        self.assertEqual(result2, result3)

        media.delete()
Пример #17
0
 def process_zipfile(self):
     if os.path.isfile(self.zip_file.path):
         # TODO: implement try-except here
         zipf = zipfile.ZipFile(self.zip_file.path)
         bad_file = zipf.testzip()
         if bad_file:
             raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
         if not self.album:
             self.album = Album(title=self.title, date=datetime.datetime.now())
             self.album.save()
         for filename in sorted(zipf.namelist()):
             if filename.startswith("__"):  # do not process meta files
                 continue
             data = zipf.read(filename)
             if len(data):
                 try:
                     # the following is taken from django.newforms.fields.ImageField:
                     #  load() is the only method that can spot a truncated JPEG,
                     #  but it cannot be called sanely after verify()
                     trial_image = PyImage.open(StringIO(data))
                     trial_image.load()
                     # verify() is the only method that can spot a corrupt PNG,
                     #  but it must be called immediately after the constructor
                     trial_image = PyImage.open(StringIO(data))
                     trial_image.verify()
                 except Exception, e:
                     # if a "bad" file is found we just skip it.
                     continue
                 img = Image(title="", text="", date_taken=datetime.datetime.now())
                 img.image.save(filename, ContentFile(data))
                 img.save(date_from_image=True)
                 self.album.images.add(img)
         zipf.close()
def procesamiento_imagen():    
	## Convertir a grayscale
	img = Image.open(rostro).convert('LA')
	img.save('greyscale.png')

	## Resize

	foo = Image.open("greyscale.png")
	foo = foo.resize((256,256),Image.ANTIALIAS)
	foo.save("greyscale.png",optimize=True,quality=95)	


	##  Eliminar ruido
	img = cv2.imread('greyscale.png')
	dst = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)

	## Canny detector
	img = cv2.imread('greyscale.png',0)
	edges = cv2.Canny(img,256,256)

	plt.subplot(121),plt.imshow(img,cmap = 'gray')
	plt.title('Original Image'), plt.xticks([]), plt.yticks([])
	plt.subplot(122),plt.imshow(edges,cmap = 'gray')
	plt.title('Edge Image'), plt.xticks([]), plt.yticks([])

	plt.show()
Пример #19
0
    def make_bundle(self, versioner):
        import Image  # If this fails, you need the Python Imaging Library.

        boxes = [ImageBox(Image.open(path), path) for path in self.get_paths()]
        # Pick a max_width so that the sprite is squarish and a multiple of 16,
        # and so no image is too wide to fit.
        total_area = sum(box.width * box.height for box in boxes)
        width = max(max(box.width for box in boxes), (int(math.sqrt(total_area)) // 16 + 1) * 16)
        (_, height, packing) = pack_boxes(boxes, width)
        sprite = Image.new("RGBA", (width, height))
        for (left, top, box) in packing:
            # This is a bit of magic to make the transparencies work. To
            # preserve transparency, we pass the image so it can take its
            # alpha channel mask or something. However, if the image has no
            # alpha channels, then it fails, we we have to check if the
            # image is RGBA here.
            img = box.image
            mask = img if img.mode == "RGBA" else None
            sprite.paste(img, (left, top), mask)
        sprite.save(self.get_bundle_path(), "PNG")
        self._optimize_output()
        # It's *REALLY* important that this happen here instead of after the
        # generate_css() call, because if we waited, the CSS woudl have the URL
        # of the last version of this bundle.
        if versioner:
            versioner.update_bundle_version(self)
        self.generate_css(packing)
Пример #20
0
def watermark(im, mark, position, opacity=1):
    """Adds a watermark to an image.
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
    """
    if opacity < 1:
        mark = reduce_opacity(mark, opacity)
    if im.mode != "RGBA":
        im = im.convert("RGBA")
    # create a transparent layer the size of the image and draw the
    # watermark in that layer.
    layer = Image.new("RGBA", im.size, (0, 0, 0, 0))
    if position == "tile":
        for y in range(0, im.size[1], mark.size[1]):
            for x in range(0, im.size[0], mark.size[0]):
                layer.paste(mark, (x, y))
    elif position == "scale":
        # scale, but preserve the aspect ratio
        ratio = min(float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
        w = int(mark.size[0] * ratio)
        h = int(mark.size[1] * ratio)
        mark = mark.resize((w, h))
        layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
    else:
        layer.paste(mark, position)
    # composite the watermark with the layer
    return Image.composite(layer, im, layer)
Пример #21
0
 def __init__(self, width, height=None):
     """
     Takes either a single string for a filename, or width and
     height of an empty picture.
     """
     if height:
         self.image = Image.new("RGB", (width, height))
         self.title = "Picture"
         self.width = width
         self.height = height
     else:
         self.image = Image.open(width)  # actually filename
         self.title = width
         self.width, self.height = self.image.size
     # Default values for pen
     self.pen_color = (0, 0, 0)
     self.pen_position = (0, 0)
     self.pen_width = 1
     self.pen_rotation = 0
     # Pixel data of the image
     self.pixel = self.image.load()
     # Draw object of the image
     self.draw = ImageDraw.Draw(self.image)
     # The main window, and associated widgets.
     self.root = None
     self.canvas = None
Пример #22
0
    def _generate_thumbnail(self):
        """
        Be aware that this function handle very badly remote backends such as
        s3. You can add in your save() method something like::

            if 's3boto' in settings.DEFAULT_FILE_STORAGE:
                self.external_url = self.image.file.url
        """
        image = None
        if self.external_url:
            import urllib

            filepath, headers = urllib.urlretrieve(self.external_url)
            image = PilImage.open(filepath)
            filename = os.path.basename(filepath)
        elif self.file:
            image = PilImage.open(self.file.path)
            filename = os.path.basename(self.file.name)
        if image is None:
            return
        if image.mode not in ("L", "RGB"):
            image = image.convert("RGB")
        image.thumbnail(THUMB_SIZE, PilImage.ANTIALIAS)

        destination = StringIO()
        image.save(destination, format="JPEG")
        destination.seek(0)

        self.thumbnail.save(filename, ContentFile(destination.read()))
    def testExecute(self):
        """
        """
        self.run()
        plugin = self.getPlugin()
        ################################################################################
        # Compare XSDataResults
        ################################################################################
        strExpectedOutput = self.readAndParseFile(self.getReferenceDataOutputFile())
        EDVerbose.DEBUG("Checking obtained result...")

        xsDataResultObtained = plugin.getDataOutput()
        EDAssert.strAlmostEqual(
            self.xsDataResultReference.marshal(), xsDataResultObtained.marshal(), "XSDataResult output are the same"
        )
        ################################################################################
        # Compare image Files
        ################################################################################
        outputData = Image.open(self.outputFile)
        referenceData = Image.open(os.path.join(self.getTestsDataImagesHome(), os.path.basename(self.outputFile)))
        delta = ImageChops.difference(outputData, referenceData)
        deltaColor = delta.getextrema()
        i = 0
        for color in deltaColor:
            EDAssert.lowerThan(color[1], 12, "Maximum tone variation is %s for channel %s" % (color[1], "RGBA"[i]))
            i += 1
Пример #24
0
def compare(name1, name2):
    img = Image.open(name1).convert("LA")
    img2 = Image.open(name2).convert("LA")

    width, height = img.size

    pixels = list(img.getdata())
    pixels2 = list(img2.getdata())

    pixels = [pixels[i * width : (i + 1) * width] for i in xrange(height)]
    pixels2 = [pixels2[i * width : (i + 1) * width] for i in xrange(height)]

    result = []
    sums = [0, 0]
    for i, x in enumerate(pixels):
        for j, y in enumerate(x):
            sums[0] += y[0]
            sums[1] += pixels2[i][j][0]
            result.append(abs(y[0] - pixels2[i][j][0]))

    avg = sum(result) / (width * height)
    avgdiff = [x - avg for x in result if x >= avg]

    result2 = sum(avgdiff) / (width * height)
    return max(avgdiff), result2, avg, sums
Пример #25
0
def make_tile(fname, out, rot=0):
    image = prep_image(fname)
    image = image.rotate(rot, expand=1)

    # chop added extra pixels by expanding
    d = quality * 4
    dx, dy = image.size
    image = image.crop((d, d, dx - d, dy - d)).copy()

    # Scale Y-axis
    # convert -resample is much better than PIL.
    # ideally we'd use GIMP ...
    image.save("in.png")
    os.system("convert in.png -resample %dx%d  out.png" % (size[0] * quality, size[1] * quality))
    image = Image.open("out.png")

    # Apply tilemask
    w, h = image.size
    tmask, imask = make_tilemasks((w, h))
    tile = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    tile.paste(image, tmask)

    # Again convert -resize is better ...
    tile.save("in.png")
    os.system("convert in.png -resize %dx%d out.png" % (size))
    image = Image.open("out.png")
    image.save(out)
Пример #26
0
def ChopTiles(fileName, newFileName, oldcols, newcols):
    global im, newim
    im = Image.open(fileName)
    width, height = im.size
    print "NEWCOLS", newcols
    print "WIDTH", width, "HEIGHT", height
    cols = 1
    rows = height / width
    print fileName, width, height, im

    newwidth = width * newcols
    newheight = int(math.ceil(height / newcols))
    newrows = newheight / width

    print "NEWWIDTH", newwidth, "NEWHEIGHT", newheight, "NEWCOLS", newcols, "NEWROWS", newrows

    newim = Image.new(im.mode, (newwidth, newheight))

    for cell in range(0, newrows * newcols):
        oldcol = int(cell % oldcols)
        oldrow = int(math.floor(cell / oldcols))
        frombox = (0, cell * width, width, (cell + 1) * width)

        newcol = int(cell % newcols)
        newrow = int(math.floor(cell / newcols))
        tobox = (newcol * width, newrow * width, (newcol + 1) * width, (newrow + 1) * width)

        tile = im.crop(frombox)
        newim.paste(tile, tobox)

    newim.save(newFileName)
Пример #27
0
def getTargets(screen):  # TODO
    """Get the words from the screen. (This will be the hard part.)"""
    (width, height) = screen.size
    # screen.save('screen'+str(cnt)+'.png')
    blobs = screen.convert("L")
    blobs = np.array(blobs)
    # blobs=screen.
    leftmost = 0
    targets = []
    for y in range(width):
        for x in range(height):
            if blobs[x, y] < 20:
                print(x, y)
                if y + 200 <= width:
                    targets.append(np.copy(blobs[x - 20 : x + 20, y : y + 200]))
                blobs[x - 30 : x + 30, y : y + 200] = 255
                # Image.fromarray(blobs).show()
                # raw_input('')
                if leftmost == 0:
                    leftmost = y
    cnt = 0
    for target in targets:
        Image.fromarray(target).save("target" + str(cnt) + ".png")
        cnt = cnt + 1
    return targets
    """words=[]
Пример #28
0
def write_image(img, fname, apply_gamma=False):
    """Save a float-3 numpy array image to a file.

    Supported formats: PNG, JPEG, and others; see PIL docs for more.

    Image can be 3-channel, which is interpreted as RGB, or can be 1-channel,
    which is greyscale.

    Can optionally specify that the image should be gamma-encoded prior to
    writing it out; this should be done if the image contains linear pixel
    values, to make the image look "normal".

    Args:
        img: Numpy image array data.
        fname: Path of file to save to; the extension specifies the format.
        apply_gamma: (Optional) apply gamma to the image prior to writing it.
    """
    if apply_gamma:
        img = apply_lut_to_image(img, DEFAULT_GAMMA_LUT)
    (h, w, chans) = img.shape
    if chans == 3:
        Image.fromarray((img * 255.0).astype(numpy.uint8), "RGB").save(fname)
    elif chans == 1:
        img3 = (img * 255.0).astype(numpy.uint8).repeat(3).reshape(h, w, 3)
        Image.fromarray(img3, "RGB").save(fname)
    else:
        raise its.error.Error("Unsupported image type")
Пример #29
0
def repack_rle_565(rawfile, rlefile, function):

    if rawfile[-4:] != ".raw":
        try:
            import Image
        except ImportError:
            sys.stderr.write("Please Install PIL (python-imaging)\n")
            return None
        try:
            img = Image.open(rawfile)
        except:
            sys.stderr.write("Cannot Open Image File")
            return None

        from JpegImagePlugin import RAWMODE

        if "transparency" in img.info or img.mode == "RGBA":
            new = img.mode == "RGBA" and img or img.convert("RGBA")
            img = Image.new("RGB", new.size)
            img.paste(new, (0, 0), new)
        elif img.mode not in RAWMODE:
            img = img.convert("RGB")

        if img.size not in list(SIZE.values()):
            sys.stderr.write("warning: Image is not HVGA, [W]QVGA, WVGA\n")

        rawfile = rlefile[:-4] + ".raw"
        data = open(rawfile, "wb")
        data.write(img.tostring())
        data.close()

    raw = open(rawfile, "rb")
    rle = open(rlefile, "wb")
    function(raw, rle)
Пример #30
0
def generate():
    random.seed(1337)
    func = get_value_random
    func_name = ""

    if "inverse" == sys.argv[1]:
        func = get_value_inverse
        func_name = "inverse"
    else:
        func = get_value_random
        func_name = "noise"

    path = sys.argv[2]
    name = path.split("/")[-1].split(".")[0]

    for porcentage in range(10, 101, 10):
        origin = Image.open(path)
        dest = Image.new("RGB", (64, 64), "black")

        pixels_origin = origin.load()
        pixels_dest = dest.load()

        for i in xrange(dest.size[1]):
            for j in xrange(dest.size[0]):
                if random.randint(0, 100) <= porcentage:
                    pixels_dest[j, i] = func(pixels_origin[j, i], True)
                else:
                    pixels_dest[j, i] = func(pixels_origin[j, i], False)

        dest.save("%s_%s_%s.png" % (name, func_name, str(porcentage)))