Exemplo n.º 1
0
def put_highlight(image, highlight, resample_highlight, opacity, cache=None):
    if cache is None:
        cache = {}
    resample_highlight = getattr(Image, resample_highlight)
    id = 'highlight_%s_w%d_h%d_o%d'\
        % (highlight, image.size[0], image.size[1], opacity)
    try:
        highlight = cache[id]
    except KeyError:
        highlight = open_image(highlight)\
            .convert('RGBA').resize(image.size, resample_highlight)
        if opacity < 100:
            #apply opacity
            highlight_alpha = imtools.get_alpha(highlight)
            opacity = (255 * opacity) / 100
            highlight.putalpha(ImageMath.eval("convert((a * o) / 255, 'L')",
                a=highlight_alpha, o=opacity))
        #store in cache
        cache[id] = highlight
    if not has_transparency(image):
        image = image.convert('RGBA')
    else:
        if has_transparency(image):
            image = image.convert('RGBA')
        alpha = imtools.get_alpha(image)
        highlight = highlight.copy()
        highlight_alpha = imtools.get_alpha(highlight)
        highlight.putalpha(ImageMath.eval("convert(min(a, b), 'L')",
            a=alpha, b=highlight_alpha))

    overlay = highlight.convert('RGB')
    paste(image, overlay, mask=highlight)
    return image
Exemplo n.º 2
0
def main(args):
	coverImg = open_image(args.cover_image, "rb")	# read only in binary
	secretImg = open_image(args.secret_image, "rb") 
	
	# check the size, for now just make secret image size equals cover image
	secretImg = secretImg.resize(coverImg.size)


	red, green, blue = coverImg.split()
	sred, sgreen, sblue = secretImg.split()




	red2 = ImageMath.eval("convert(a&0xFE|b&0x1,'L')", a=red, b=sred)
	green2 = ImageMath.eval("convert(a&0xFE|b&0x1,'L')", a=green, b=sgreen)
	blue2 = ImageMath.eval("convert(a&0xFE|b&0x1,'L')", a=blue, b=sblue)


	out = Image.merge("RGB", (red2, green2, blue2))
	out.save("merged.bmp")





	exit(0)
Exemplo n.º 3
0
def image_diff(im1, im2):
    """Return the diff of two images"""
    from PIL from PIL import Image, ImageMath
    r1, g1, b1, a1 = im1.convert('RGBA').split()
    r2, g2, b2, a2 = im2.convert('RGBA').split()
    diff_image = ImageMath.eval(
        """convert(
            max(
                max(
                    max(abs(r1 - r2), abs(g1 - g2)),
                    abs(b1 - b2)
                ),
                abs(a1 - a2)
            ), 'L')""",
        r1=r1,
        r2=r2,
        g1=g1,
        g2=g2,
        b1=b1,
        b2=b2,
        a1=a1,
        a2=a2)
    if ImageMath.eval('not(image)', image=diff_image):
        return
    return diff_image
Exemplo n.º 4
0
 def test_convert(self):
     self.assertEqual(pixel(
         ImageMath.eval("convert(A+B, 'L')", images)), "L 3")
     self.assertEqual(pixel(
         ImageMath.eval("convert(A+B, '1')", images)), "1 0")
     self.assertEqual(pixel(
         ImageMath.eval("convert(A+B, 'RGB')", images)), "RGB (3, 3, 3)")
Exemplo n.º 5
0
 def paint(self, image):   
     
     if self.bpp != 0:
         width = self.lcd_size[0]
         height = self.lcd_size[1]
              
         if self.bpp == 1:
             # Paint to 565 image provided into an ARGB image surface for PIL's benefit. PIL doesn't support 565?
             argb_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
             argb_context = cairo.Context(argb_surface)
             argb_context.set_source_surface(image)
             argb_context.paint()
             
             # Now convert the ARGB to a PIL image so it can be converted to a 1 bit monochrome image, with all
             # colours dithered. It would be nice if Cairo could do this :( Any suggestions? 
             pil_img = Image.frombuffer("RGBA", self.lcd_size, argb_surface.get_data(), "raw", "RGBA", 0, 1)
             pil_img = ImageMath.eval("convert(pil_img,'1')",pil_img=pil_img)
             pil_img = ImageMath.eval("convert(pil_img,'P')",pil_img=pil_img)
             pil_img = pil_img.point(lambda i: i >= 250,'1')
             
             invert_control = self.get_control("invert_lcd")
             if invert_control and invert_control.value == 1:            
                 pil_img = pil_img.point(lambda i: 1^i)
                 
             # Create drawable message
             pil_img = pil_img.convert("RGB")
             self.image = pil_img           
         else:
             # Take a copy of the image to prevent flickering
             argb_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
             argb_context = cairo.Context(argb_surface)
             argb_context.set_source_surface(image)
             argb_context.paint()
             self.image = argb_surface
         gobject.timeout_add(0, self.redraw)
Exemplo n.º 6
0
def _lsb_pixel_decode(image):
    r, g, b, *_ = image.split()
    r = ImageMath.eval("convert(c&0x1, 'L')", c=r)
    g = ImageMath.eval("convert(c&0x1, 'L')", c=g)
    b = ImageMath.eval("convert(c&0x1, 'L')", c=b)
    data = roundrobin(iter_pixels(r), iter_pixels(g), iter_pixels(b))
    return bytes([reduce(lambda byte, bit: byte << 1 | bit, eight_bits)
                  for eight_bits in grouper(data, 8, fillvalue=0)])
Exemplo n.º 7
0
def color_to_alpha(image, color=None):
    image = image.convert('RGBA')
    width, height = image.size

    color = map(float, color)
    img_bands = [band.convert("F") for band in image.split()]

    # Find the maximum difference rate between source and color. I had to use two
    # difference functions because ImageMath.eval only evaluates the expression
    # once.
    alpha = ImageMath.eval(
        """float(
            max(
                max(
                    max(
                        difference1(red_band, cred_band),
                        difference1(green_band, cgreen_band)
                    ),
                    difference1(blue_band, cblue_band)
                ),
                max(
                    max(
                        difference2(red_band, cred_band),
                        difference2(green_band, cgreen_band)
                    ),
                    difference2(blue_band, cblue_band)
                )
            )
        )""",
        difference1=difference1,
        difference2=difference2,
        red_band = img_bands[0],
        green_band = img_bands[1],
        blue_band = img_bands[2],
        cred_band = color[0],
        cgreen_band = color[1],
        cblue_band = color[2]
    )

    # Calculate the new image colors after the removal of the selected color
    new_bands = [
        ImageMath.eval(
            "convert((image - color) / alpha + color, 'L')",
            image = img_bands[i],
            color = color[i],
            alpha = alpha
        )
        for i in xrange(3)
    ]

    # Add the new alpha band
    new_bands.append(ImageMath.eval(
        "convert(alpha_band * alpha, 'L')",
        alpha = alpha,
        alpha_band = img_bands[3]
    ))

    return Image.merge('RGBA', new_bands)
