Example #1
0
    def test_save_screenshot_valid(self, tmpdir):
        """Check that 'save_screenshot' works"""
        # Run the test crawl
        manager_params, browser_params = self.get_config(str(tmpdir))
        manager = TaskManager.TaskManager(manager_params, browser_params)
        cs = CommandSequence.CommandSequence(url_a)
        cs.get(sleep=1)
        cs.save_screenshot('test')
        cs.screenshot_full_page('test_full')
        manager.execute_command_sequence(cs)
        manager.close()

        # Check that viewport image is not blank
        pattern = os.path.join(str(tmpdir), 'screenshots', '1-*-test.png')
        screenshot = glob.glob(pattern)[0]
        im = Image.open(screenshot)
        bands = im.split()
        is_blank = all(band.getextrema() == (255, 255) for band in bands)
        assert not is_blank

        # Check that full page screenshot is not blank
        pattern = os.path.join(str(tmpdir), 'screenshots', '1-*-test_full.png')
        screenshot = glob.glob(pattern)[0]
        im = Image.open(screenshot)
        bands = im.split()
        is_blank = all(band.getextrema() == (255, 255) for band in bands)
        assert not is_blank
Example #2
0
File: tests.py Project: agoya/glue
    def test_project_manager(self):
        manager = self.generate_manager(glue.ProjectSpriteManager, 'multiple')
        manager.process()

        rgb_img_path = os.path.join(self.output_path, 'rgb.png')
        rgb_css_path = os.path.join(self.output_path, 'rgb.css')
        mix_img_path = os.path.join(self.output_path, 'mix.png')
        mix_css_path = os.path.join(self.output_path, 'mix.css')
        self.assertTrue(os.path.isfile(rgb_img_path))
        self.assertTrue(os.path.isfile(rgb_css_path))
        self.assertTrue(os.path.isfile(mix_img_path))
        self.assertTrue(os.path.isfile(mix_css_path))

        image = Image.open(rgb_img_path)
        css = open(rgb_css_path)

        self.assertEqual(image.getpixel((0, 0)), RED)
        self.assertEqual(image.getpixel((25, 0)), GREEN)
        self.assertEqual(image.getpixel((0, 25)), BLUE)
        self.assertEqual(image.getpixel((25, 25)), TRANSPARENT)

        self.assertEqualCSS(css.read(), EXPECTED_PROJECT_RGB_CSS)
        css.close()

        image = Image.open(mix_img_path)
        css = open(mix_css_path)

        self.assertEqual(image.getpixel((0, 0)), YELLOW)
        self.assertEqual(image.getpixel((25, 0)), PINK)
        self.assertEqual(image.getpixel((0, 25)), CYAN)
        self.assertEqual(image.getpixel((25, 25)), TRANSPARENT)

        self.assertEqualCSS(css.read(), EXPECTED_PROJECT_MIX_CSS)
        css.close()
Example #3
0
    def draw_articulations(self, count, length, radius, line_thickness, ring_thickness):
        canvas_size = radius * 2 + length
        canvas_c = (canvas_size / 2.0, canvas_size / 2.0)
        half_len = length / 2.0
        theta = 360.0 / count
        
        canvas = Image.new("RGB", [canvas_size, canvas_size], tuple(LIGHTGREY[:3]))
        mask = Image.new('L', [canvas_size, canvas_size], 0)
        mask_surf = aggdraw.Draw(mask)

        line_pen = aggdraw.Pen(255, line_thickness)
        ring_pen = aggdraw.Pen(0, ring_thickness)
        transparent_brush = aggdraw.Brush((255, 0, 0), 0)
        
        # Draw articulations
        for i in range(0, count):
            start = util.point_pos(canvas_c, radius-half_len, angle=theta*i)
            end = util.point_pos(canvas_c, radius+half_len, angle=theta*i)
            mask_surf.line((start[0], start[1], end[0], end[1]), line_pen)
        
        # Draw ring mask for articulations
        xy_1 = canvas_c[0] - radius
        xy_2 = canvas_c[0] + radius
        mask_surf.ellipse([xy_1, xy_1, xy_2, xy_2], ring_pen, transparent_brush)
        mask_surf.flush()
        
        # Apply ring mask to articulations
        canvas.putalpha(mask)
        
        return np.asarray(canvas)