Exemplo n.º 8
0
def getColorfulness(im): #OK
    """return (cf, sigma_rgyb, mu_rgyb)"""
    r, g, b = im.split()
    im_rg = ImageMath.eval("a - b", a=r, b=g)
    im_yb = ImageMath.eval("(a + b)/2 - c", a=r, b=g, c=b)
    rg = list(im_rg.getdata())
    yb = list(im_yb.getdata())
    sigma = math.sqrt(numpy.std(rg) ** 2 + numpy.std(yb) ** 2)
    mu = math.sqrt(numpy.average(rg) ** 2 + numpy.average(yb) ** 2)
    return sigma + 0.3 * mu
Exemplo n.º 9
0
def normalizeImage(im):
	# split RGB images into 3 channels
	rr, gg, bb = im.split()

	rTmp = ImageMath.eval("int(a*((float(255/max(a,b)))))", a=rr, b=rr).convert('L')
	gTmp = ImageMath.eval("int(a*((float(255/max(a,b)))))", a=gg, b=gg).convert('L')
	bTmp = ImageMath.eval("int(a*((float(255/max(a,b)))))", a=bb, b=bb).convert('L')
		
	# merge channels into RGB image
	imgOut = Image.merge("RGB", (rTmp, gTmp, bTmp))
	return imgOut
Exemplo n.º 10
0
def applyOutline(a, o):
    w, h = a.size
    c = a.crop((o, o, w - o, h - o))
    t = Image.new("L", a.size)
    for n in ((o, 0), (0, o), (o + o, o), (o, o + o)):
        t.paste(c, n)
        a = ImageMath.eval("convert(max(a,b),'L')", a=a, b=t)
    for n in ((0, 0), (o + o, 0), (0, o + o), (o + o, o + o)):
        t.paste(c, n)
        a = ImageMath.eval("convert(max(a,b/1.414),'L')", a=a, b=t)
    return a
Exemplo n.º 11
0
def substractImage(imgA,imgB):
	rA, gA, bA = imgA.split()
	rB, gB, bB = imgB.split()

	rTmp = ImageMath.eval("a-b", a=rA, b=rB).convert('L')
	gTmp = ImageMath.eval("a-b", a=gA, b=gB).convert('L')
	bTmp = ImageMath.eval("a-b", a=bA, b=bB).convert('L')
	
	# merge channels into RGB image
	imgOut = Image.merge("RGB", (rTmp, gTmp, bTmp))
	return imgOut
Exemplo n.º 12
0
def divideImage(imgA,imgB):
	# split RGB images into 3 channels
	rA, gA, bA = imgA.split()
	rB, gB, bB = imgB.split()

	# divide each channel (image1/image2)
	rTmp = ImageMath.eval("int(a/((float(b))/256))", a=rA, b=rB).convert('L')
	gTmp = ImageMath.eval("int(a/((float(b))/256))", a=gA, b=gB).convert('L')
	bTmp = ImageMath.eval("int(a/((float(b))/256))", a=bA, b=bB).convert('L')

	# merge channels into RGB image
	imgOut = Image.merge("RGB", (rTmp, gTmp, bTmp))
	return imgOut
Exemplo n.º 13
0
def decode_data(rgb, bits):
    decoded_rgb = []

    for k in range(3):
        decoded_rgb.append(ImageMath.eval("convert((rgb & 2**bits - 1) << 8 - bits, 'L')", rgb = rgb[k], bits = bits))

    return tuple(decoded_rgb)
Exemplo n.º 14
0
    def assert_image_similar(self, a, b, epsilon, msg=None):
        epsilon = float(epsilon)
        self.assertEqual(
            a.mode, b.mode,
            msg or "got mode %r, expected %r" % (a.mode, b.mode))
        self.assertEqual(
            a.size, b.size,
            msg or "got size %r, expected %r" % (a.size, b.size))

        a, b = convert_to_comparable(a, b)

        diff = 0
        for ach, bch in zip(a.split(), b.split()):
            chdiff = ImageMath.eval("abs(a - b)", a=ach, b=bch).convert('L')
            diff += sum(i * num for i, num in enumerate(chdiff.histogram()))

        ave_diff = float(diff)/(a.size[0]*a.size[1])
        try:
            self.assertGreaterEqual(
                epsilon, ave_diff,
                (msg or '') +
                " average pixel value difference %.4f > epsilon %.4f" % (
                    ave_diff, epsilon))
        except Exception as e:
            if HAS_UPLOADER:
                try:
                    url = test_image_results.upload(a, b)
                    logger.error("Url for test images: %s" % url)
                except:
                    pass
            raise e
Exemplo n.º 15
0
def encode_data(cover_rgb, secret_rgb, bits):
    encoded_rgb = []

    for k in range(3):
        encoded_rgb.append(ImageMath.eval("convert((cover_rgb & (256 - 2**bits)) + ((secret_rgb & (256 - 2**(8 - bits)) - 1) >> 8 - bits), 'L')", cover_rgb = cover_rgb[k], secret_rgb = secret_rgb[k], bits = bits))

    return tuple(encoded_rgb)
Exemplo n.º 16
0
def segment(image_filepath, **kwargs):
    input_img = Image.open(image_filepath)

    # make a '1' bit image with the same size as the input_img
    mask_img = Image.new('1', input_img.size)

    # instantiate an ImageDraw object using the mask_img object
    mask_drawer = ImageDraw.Draw(mask_img)

    try:
        json_poly_data = json.loads(kwargs['JSON'])
    except ValueError:
        # There's a problem in the JSON - it may be malformed, or empty
        json_poly_data = []

    for polygon in json_poly_data:
        flattened_poly = [j for i in polygon for j in i]
        mask_drawer.polygon(flattened_poly, outline=1, fill=1)

    output_img = ImageMath.eval('b - a', a=input_img, b=mask_img)
    output_img = ImageOps.invert(output_img.convert('RGB'))

    encoded = json.dumps(json_poly_data)

    return {
        'tiff': output_img,
        'json': encoded
    }
Exemplo n.º 17
0
def warmup(image, midtone, brighten, amount=100):
    """Apply a toning filter. Move the midtones to the desired
    color while preserving blacks and whites with optional mixing
    with original image - amount: 0-100%"""

    mode = image.mode
    info = image.info

    if image.mode != "L":
        im = imtools.convert(image, "L")
    else:
        im = image

    if image.mode != "RGBA" and imtools.has_transparency(image):
        image = imtools.convert(image, "RGBA")

    luma = imtools.convert(imtools.split(im)[0], "F")
    o = []
    m = ImageColor.getrgb(midtone)
    b = brighten / 600.0
    # Calculate channels separately
    for l in range(3):
        o.append(ImageMath.eval("m*(255-i)*i+i", i=luma, m=4 * ((m[l] / 255.0) - 0.5 + b) / 255.0).convert("L"))

    colorized = Image.merge("RGB", tuple(o))

    if imtools.has_alpha(image):
        imtools.put_alpha(colorized, imtools.get_alpha(image))

    if amount < 100:
        colorized = imtools.blend(image, colorized, amount / 100.0)

    return colorized
Exemplo n.º 18
0
def generate_animated_images_old(front_image, back_image, scale_factor):
    animated_images = []
    for x in xrange (0, front_image.size[0], scale_factor):
        temp_image = Image.new('1', front_image.size, "white")
        temp_image.paste(front_image.crop((front_image.size[0] - x, 0, front_image.size[0], front_image.size[1])), (0,0))
        animated_image = ImageMath.eval("convert((a & b), 'L')", a=temp_image, b=back_image)
        #animated_image.save(file_name + "_" + str(x) + file_ext)
        animated_images.append(animated_image)

    for x in xrange (0, front_image.size[0] + 1, scale_factor):
        temp_image = Image.new('1', front_image.size, "white")
        temp_image.paste(front_image.crop((0, 0, front_image.size[0] - x, front_image.size[1])), (x, 0))
        animated_image = ImageMath.eval("convert((a & b), 'L')", a=temp_image, b=back_image)
        #animated_image.save(file_name + "_" + str(x+front_image.size[0]) + file_ext)
        animated_images.append(animated_image)
    return animated_images
Exemplo n.º 19
0
  def process(self, image):
    """
    @param image -- The image to process.

    Returns a single image, or a list containing one or more images.
    """
    BaseFilter.process(self, image)

    base, alpha = image.split()

    if self.scaleTowardCenter:
      scale = float(self.factor)
      assert base.mode == "L"
      maxValue = 255 # TODO: Determine how to get maximum value __allowed__.
      offset = ((1.0 - self.factor) / 2.0) * maxValue
      newImage = ImageMath.eval(
          "convert(convert(gray, 'F') * scale + offset, mode)",
          gray=base,
          scale=scale,
          offset=offset,
          mode=base.mode,
        )
    else:
      contrastEnhancer = ImageEnhance.Contrast(image.split()[0])
      newImage = contrastEnhancer.enhance(self.factor)

    newImage.putalpha(alpha)

    return newImage
Exemplo n.º 20
0
def makeColorTransparent(image, color, thresh2=0):
    from PIL import ImageMath
    image = image.convert("RGBA")
    red, green, blue, alpha = image.split()
    image.putalpha(ImageMath.eval("""convert(((((t - d(c, (r, g, b))) >> 31) + 1) ^ 1) * a, 'L')""",
        t=thresh2, d=distance2, c=color, r=red, g=green, b=blue, a=alpha))
    return image
def strip_processing(path, blur_radius=7, iter_steps=1, binarize_threshold=10):

    """Strip precessing function.

    Inputs:
    string: path of the image
    blur_radius: radius of gaussian blur
    iter_steps: execution times of denoise
    binarize_threshold: used as function lut's input

    Outputs:
    Image: the processed image."""

    gray=ImageOps.invert(ImageOps.grayscale(Image.open("stripes.jpg")))
    gray_blur=gray.filter(ImageFilter.GaussianBlur(blur_radius))
    high_freq=ImageMath.eval("25*(a-b)",a=gray,b=gray_blur).convert("L")

    binarized=ImageOps.invert(high_freq.point(lut(binarize_threshold))).convert("1")
    binarized_data=binarized.load()
    #binarized.show()

    height=binarized.height
    width=binarized.width

    pix=np.array([[np.uint8(binarized_data[j,i]) for j in range(width)] for i in range(height)])

    for i in range(iter_steps):
        pix=denoise(pix)

    answer=Image.fromarray(pix)
    #answer.show()
    #answer.save("test.bmp")
    return answer
Exemplo n.º 22
0
    def run(self):
        while True:
            try:
                camera = WebCamera.objects.get(pk = self._camera.id)
                if camera.motion_control:
                    now = datetime.now()
                    request = get_pool().request("GET", "%s?action=snapshot" % camera.internal_url)
                    try:
                        source = Image.open(BytesIO(request.data))
                        img = ImageOps.equalize(ImageOps.grayscale(source))
                        if self._previous is not None:
                            out = ImageMath.eval("convert(a - b, 'L')", a = img, b = self._previous)
                            out = out.filter(MedianFilter())
                            total = 0
                            for idx, val in enumerate(out.histogram()):
                                total += val * idx
                            if total > 3000000:
                                camera.last_motion = now
                                camera.save()

                                filename = os.path.join(camera.motion_folder, "{:%Y%m%d-%H%M%S}.jpg".format(now))
                                source.save(filename)
                                filesize = os.path.getsize(filename)
                                if filesize < 6700:
                                    os.remove(filename) 

                        self._previous = img
                    finally:
                        request.close()
                else:
                    self._previous = None
            except:
                print("Ignore Exception")
            sleep(1)