Example #4
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 #5
0
def translate(name,text):
    path = sys.path[0]+"\TP\\"
    im = Image.open(path+"space.bmp")
    line = text.split("@")
    length = 0
    for i in line:
        if len(i) > length:
            length = len(i)
    height = len(line)
    length *= 42
    height *= 40
    diagram = Image.new("RGBA",(length,height),(255,255,255))
    longest = 0
    for i in range(0,len(line)):
        letters = []
        pos = 0
        for j in range(0,len(line[i])):
            temp = convert(line[i][j])
            if(temp != "null"):
                letters.append(temp)
        for j in range(0,len(letters)):
            k = len(letters)-j-1
            im = Image.open(path+letters[k]+".bmp")
            (le,up,ri,bo) = im.getbbox()
            diagram.paste(im,(pos,i*40,pos+ri,(i+1)*40))
            pos+=ri+1
        if(pos > longest):
            longest = pos
    diagram = diagram.crop((0,0,longest-1,len(line)*40))
    diagram.save(path+name+".png")
    diagram.show()
Example #6
0
 def _apply_watermark(self, datafile):
     text = self.aq_parent.watermark_text
     FONT = os.path.join(os.path.dirname(__file__), 'fonts', 'VeraSeBd.ttf')
     img = Image.open(datafile)
     newimg = StringIO()
     fmt = img.format
     watermark = Image.new("RGBA", (img.size[0], img.size[1]))
     draw = ImageDraw.ImageDraw(watermark, "RGBA")
     size = 0
     while True:
         size += 1
         nextfont = ImageFont.truetype(FONT, size)
         nexttextwidth, nexttextheight = nextfont.getsize(text)
         if nexttextwidth+nexttextheight/3 > watermark.size[0]:
             break
         font = nextfont
         textwidth, textheight = nexttextwidth, nexttextheight
     draw.setfont(font)
     draw.text(((watermark.size[0]-textwidth)/2,
                (watermark.size[1]-textheight)/2), text)
     watermark = watermark.rotate(degrees(atan(float(img.size[1])/img.size[0])),
                              Image.BICUBIC)
     mask = watermark.convert("L").point(lambda x: min(x, 88))
     watermark.putalpha(mask)
     img.paste(watermark, None, watermark)
     quality = self._photo_quality(datafile)
     img.save(newimg, fmt, quality=quality)
     newimg.seek(0)
     return newimg
def test_write_svg_to_png(filename):
    # If you want to regenerate these, e.g. the svg template has significantly
    # changed, easiest way is to patch write_svg_to_png to not delete the
    # temporary file (delete:False in temp_args) and copy the svg out of /tmp.
    # Output png files are in user-media/version-previews/full and /thumbs.
    out = tempfile.mktemp()
    svg_xml = os.path.join(
        settings.ROOT,
        'src/olympia/versions/tests/static_themes/%s.svg' % filename)
    svg_png = os.path.join(
        settings.ROOT,
        'src/olympia/versions/tests/static_themes/%s.png' % filename)
    with storage.open(svg_xml, 'rb') as svgfile:
        svg = svgfile.read()
    write_svg_to_png(svg, out)
    assert storage.exists(out)
    # compare the image content. rms should be 0 but travis renders it
    # different... 3 is the magic difference.
    svg_png_img = Image.open(svg_png)
    svg_out_img = Image.open(out)
    image_diff = ImageChops.difference(svg_png_img, svg_out_img)
    sum_of_squares = sum(
        value * ((idx % 256) ** 2)
        for idx, value in enumerate(image_diff.histogram()))
    rms = math.sqrt(
        sum_of_squares / float(svg_png_img.size[0] * svg_png_img.size[1]))

    assert rms < 3