Exemplo n.º 23
0
 def optim_obj_xor(x):
     draw(x)
     image = get_image()
     xor = imath.eval("a^b", a=image, b=image_obj)
     res = sum(xor.getdata())
     print x, res
     return res
Exemplo n.º 24
0
def getContrast(im): #OK
    """return contrast"""
    im = im.convert('L')
    stat = ImageStat.Stat(im)
    mean = stat.mean[0]
    im_diff = ImageMath.eval("abs(a - b)", a=im, b=mean)
    diff = list(im_diff.getdata())
    return math.sqrt(1.0 / (len(diff) - 1) * sum(pix ** 2 for pix in diff))
Exemplo n.º 25
0
Arquivo: cal.py Projeto: chxzh/shadyn
def xor_closure(target, path):
    '''
    target shall be a single-band Image instance
    '''
    target = imath.eval("x>>7", x=target)
    def _get_xor(image):
        xor_img = imath.eval("(a>>7)^b", a=image, b=target)
        return sum(xor_img.getdata())
    return _get_xor
Exemplo n.º 26
0
 def paint(self, img):
     if not self.is_connected():
         return
     
     # Just return if the device has no LCD
     if self.device.bpp == 0:
         return None
          
     self.lock.acquire()        
     try :           
         size = self.get_size()
         
         # Paint to 565 image provided into an ARGB image surface for PIL's benefit. PIL doesn't support 565?
         argb_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0], size[1])
         argb_context = cairo.Context(argb_surface)
         argb_context.set_source_surface(img)
         argb_context.paint()
         
         # Now convert the ARGB to a PIL image so it can be converted to a 1 bit monochrome image, with all
         # colours dithered. It would be nice if Cairo could do this :( Any suggestions? 
         pil_img = Image.frombuffer("RGBA", size, argb_surface.get_data(), "raw", "RGBA", 0, 1)
         pil_img = ImageMath.eval("convert(pil_img,'1')",pil_img=pil_img)
         pil_img = ImageMath.eval("convert(pil_img,'P')",pil_img=pil_img)
         pil_img = pil_img.point(lambda i: i >= 250,'1')
         
         invert_control = self.get_control("invert_lcd")
         if invert_control.value == 0:            
             pil_img = pil_img.point(lambda i: 1^i)
 
         # Covert image buffer to string
         buf = ""
         for x in list(pil_img.getdata()): 
             buf += chr(x)
             
         if len(buf) != self.device.lcd_size[0] * self.device.lcd_size[1]:
             logger.warning("Invalid buffer size")
         else:
             try : 
                 self.send(buf)
             except IOError as e:
                 logger.error("Failed to send buffer.", exc_info = e)
                 self.disconnect()
     finally:
         self.lock.release()
Exemplo n.º 27
0
 def _on_snapshot_clicked(self):
     img = self.optimizer.rendis.acquire().acquire_snapshot()
     filename = QFileDialog.getSaveFileName(self,
                                 "save the binary shadow snapshot",
                                 "../img/",
                                 "image file (*.png)")
     if filename != '':
         img = ImageMath.eval("a/127 * 255", a=img)
         img.save(str(filename), format='png')
     pass
Exemplo n.º 28
0
def generate_animated_images(front_image, back_image, scale_factor):
    animated_images = []
    for x in xrange (-scale_factor, front_image.size[0], scale_factor):
        left_image = Image.new('1', (front_image.size[0] * 2, front_image.size[1]), "white")
        left_image.paste(front_image, (x, 0))
        right_image = Image.new('1', (front_image.size[0] * 2, front_image.size[1]), "white")
        right_image.paste(back_image, (front_image.size[0] - x, 0))
        animated_image = ImageMath.eval("convert((a & b), 'L')", a=left_image, b=right_image)
        #animated_image.save(str(x) + ".png")
        animated_images.append(animated_image)
    return animated_images
Exemplo n.º 29
0
def sketch(image, details_degree=1):
    im1 = image.convert('L')
    im2 = im1.copy()

    im2 = ImageOps.invert(im2)
    for i in xrange(details_degree):
        im2 = im2.filter(ImageFilter.BLUR)
    im1 = ImageMath.eval('convert(min(a * 255/ (256 - b), 255), "L")',
            a=im1,
            b=im2)
    return im1
Exemplo n.º 30
0
def gen_captcha(text, fontname, fontsize, file_name):
	"""Generate a captcha image"""
	# white text on a black background
	bgcolor = 0x0
	fgcolor = 0xffffff
	# create a font object
	font = ImageFont.truetype(fontname,fontsize)
	# determine dimensions of the text
	dim = font.getsize(text)
	# create a new image significantly larger that the text
	edge = max(dim[0], dim[1]) + 2*min(dim[0], dim[1])
	im = Image.new('RGB', (edge, edge), bgcolor)
	d = ImageDraw.Draw(im)
	x, y = im.size
	# add the text to the image
	d.text((x/2-dim[0]/2, y/2-dim[1]/2), text, font=font, fill=fgcolor)
	k = 2
	wob = 0.09*dim[1]
	rot = 45
	# Apply lots of small stirring operations, rather than a few large ones
	# in order to get some uniformity of treatment, whilst
	# maintaining randomness
	for i in range(k):
		im = wobbly_copy(im, wob, bgcolor, i*2+3, rot+0)
		im = wobbly_copy(im, wob, bgcolor, i*2+1, rot+45)
		im = wobbly_copy(im, wob, bgcolor, i*2+2, rot+90)
		rot += 30

	# now get the bounding box of the nonzero parts of the image
	bbox = im.getbbox()
	bord = min(dim[0], dim[1])/4 # a bit of a border
	im = im.crop((bbox[0]-bord, bbox[1]-bord, bbox[2]+bord, bbox[3]+bord))

	# Create noise
	nblock = 4
	nsize = (im.size[0] / nblock, im.size[1] / nblock)
	noise = Image.new('L', nsize, bgcolor)
	data = noise.load()
	for x in range(nsize[0]):
		for y in range(nsize[1]):
			r = random.randint(0, 65)
			gradient = 70 * x / nsize[0]
			data[x, y] = r + gradient
	# Turn speckles into blobs
	noise = noise.resize(im.size, Image.BILINEAR)
	# Add to the image
	im = ImageMath.eval('convert(convert(a, "L") / 3 + b, "RGB")', a=im, b=noise)

	# and turn into black on white
	im = ImageOps.invert(im)

	# save the image, in format determined from filename
	im.save(file_name)
Exemplo n.º 31
0
def createImages(a, b, c, d, chenPhoto, cls):
    info = []
    dir_path = os.path.dirname(os.path.realpath(__file__)) + '/PNGFiles'
    numSimToConsider = 30
    simPhotosLookedAt = 0
    if (cls == 'tball'): cls = 'tennisball'
    if (cls == 'gball'): cls = 'GolfBall'
    if isinstance(a, tuple): a = a[0]
    if isinstance(b, tuple): b = b[0]
    if isinstance(c, tuple): c = c[0]
    if isinstance(d, tuple): d = d[0]
    if (c - a <= 40 or d - b <= 40): return -100
    for filename in os.listdir(dir_path):
        if (simPhotosLookedAt > numSimToConsider): break
        debris = filename.split('.')
        if (not debris[-1] == 'png'): continue
        if (not re.search(cls, filename, re.IGNORECASE)): continue
        im = Image.open(
            dir_path + '/' +
            filename)  # might be png, gif etc, for instance test1.png
        imageCrop = im.crop(
            (a, b, c, d)
        )  # old one im.crop((100,0,550,280))#im.crop((100,150,550,380)) # ' 2 3 4 7 8 9 10 - no 5 6
        maxsize = (40, 40)
        imageCrop = ImageOps.fit(imageCrop, maxsize, Image.ANTIALIAS)
        im2 = ImageMath.eval('im/256', {'im': imageCrop}).convert('L')
        xLen, yLen = im2.size
        if (not (xLen == 40 and yLen == 40)): return -100
        #im2.save(filename.replace('png','jpeg'), 'JPEG')
        shifts = [i for i in range(10)]
        for shift in shifts:
            lIm, rIm, uIm, dIm = bootstrapSample(im2, shift, 240, -65, 12)
            for imToModify in [lIm, rIm, uIm, dIm]:
                imageNew = ImageOps.fit(imToModify, maxsize, Image.ANTIALIAS)
                info.append(mutual_information(imageNew, chenPhoto))
        simPhotosLookedAt += 1
    return max(info)
Exemplo n.º 32
0
def up_icon_image(sublist):
    # 检查是否有图标,没有图标下载保存到本地
    id = sublist["id"]
    icon_url = sublist["icon"]

    icon_path = os.path.join(FILE_PATH, "icon", f"{id}.png")

    if not os.path.exists(icon_path):
        schedule = request.Request(icon_url)
        schedule.add_header('User-Agent', header)
        with request.urlopen(schedule) as f:
            icon = Image.open(f)
            icon = icon.resize((150, 150))

            box_alpha = Image.open(
                os.path.join(FILE_PATH, "icon",
                             "box_alpha.png")).getchannel("A")
            box = Image.open(os.path.join(FILE_PATH, "icon", "box.png"))

            try:
                icon_alpha = icon.getchannel("A")
                icon_alpha = ImageMath.eval("convert(a*b/256, 'L')",
                                            a=icon_alpha,
                                            b=box_alpha)
            except ValueError:
                # 米游社的图有时候会没有alpha导致报错,这时候直接使用box_alpha当做alpha就行
                icon_alpha = box_alpha

            icon2 = Image.new("RGBA", (150, 150), "#00000000")
            icon2.paste(icon, (0, -10))

            bg = Image.new("RGBA", (150, 150), "#00000000")
            bg.paste(icon2, mask=icon_alpha)
            bg.paste(box, mask=box)

            with open(icon_path, "wb") as icon_file:
                bg.save(icon_file)
Exemplo n.º 33
0
def set_sat(c, s):
    """
    :type c: tuple(ImageMath._Operand)
    :type s: ImageMath._Operand
    :rtype: tuple(ImageMath._Operand)
    """
    x = ImageMath.imagemath_max(ImageMath.imagemath_max(c[0], c[1]), c[2])
    n = ImageMath.imagemath_min(ImageMath.imagemath_min(c[0], c[1]), c[2])
    cs = x - n
    not_even_area = ImageMath.imagemath_int(x != n)

    result = []
    for cc in c:
        max_area = ImageMath.imagemath_int(x == cc)
        min_area = ImageMath.imagemath_int(n == cc)
        mid_area = (max_area ^ 1) & (min_area ^ 1)

        mid = (((cc - n) * s) / cs) * mid_area
        cc = ((s * max_area) + mid) * not_even_area
        result.append(cc)

    return tuple(result)
Exemplo n.º 34
0
    def createAnaglyph(self, images):
        '''Create an anaglyph image from two images.
		
		Args:
			images: Two PIL images.
		
		Returns:
			The anaglyph PIL image.
		'''
        left, right = self.process_images(images)

        left_bands = left.split()
        right_bands = right.split()
        output_bands = list()
        for i in range(3):
            expression = (
                "(float(lr)*{lm[0]}+float(lg)*{lm[1]}+float(lb)*{lm[2]}+" +
                "float(rr)*{rm[0]}+float(rg)*{rm[1]}+float(rb)*{rm[2]})"
            ).format(lm=self.matrices[0][i], rm=self.matrices[1][i])

            expression = self.process_expression(i, expression)

            output_bands.append(
                ImageMath.eval("convert(" + expression + ", 'L')",
                               lr=left_bands[0],
                               lg=left_bands[1],
                               lb=left_bands[2],
                               rr=right_bands[0],
                               rg=right_bands[1],
                               rb=right_bands[2]))

        if len(left_bands) > 3 and len(right_bands) > 3:
            output_bands.append(
                ImageChops.lighter(left_bands[3], right_bands[3]))
            return Image.merge("RGBA", output_bands)
        return Image.merge("RGB", output_bands)
Exemplo n.º 35
0
def mse(imageA, imageB):
    """
    Name:
        mse
    Description:
        the 'Mean Squared Error' between the two images is the
        sum of the squared difference between the two images.
        NOTE: the two images must have the same dimension
    Params:
        imageA, imageB - the images to be compared
    Returns:
        err - the % of error in MSE
    """

    imgA = Image.open(imageA)
    imgB = Image.open(imageB)

    err = np.sum(ImageMath.eval(
        "(convert(imgA, 'F') - convert(imgB, 'F'))**2", imgA=imgA, imgB=imgB))
    err /= float(imgA.size[0] * imgA.size[1])

    # return the MSE, the lower the error, the more "similar"
    # the two images are
    return err