Example #8
0
def downloader(opener, filename, s, jpg=None, png=None):
    s.acquire()
    try:
        if not os.path.exists(filename):
            log("Download %s" % (filename))
            try:
                page = opener.open(jpg)
                dJPG = page.read()
                imageStringJPG = cStringIO.StringIO(dJPG)
                imageStringJPG.seek(0)
                page.close()
            except urllib2.HTTPError, e:
                imageStringJPG = ""
                log("Error %s" % (e))
            
            try:
                page = opener.open(png)
                dPNG = page.read()
                imageStringPNG = cStringIO.StringIO(dPNG)
                imageStringPNG.seek(0)
                page.close()
            except urllib2.HTTPError, e:
                imageStringPNG = ""
                log("Error %s" % (e))
                
            if imageStringJPG and imageStringPNG:
                imageJPG = Image.open(imageStringJPG)
                imagePNG = Image.open(imageStringPNG)
                A = imagePNG.convert('RGBA').split()[-1]
                imageJPG.paste(imagePNG, A)
                imageJPG.save(filename, quality=100)
                imageStringJPG.close()
                imageStringPNG.close()
def run_me(run_time=None):

    if run_time:
        start_time = time.time()

    # inp_paths = [os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Output', 'Two Crop test.png')]

    inp_paths = [os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Input', 'Two Crop test.png'),
                 os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Input', 'Two Crop test2.png')]
    orig_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Input', 'Two Infrared test.png')
    out_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Output', 'UnCropResult.png')

    orig = Image.open(orig_path)

    for img_path in inp_paths:
        try:
            img = Image.open(img_path)
            main(img, orig)
        except Exception as e:
            img = Image.open(img_path)
            main(img.transpose(Image.FLIP_LEFT_RIGHT), orig.transpose(Image.FLIP_LEFT_RIGHT))

    # img = Image.open('Input/Two Crop test3.png')
    #
    # ret = main(img, ret)
    # ret.show()

    if run_time:
        print("\n--- %s seconds ---" % (time.time() - start_time))
def fix_generated_thumbs(file, is_verbose, fix_thumb):
    try:
        cover = Image.open(file)
    except IOError:
        return False
    try:
        dpi = cover.info["dpi"]
    except KeyError:
        dpi = (96, 96)
    if dpi == (96, 96) and fix_thumb:
        if is_verbose:
            print('* Fixing generated thumbnail "%s"...' % (file))
        pdoc_cover = Image.new("L", (cover.size[0], cover.size[1] + 45),
                               "white")
        pdoc_cover.paste(cover, (0, 0))
        pdoc_cover.save(file, dpi=[72, 72])
    elif dpi == (72, 72) and not fix_thumb:
        if is_verbose:
            print('* Reverse fix for generated thumbnail "%s"...' % (file))
        pdoc_cover = Image.new("L", (cover.size[0], cover.size[1] - 45),
                               "white")
        pdoc_cover.paste(cover, (0, 0))
        pdoc_cover.save(file, dpi=[96, 96])
    else:
        if is_verbose:
            print('* Generated thumbnail "%s" is OK. DPI: %s. Skipping...'
                  % (os.path.basename(file), dpi))
    return False
Example #11
0
def save_sample_pictures():
    for te_train, te_target in test_stream.get_epoch_iterator():
        break
    te_out, te_ta = ae_encode(input_transform(te_train), target_transform(te_target))
    te_reshape = inverse(te_out)
    te_target_reshape = inverse(te_ta)

    new_size = (128 * 6, 160 * 12)
    new_im = Image.new('RGB', new_size)
    r = np.random.choice(128, 24, replace=False).reshape(2,12)
    for i in range(2):
        for j in range(12):
            index =  r[i][j]
            a1 = np.concatenate((te_train[index],te_target_reshape[index]),axis=2)
            a1 = YUV2RGB(a1)
            a2 = np.concatenate((te_train[index],te_train[index]),axis=2)
            a2 = np.concatenate((a2,te_train[index]),axis=2)
            a3 = np.concatenate((te_train[index],te_reshape[index]),axis=2)
            a3 = YUV2RGB(a3)
            target_im = Image.fromarray(a1.astype(np.uint8))
            train_im = Image.fromarray(a2.astype(np.uint8))
            im = Image.fromarray(a3.astype(np.uint8))
            
            new_im.paste(target_im, (128 * i * 3, 160 * j))
            new_im.paste(train_im, (128 * (i * 3 + 1), 160 * j))
            new_im.paste(im, (128 * (i * 3 + 2), 160 * j))
    img_loc = "/data/chencj/Face/gen_images/%i.png" %int(time())     
    print "saving images to %s" %img_loc
    new_im.save(img_loc)
def test_sanity():

    im1 = lena()
    im2 = Image.new(im1.mode, im1.size, 0)

    for y in range(im1.size[1]):
        for x in range(im1.size[0]):
            pos = x, y
            im2.putpixel(pos, im1.getpixel(pos))
    
    assert_image_equal(im1, im2)

    im2 = Image.new(im1.mode, im1.size, 0)
    im2.readonly = 1

    for y in range(im1.size[1]):
        for x in range(im1.size[0]):
            pos = x, y
            im2.putpixel(pos, im1.getpixel(pos))
    
    assert_false(im2.readonly)
    assert_image_equal(im1, im2)

    im2 = Image.new(im1.mode, im1.size, 0)

    pix1 = im1.load()
    pix2 = im2.load()

    for y in range(im1.size[1]):
        for x in range(im1.size[0]):
            pix2[x, y] = pix1[x, y]

    assert_image_equal(im1, im2)
Example #13
0
def load(filepath, rescale=True, dtype='float64'):
    assert type(filepath) == str

    if rescale == False and dtype == 'uint8':
        rval = np.asarray(Image.open(filepath))
        # print 'image.load: ' + str((rval.min(), rval.max()))
        assert rval.dtype == 'uint8'
        return rval

    s = 1.0
    if rescale:
        s = 255.
    try:
        rval = Image.open(filepath)
    except:
        raise Exception("Could not open "+filepath)

    rval = np.cast[dtype](np.asarray(rval)) / s

    if len(rval.shape) == 2:
        rval = rval.reshape(rval.shape[0], rval.shape[1], 1)

    if len(rval.shape) != 3:
        raise AssertionError("Something went wrong opening " +
                filepath + '. Resulting shape is ' + str(rval.shape) +
                " (it's meant to have 3 dimensions by now)")

    return rval
Example #14
0
    def check(self, mode, c=None):
        if not c:
            c = self.color(mode)

        # check putpixel
        im = Image.new(mode, (1, 1), None)
        im.putpixel((0, 0), c)
        self.assertEqual(
            im.getpixel((0, 0)), c,
            "put/getpixel roundtrip failed for mode %s, color %s" % (mode, c))

        # Check 0
        im = Image.new(mode, (0, 0), None)
        with self.assertRaises(IndexError):
            im.putpixel((0, 0), c)
        with self.assertRaises(IndexError):
            im.getpixel((0, 0))

        # check initial color
        im = Image.new(mode, (1, 1), c)
        self.assertEqual(
            im.getpixel((0, 0)), c,
            "initial color failed for mode %s, color %s " % (mode, c))

        # Check 0
        im = Image.new(mode, (0, 0), c)
        with self.assertRaises(IndexError):
            im.getpixel((0, 0))
Example #15
0
File: tests.py Project: jmg/fedex
    def test_shipment_service(self):
        """Test the shipment service.
        """
        service = ShipmentService(CONFIGURATION)
        shipment = service.create_shipment()
        shipment.ShipTimestamp = datetime.now()
        set_label(shipment.LabelSpecification)
        package = service.create_package()
        set_package(package)
        set_shipment(shipment, package)
        result = service.process(shipment)
        print result
        details = result.CompletedShipmentDetail.CompletedPackageDetails[0]
        image = details.Label.Parts[0].Image
        binary = a2b_base64(image)

        with NamedTemporaryFile() as png_file:
            png_file.write(binary)

            if Image:
                png_file.seek(0)
                Image.open(png_file.name).show()

        tracking_id = details.TrackingIds[0]
        result = service.delete(tracking_id)
        print result
    def update_image_sizes( sender, **kwargs):
        # if main image is too big, resize it; make a thumbnail image
        img_rec = kwargs.get('instance', None)
        if img_rec is None:
            return

        # (1) resize main image
        if img_rec.main_image.width > MAX_MAIN_IMAGE_WIDTH or img_rec.main_image.height > MAX_MAIN_IMAGE_WIDTH:
            im = Image.open(img_rec.main_image.file.name)   # open image
            im.thumbnail((MAX_MAIN_IMAGE_WIDTH, MAX_MAIN_IMAGE_WIDTH), Image.ANTIALIAS) # resize
            im.save(img_rec.main_image.file.name, quality=90)   #save
        
        # (2) make a thumbnail
        thumb = Image.open(img_rec.main_image.file.name)    # open the main image
        thumb.thumbnail((MAX_THUMB_IMAGE_WIDTH, MAX_THUMB_IMAGE_WIDTH), Image.ANTIALIAS)
        thumb_fullpath = os.path.join(settings.MEDIA_ROOT\
                        , img_rec.get_image_upload_directory_thumb(os.path.basename(img_rec.main_image.path)) )

        # if needed, make thumb directory
        if not os.path.isdir(os.path.dirname(thumb_fullpath)):
            os.makedirs(os.path.dirname(thumb_fullpath))
        # save file
        thumb.save(thumb_fullpath, quality=100)

        # disconnect save signal, save the ImageRecord, and reconnect signal
        post_save.disconnect(ImageRecord.update_image_sizes, sender=ImageRecord)        
        # update/save django model
        img_rec.thumb_image.name = img_rec.get_image_upload_directory_thumb(os.path.basename(thumb_fullpath))
        img_rec.save()
        post_save.connect(ImageRecord.update_image_sizes, sender=ImageRecord)
Example #17
0
def _is_image_file(path):
    """Whether the file is a readable image file via Pillow."""
    try:
        pImage.open(path)
        return True
    except:
        return False
Example #18
0
def image(path):
  if '..' in path:
    abort(500)
  fd = open(join(app.root_path, "images", path))
  data = fd.read()

  hsize = int(request.args.get("h", 0))
  vsize = int(request.args.get("v", 0))
  if hsize > 1000 or vsize > 1000:
    abort(500)

  if hsize:
    image = Image.open(StringIO(data))
    x, y = image.size

    x1 = hsize
    y1 = int(1.0 * y * hsize / x)
    image.thumbnail((x1, y1), Image.ANTIALIAS)
    output = StringIO()
    image.save(output, "PNG")
    data = output.getvalue()
  if vsize:
    image = Image.open(StringIO(data))
    x, y = image.size

    x1 = int(1.0 * x * vsize / y)
    y1 = vsize
    image.thumbnail((x1, y1), Image.ANTIALIAS)
    output = StringIO()
    image.save(output, "PNG")
    data = output.getvalue()

  response = make_response(data)
  response.headers['content-type'] = mimetypes.guess_type(path)
  return response
Example #19
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 #20
0
def leftpanel(frame):
	height = 580 #image height

	LeftPanel = wx.Panel(frame,wx.ID_ANY)
	LeftPanel.SetBackgroundColour('#FFFFFF')
	layoutLeft = wx.BoxSizer(wx.VERTICAL)

	# for ImagePanel
	ImagePanel = wx.Panel(LeftPanel,wx.ID_ANY)
	pil = Image.open('store/gui/top.jpg')
	ratio = float(height-10*2)/float(pil.size[1])
	new_size = (int(pil.size[0]*ratio),int(pil.size[1]*ratio))
	pil.thumbnail(new_size,Image.ANTIALIAS)
	image = wx.EmptyImage(pil.size[0],pil.size[1])
	image.SetData(pil.convert('RGB').tostring())
	wx.StaticBitmap(ImagePanel, wx.ID_ANY, image.ConvertToBitmap())
	layoutLeft.Add(ImagePanel,flag=wx.ALL,border=10)

	# for LogoPanel
	LogoPanel = wx.Panel(LeftPanel,wx.ID_ANY)
	pil = Image.open('store/gui/logo.png')
	ratio = float(image.GetWidth()-10*2)/float(pil.size[0])
	new_size = (int(pil.size[0]*ratio),int(pil.size[1]*ratio))
	pil.thumbnail(new_size,Image.ANTIALIAS)
	image = wx.EmptyImage(pil.size[0],pil.size[1])
	image.SetData(pil.convert('RGB').tostring())
	wx.StaticBitmap(LogoPanel, wx.ID_ANY, image.ConvertToBitmap())
	LogoPanel.SetSize(new_size)
	layoutLeft.Add(LogoPanel,flag=wx.ALL,border=10)

	LeftPanel.SetSizer(layoutLeft)
	return LeftPanel
Example #21
0
def preprocess(file_name, variations, storage):
    with storage.open(file_name) as f:
        with Image.open(f) as image:
            file_format = 'PNG'

            # resize to a maximum of 1000x1000 keeping aspect ratio
            image.thumbnail((1000, 1000), resample=Image.ANTIALIAS)

            # Create a disk as mask
            mindimension = min(1000, image.size[1], image.size[0])
            bigsize = (mindimension * 3, mindimension * 3)
            mask = Image.new('L', bigsize, 0)
            draw = ImageDraw.Draw(mask)
            draw.ellipse((0, 0) + bigsize, fill=255)
            mask = mask.resize((mindimension, mindimension), Image.ANTIALIAS)

            # only keep the image that fit in the mask
            output = ImageOps.fit(image, mask.size, centering=(0.5, 0.5))
            output.putalpha(mask)

            with BytesIO() as file_buffer:
                output.save(file_buffer, file_format)
                f = ContentFile(file_buffer.getvalue())
                # delete the original big image
                storage.delete(file_name)
                # save the resized version with the same filename and format
                storage.save(file_name, f)

    # render stdimage variations
    render_variations(file_name, variations, replace=True, storage=storage)

    return False  # prevent default rendering
def resizeImage(subdir, infile, output_dir=""):
     outfile = os.path.splitext(infile)[0]+"_min"
     extension = os.path.splitext(infile)[1]
     w=400
     logo = Image.open('../Logo/JXX.png')
     logo.thumbnail((w/10, w/10))
     if (cmp(extension, ".JPG")):
        return

     if infile != outfile:
        try :
            im = Image.open(subdir+"/"+infile)
            width, height = im.size
            if(width>height):
                nh = width*height/w
            else:
                nh = w
                w = height*width/nh
            im.thumbnail((w, nh), Image.ANTIALIAS)

            image_copy = im.copy()
            position = ((image_copy.width - logo.width - 10), (image_copy.height - logo.height - 10))
            image_copy.paste(logo, position, logo)
            image_copy.save(subdir+"/"+output_dir+outfile+extension,"JPEG")
        except IOError:
            print "cannot reduce image for ", infile
Example #23
0
    def basehash(self, path=True):
        """basehash compare If histogram smooth
        :return: float
        """
        import math
        import operator
        from PIL import Image

        if path:
            image1 = Image.open(self.image_a_path)
            image2 = Image.open(self.image_b_path)
        else:
            image1 = Image.open(self.image_a_binary)
            image2 = Image.open(self.image_b_binary)

        if not image1.size is image2.size:
            image2 = image2.resize(image1.size)
        pass
        h1 = image1.convert('RGB').histogram()
        h2 = image2.convert('RGB').histogram()

        rms = math.sqrt(
            reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2)))
            /
            len(h1)
        )
        self.value_of_phash = rms
        return rms