Exemplo n.º 36
0
def color_aug(image):
    # 色相いじる
    h, s, v = image.convert("HSV").split()
    _h = ImageMath.eval("(h + {}) % 255".format(np.random.randint(-25, 25)),
                        h=h).convert("L")
    img = Image.merge("HSV", (_h, s, v)).convert("RGB")

    # 彩度を変える
    saturation_converter = ImageEnhance.Color(img)
    img = saturation_converter.enhance(np.random.uniform(0.9, 1.1))

    # コントラストを変える
    contrast_converter = ImageEnhance.Contrast(img)
    img = contrast_converter.enhance(np.random.uniform(0.9, 1.1))

    # 明度を変える
    brightness_converter = ImageEnhance.Brightness(img)
    img = brightness_converter.enhance(np.random.uniform(0.9, 1.1))

    # シャープネスを変える
    sharpness_converter = ImageEnhance.Sharpness(img)
    img = sharpness_converter.enhance(np.random.uniform(0.9, 1.1))

    return img
Exemplo n.º 37
0
def change_background(img, mask, bg):
    # oh = img.height
    # ow = img.width
    ow, oh = img.size
    bg = bg.resize((ow, oh)).convert('RGB')

    imcs = list(img.split())
    bgcs = list(bg.split())
    maskcs = list(mask.split())
    fics = list(Image.new(img.mode, img.size).split())

    for c in range(len(imcs)):
        negmask = maskcs[c].point(lambda i: 1 - i / 255)
        posmask = maskcs[c].point(lambda i: i / 255)

        #a是真正图片的当前通道,b是背景的当前通道,c是正掩码,d是负掩码
        fics[c] = ImageMath.eval("a * c + b * d",
                                 a=imcs[c],
                                 b=bgcs[c],
                                 c=posmask,
                                 d=negmask).convert('L')
    out = Image.merge(img.mode, tuple(fics))

    return out
Exemplo n.º 38
0
def getdims(pdf):
    tmpdir=mkdtemp()
    gs('-q',
       '-dQUIET',
       '-dSAFER',
       '-dBATCH',
       '-dNOPAUSE',
       '-dNOPROMPT',
       '-sDEVICE=pngmono',
       '-r72x72',
       '-sOutputFile=%s/%%08d' % tmpdir,
       '-f%s' % pdf)
    mask=None
    for fname in os.listdir(tmpdir):
        page=Image.open(tmpdir+'/'+fname) #.convert("1",dither=Image.NONE)
        if not mask:
            mask=page
        mask=ImageMath.eval("a & b", a=page, b=mask)
    rmtree(tmpdir)
    data = np.array(mask)
    data_slices = find_paws(255-data, smooth_radius = 5, threshold = 5)
    bboxes = remove_overlaps(slice_to_bbox(data_slices))
    m=max(bboxes,key=lambda x: (x.x2 - x.x1)*(x.y2 - x.y1))
    return (m.x1,m.y1,m.y2-m.y1,m.x2-m.x1)
Exemplo n.º 39
0
def assert_compare_images(a, b, max_average_diff, max_diff=255):
    assert a.mode == b.mode, "got mode %r, expected %r" % (a.mode, b.mode)
    assert a.size == b.size, "got size %r, expected %r" % (a.size, b.size)

    a, b = convert_to_comparable(a, b)

    bands = ImageMode.getmode(a.mode).bands
    for band, ach, bch in zip(bands, a.split(), b.split()):
        ch_diff = ImageMath.eval("convert(abs(a - b), 'L')", a=ach, b=bch)
        ch_hist = ch_diff.histogram()

        average_diff = sum(i * num for i, num in enumerate(ch_hist)) / (
            a.size[0] * a.size[1]
        )
        msg = "average pixel value difference {:.4f} > expected {:.4f} "
        "for '{}' band".format(average_diff, max_average_diff, band)
        assert max_average_diff >= average_diff, msg

        last_diff = [i for i, num in enumerate(ch_hist) if num > 0][-1]
        assert (
            max_diff >= last_diff
        ), "max pixel value difference {} > expected {} for '{}' band".format(
            last_diff, max_diff, band
        )
Exemplo n.º 40
0
def MakeColorTransparent(image, color, thresh2=0):
    """
    将指定颜色转为透明

    https://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent/765829"""
    from PIL import ImageMath

    def Distance2(a, b):
        return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (
            a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2])

    image = image.convert("RGBA")
    red, green, blue, alpha = image.split()
    image.putalpha(
        ImageMath.eval(
            """convert(((((t - d(c, (r, g, b))) >> 31) + 1) ^ 1) * a, 'L')""",
            t=thresh2,
            d=Distance2,
            c=color,
            r=red,
            g=green,
            b=blue,
            a=alpha))
    return image
Exemplo n.º 41
0
def diffImages(imgA, imgB):
    """Subtract two images (r-r, g-g, b-b).  Also add 128 to reduce negative values
       If a pixel is exactly same in both images, then the result will be 128,128,128 gray
       Out of range values (<0 and > 255) are moved to 0 and 255 by the convert('L') function

    Args:
        imgA: Pillow image object to subtract from
        imgB: Pillow image object to subtract

    Returns:
        Pillow image object containing the results of the subtraction with 128 mean
    """
    bandsImgA = imgA.split()
    bandsImgB = imgB.split()
    bandsImgOut = []

    for bandNum in range(len(bandsImgA)):
        # out = ImageMath.eval("convert((128+a/2)-b/2,'L')", a=bandsImgA[bandNum], b=bandsImgB[bandNum])
        out = ImageMath.eval("convert(128+a-b,'L')",
                             a=bandsImgA[bandNum],
                             b=bandsImgB[bandNum])
        bandsImgOut.append(out)

    return Image.merge('RGB', bandsImgOut)