Example #24
0
 def getValicode(self):
     element = self.driver.find_element_by_id("change_cas")
     element.click();
     time.sleep(0.5)
     self.driver.get_screenshot_as_file("screenshot.png")
     img = IMG.open('screenshot.png')
     width = img.size[0]
     height =  img.size[1]
     region = (int(width*0.50699677), int(height*0.52849162), int(width*0.593110872), int(height*0.57318436))
     cropImg = img.crop(region)
     cropImg.save('1.png')
     image = IMG.open('1.png')
     enhancer = ImageEnhance.Contrast(image)
     image_enhancer = enhancer.enhance(2)
     valicode = image_to_string(image_enhancer)
     if len(valicode)==0:
         return self.getValicode()
     else:
         pattern = re.compile(r'[0-9,a-z,A-Z]{4}')
         match = pattern.match(valicode)
         if match:
             print valicode
             return valicode
         else:
             return self.getValicode()
Example #25
0
def split_and_compress_layers(layers, tilewidth, tileheight):
    unique_tiles = []
    compressed_layers = []
    for l, (layer_file, depth) in enumerate(layers):
        print "Splitting and compressing %s" % layer_file
        tiles = []

        layer = Image.open(layer_file)
        layerwidth, layerheight = layer.size

        for tile_buffer in crop(layer, tilewidth, tileheight):
            tile = Image.new('RGB', [tilewidth, tileheight], 255)
            tile.paste(tile_buffer)
            tile_str = tile.tostring()

            if tile_str not in unique_tiles:
                unique_tiles.append(tile_str)
            tiles.append(unique_tiles.index(tile_str))

            del tile
        del layer
        compressed_layers.append((layerwidth, layerheight, depth, tiles))

        print "Layer %d has %d unique tiles out of %d" % (l, len(set(compressed_layers[l][3])), len(compressed_layers[l][3]))
    return unique_tiles, compressed_layers