Exemplo n.º 42
0
def clip_color(c):
    """
    :type c: tuple(ImageMath._Operand)
    :rtype: tuple(ImageMath._Operand)
    """
    l = lum(c)
    x = ImageMath.imagemath_max(ImageMath.imagemath_max(c[0], c[1]), c[2])
    n = ImageMath.imagemath_min(ImageMath.imagemath_min(c[0], c[1]), c[2])

    n_l_0 = ImageMath.imagemath_int(n < 0)
    x_b_1 = ImageMath.imagemath_int(x > 1.0)
    l_m_n = l - n
    x_m_l = x - l
    m_l = (1.0 - l)

    if bool(n_l_0):
        c = [(_c * (n_l_0 ^ 1)) + ((l + ((_c - l) * l / l_m_n)) * n_l_0)
             for _c in c]

    if bool(x_b_1):
        c = [(_c * (x_b_1 ^ 1)) + ((l + ((_c - l) * m_l / x_m_l)) * x_b_1)
             for _c in c]

    return c
Exemplo n.º 43
0
 def test_one_image_larger(self):
     self.assertEqual(pixel(ImageMath.eval("A+B", A=A2, B=B)), "I 3")
     self.assertEqual(pixel(ImageMath.eval("A+B", A=A, B=B2)), "I 3")
Exemplo n.º 44
0
 def test_compare(self):
     self.assertEqual(pixel(ImageMath.eval("min(A, B)", images)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("max(A, B)", images)), "I 2")
     self.assertEqual(pixel(ImageMath.eval("A == 1", images)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("A == 2", images)), "I 0")
Exemplo n.º 45
0
 def test_logical(self):
     self.assertEqual(pixel(ImageMath.eval("not A", images)), 0)
     self.assertEqual(pixel(ImageMath.eval("A and B", images)), "L 2")
     self.assertEqual(pixel(ImageMath.eval("A or B", images)), "L 1")
Exemplo n.º 46
0
    def paint(self, img):
        if not self.is_connected():
            return

        # Just return if the device has no LCD
        if self.device.bpp == 0:
            return None

        self.lock.acquire()
        try:
            size = self.get_size()

            # Paint to 565 image provided into an ARGB image surface for PIL's benefit. PIL doesn't support 565?
            argb_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0],
                                              size[1])
            argb_context = cairo.Context(argb_surface)
            argb_context.set_source_surface(img)
            argb_context.paint()

            # Now convert the ARGB to a PIL image so it can be converted to a 1 bit monochrome image, with all
            # colours dithered. It would be nice if Cairo could do this :( Any suggestions?
            pil_img = Image.frombuffer("RGBA", size, argb_surface.get_data(),
                                       "raw", "RGBA", 0, 1)
            pil_img = ImageMath.eval("convert(pil_img,'1')", pil_img=pil_img)
            pil_img = ImageMath.eval("convert(pil_img,'P')", pil_img=pil_img)
            pil_img = pil_img.point(lambda i: i >= 250, '1')

            invert_control = self.get_control("invert_lcd")
            if invert_control.value == 0:
                pil_img = pil_img.point(lambda i: 1 ^ i)

            # Convert image buffer to string
            buf = ""
            for x in list(pil_img.getdata()):
                buf += chr(x)

            if len(buf) != self.device.lcd_size[0] * self.device.lcd_size[1]:
                logger.warning("Invalid buffer size")
            else:
                # TODO Replace with C routine
                arrbuf = array.array('B', self.empty_buf)
                width, height = self.get_size()
                max_byte_offset = 0
                for x in range(0, width):
                    for y in range(0, height):
                        pixel_offset = y * width + x
                        byte_offset = pixel_offset / 8
                        max_byte_offset = max(max_byte_offset, byte_offset)
                        bit_offset = 7 - (pixel_offset % 8)
                        val = ord(buf[x + (y * 160)])
                        pv = arrbuf[byte_offset]
                        if val > 0:
                            arrbuf[byte_offset] = pv | 1 << bit_offset
                        else:
                            arrbuf[byte_offset] = pv & ~(1 << bit_offset)
                buf = arrbuf.tostring()
                try:
                    logger.debug("Writing buffer of %d bytes", len(buf))
                    pylibg15.write_pixmap(buf)
                except IOError as e:
                    logger.error("Failed to send buffer.", exc_info=e)
                    self.disconnect()
        finally:
            self.lock.release()
Exemplo n.º 47
0
    def test_ops(self):

        self.assertEqual(pixel(ImageMath.eval("-A", images)), "I -1")
        self.assertEqual(pixel(ImageMath.eval("+B", images)), "L 2")

        self.assertEqual(pixel(ImageMath.eval("A+B", images)), "I 3")
        self.assertEqual(pixel(ImageMath.eval("A-B", images)), "I -1")
        self.assertEqual(pixel(ImageMath.eval("A*B", images)), "I 2")
        self.assertEqual(pixel(ImageMath.eval("A/B", images)), "I 0")
        self.assertEqual(pixel(ImageMath.eval("B**2", images)), "I 4")
        self.assertEqual(pixel(
            ImageMath.eval("B**33", images)), "I 2147483647")

        self.assertEqual(pixel(ImageMath.eval("float(A)+B", images)), "F 3.0")
        self.assertEqual(pixel(ImageMath.eval("float(A)-B", images)), "F -1.0")
        self.assertEqual(pixel(ImageMath.eval("float(A)*B", images)), "F 2.0")
        self.assertEqual(pixel(ImageMath.eval("float(A)/B", images)), "F 0.5")
        self.assertEqual(pixel(ImageMath.eval("float(B)**2", images)), "F 4.0")
        self.assertEqual(pixel(
            ImageMath.eval("float(B)**33", images)), "F 8589934592.0")
Exemplo n.º 48
0
 def test_bitwise_rightshift(self):
     self.assertEqual(pixel(ImageMath.eval("Z>>0", Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("Z>>1", Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("A>>0", A=A)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("A>>1", A=A)), "I 0")
Exemplo n.º 49
0
 def _show_picture(self):
     if (1 == self._fb.bits_per_pixel):
         self._write_image(ImageMath.eval('convert(img, "1")', img=Image.open(self._filename)))
     else:
         self._write_image(img=Image.open(self._filename))
Exemplo n.º 50
0
 def test_bitwise_xor(self):
     self.assertEqual(pixel(ImageMath.eval("Z^Z", A=A, Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("Z^A", A=A, Z=Z)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("A^Z", A=A, Z=Z)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("A^A", A=A, Z=Z)), "I 0")
Exemplo n.º 51
0
 def test_bitwise_leftshift(self):
     self.assertEqual(pixel(ImageMath.eval("Z<<0", Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("Z<<1", Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("A<<0", A=A)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("A<<1", A=A)), "I 2")
Exemplo n.º 52
0
 def test_bitwise_or(self):
     self.assertEqual(pixel(ImageMath.eval("Z|Z", A=A, Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("Z|A", A=A, Z=Z)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("A|Z", A=A, Z=Z)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("A|A", A=A, Z=Z)), "I 1")
Exemplo n.º 53
0
 def test_bitwise_and(self):
     self.assertEqual(pixel(ImageMath.eval("Z&Z", A=A, Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("Z&A", A=A, Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("A&Z", A=A, Z=Z)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("A&A", A=A, Z=Z)), "I 1")
        for x in range(0, width, 32):
            draw.rectangle(
                (x + 0, y + 0, x + 29, y + 29), outline=255, fill=x // 4 + y // 4
            )

    del draw
    return second_image


try:
    # načtení originálního obrázku Leny
    original_image = Image.open(filename)
    original_image.load()

    # převod na úrovně šedi
    grayscale_image = ImageMath.eval("convert(src, 'L')", src=original_image)

    # vytvoření druhého obrázku s maskou
    second_image = create_second_image(512, 512)

    # aplikace operace
    result_image = ImageMath.eval(
        "first+second", first=grayscale_image, second=second_image
    )

    # další převod výsledku na stupně šedi
    result_image = ImageMath.eval("convert(src, 'L')", src=result_image)

    # zobrazení výsledného obrázku uživateli
    result_image.show()
Exemplo n.º 55
0
 def test_abs(self):
     self.assertEqual(pixel(ImageMath.eval("abs(A)", A=A)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("abs(B)", B=B)), "I 2")
Exemplo n.º 56
0
 def test_logical_lt(self):
     self.assertEqual(pixel(ImageMath.eval("A<A", A=A)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("B<B", B=B)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("A<B", A=A, B=B)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("B<A", A=A, B=B)), "I 0")
Exemplo n.º 57
0
 def test_bitwise_invert(self):
     self.assertEqual(pixel(ImageMath.eval("~Z", Z=Z)), "I -1")
     self.assertEqual(pixel(ImageMath.eval("~A", A=A)), "I -2")
     self.assertEqual(pixel(ImageMath.eval("~B", B=B)), "I -3")
Exemplo n.º 58
0
 def test_logical_ge(self):
     self.assertEqual(pixel(ImageMath.eval("A>=A", A=A)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("B>=B", B=B)), "I 1")
     self.assertEqual(pixel(ImageMath.eval("A>=B", A=A, B=B)), "I 0")
     self.assertEqual(pixel(ImageMath.eval("B>=A", A=A, B=B)), "I 1")
#      Pavel Tisnovsky
#

from PIL import Image
from PIL import ImageMath

filename = "Lenna.png"


try:
    # načtení originálního obrázku Leny
    original_image = Image.open(filename)
    original_image.load()

    # převod na úrovně šedi
    grayscale_image = ImageMath.eval("convert(src, 'L')", src=original_image)

    # aplikace operace
    result_image = ImageMath.eval("(~first) & 255", first=grayscale_image)

    # další převod výsledku na stupně šedi
    result_image = ImageMath.eval("convert(src, 'L')", src=result_image)

    # zobrazení výsledného obrázku uživateli
    result_image.show()

    # uložení výsledného obrázku
    result_image.save("40_image_math_not.png")

except Exception as e:
    print("Vyjimka: " + e.__str__())
Exemplo n.º 60
0
def gen_captcha(text, fontname, fontsize, file_name, old):
    """Generate a captcha image"""
    # white text on a black background
    bgcolor = 0x0
    fgcolor = 0xffffff
    # create a font object
    font = ImageFont.truetype(fontname,fontsize)
    # determine dimensions of the text
    dim = font.getsize(text)
    # create a new image significantly larger that the text
    edge = max(dim[0], dim[1]) + 2*min(dim[0], dim[1])
    im = Image.new('RGB', (edge, edge), bgcolor)
    d = ImageDraw.Draw(im)
    x, y = im.size
    # add the text to the image
    d.text((x/2-dim[0]/2, y/2-dim[1]/2), text, font=font, fill=fgcolor)
    k = 2
    wob = 0.09*dim[1]
    if old:
        k = 3
        wob = 0.20*dim[1]/k
    rot = 45
    # Apply lots of small stirring operations, rather than a few large ones
    # in order to get some uniformity of treatment, whilst
    # maintaining randomness
    for i in range(k):
        im = wobbly_copy(im, wob, bgcolor, i*2+3, rot+0, old)
        im = wobbly_copy(im, wob, bgcolor, i*2+1, rot+45, old)
        im = wobbly_copy(im, wob, bgcolor, i*2+2, rot+90, old)
        rot += 30

    # now get the bounding box of the nonzero parts of the image
    bbox = im.getbbox()
    # bord = min(dim[0], dim[1])/4 # a bit of a border
    # im = im.crop((bbox[0]-bord, bbox[1]-bord, bbox[2]+bord, bbox[3]+bord))

###
    center = (bbox[0] + (bbox[2]-bbox[0])/2,
              bbox[1] + (bbox[3]-bbox[1])/2)
    bord = 20
    im = im.crop((center[0] - (bord + dim[0]/2),
                  center[1] - (bord + dim[0]/len(text)/2),
                  center[0] + (bord + dim[0]/2),
                  center[1] + (bord + dim[0]/len(text)/2)))
###
    if not old:
        # Create noise
        nblock = 4
        nsize = (im.size[0] / nblock, im.size[1] / nblock)
        noise = Image.new('L', nsize, bgcolor)
        data = noise.load()
        for x in range(nsize[0]):
            for y in range(nsize[1]):
                r = random.randint(0, 65)
                gradient = 70 * x / nsize[0]
                data[x, y] = r + gradient
        # Turn speckles into blobs
        noise = noise.resize(im.size, Image.BILINEAR)
        # Add to the image
        im = ImageMath.eval('convert(convert(a, "L") / 3 + b, "RGB")', a=im, b=noise)

    # and turn into black on white
    im = ImageOps.invert(im)

    # save the image, in format determined from filename
    im.save(file_name)