Example #26
0
def imageStructToPIL(imageRow):
    """
    Convert the immage from image schema struct to PIL image

    :param imageRow: Row, must have ImageSchema
    :return PIL image
    """
    imgType = imageTypeByOrdinal(imageRow.mode)
    if imgType.dtype != 'uint8':
        raise ValueError("Can not convert image of type " +
                         imgType.dtype + " to PIL, can only deal with 8U format")
    ary = imageStructToArray(imageRow)
    # PIL expects RGB order, image schema is BGR
    # => we need to flip the order unless there is only one channel
    if imgType.nChannels != 1:
        ary = _reverseChannels(ary)
    if imgType.nChannels == 1:
        return Image.fromarray(obj=ary, mode='L')
    elif imgType.nChannels == 3:
        return Image.fromarray(obj=ary, mode='RGB')
    elif imgType.nChannels == 4:
        return Image.fromarray(obj=ary, mode='RGBA')
    else:
        raise ValueError("don't know how to convert " +
                         imgType.name + " to PIL")
def query(query_term, folder_name, path):

    BASE_URL = 'https://ajax.googleapis.com/ajax/services/search/images?' + 'v=1.0&q=' + query_term + '&start=%d'

    BASE_PATH = os.path.join(path, folder_name.replace(' ', '_'))

    if not os.path.exists(BASE_PATH):
        os.makedirs(BASE_PATH)
        print "made: " + BASE_PATH

    start = 0  # start query string parameter for pagination
    while start < 40:   # query 20 pages
        r = requests.get(BASE_URL % start)
        for image_info in json.loads(r.text)['responseData']['results']:
            url = image_info['unescapedUrl']
            try:
                image_r = requests.get(url)
            except ConnectionError, e:
                print 'could not download %s' % url
                continue

            #remove file-system path characters from name
            title = query_term.replace(' ', '_') + '_' + image_info['imageId']
            file = open(os.path.join(BASE_PATH, '%s.jpg') % title, 'w')
            try:
                Image.open(StringIO(image_r.content)).save(file, 'JPEG')
            except IOError, e:
                # throw away gifs and stuff
                print 'couldnt save %s' % url
                continue
            finally:
def watermark(im, mark, position, opacity=1):
    """Adds a watermark to an image."""
    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)
    def test_jpeg(self):
        path = os.path.join(TEST_DATA_PATH, "Sam_Hat1.jpg")
        image = Image.objects.create_from_path(path)

        # Re-load the image, now that the task is done
        image = Image.objects.get(id=image.id)

        self.assertTrue(image.source.path.endswith("Sam_Hat1.jpg"))
        self.assertEqual(image.width, 3264)
        self.assertEqual(image.height, 2448)
        self.assertEqual(image.jpeg_quality, None)
        self.assertTrue(os.path.exists(image.optimized.path))
        self.assertTrue(os.path.exists(image.source.path))

        source = PILImage.open(image.source.path)
        optimized = PILImage.open(image.optimized.path)

        self.assertEqual(
            source.quantization,
            optimized.quantization
        )

        self.assertEqual(
            JpegImagePlugin.get_sampling(source),
            JpegImagePlugin.get_sampling(optimized),
        )
Example #30
0
def prepare(filename, bgcolor = background_default, chatty = chatty_default):
    """
    Prepare a large image for tiling.
    
    Load an image from a file. Resize the image so that it is square,
    with dimensions that are an even power of two in length (e.g. 512,
    1024, 2048, ...). Then, return it.
    """

    src = Image.open(filename)

    if chatty:
        print "original size: %s" % str(src.size)
    
    full_size = (1, 1)

    while full_size[0] < src.size[0] or full_size[1] < src.size[1]:
        full_size = (full_size[0] * 2, full_size[1] * 2)
    
    img = Image.new('RGBA', full_size)
    img.paste("#" + bgcolor)
    
    src.thumbnail(full_size, scaling_filter)
    img.paste(src, (int((full_size[0] - src.size[0]) / 2),
                    int((full_size[1] - src.size[1]) / 2)))
    
    if chatty:
        print "full size: %s" % str(full_size)
        
    return img