Exemple #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
Exemple #2
0
def image_diff(im1, im2):
    """Return the diff of two images"""
    import Image
    import 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
Exemple #3
0
def variance(dirlist, folder):
	statsfldr = folder + statsfldrext
	try:
		vari = Image.open(statsfldr + "/variance" + ext)
	except:
		sum1 = openfloat(folder + "/" + dirlist[0])
		sum1 = sum1.point(lambda j: j * 0.0)
		i = 0
		for iimage in dirlist:
			print '(%i)' % i,
			j = 0
			for jimage in dirlist:
				imgi = openfloat(folder + "/" + iimage)
				imgj = openfloat(folder + "/" + jimage)
				sum1 = ImageMath.eval("((a-b)*(a-b))/2.0+c",a=imgi,b=imgj,c=sum1)
				print '%i' % j,
				j+=1
			i+=1
			print
		inv_i2 = 1.0 / i**2.0
		vari = sum1.point(lambda k: k * inv_i2)
		vari.save(statsfldr + "/variance" + ext)
		print "Saved the variance!",
		write_to_log('\t' + str(datetime.datetime.now()) + '    Saved the variance!\n')
	try:
		Image.open(statsfldr + "/StdDev" + ext)
	except:
		stdev = ImageMath.eval("a**0.5",a=vari)
		stdev.save(statsfldr + "/StdDev" + ext)
		print "Saved the standard deviation!",
		write_to_log('\t' + str(datetime.datetime.now()) + '    Saved the deviation!\n')
	return
Exemple #4
0
def color_to_alpha(image, color=None):
	"Takes a specific color value and changes it to alpha in image" 
	
	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. 
	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)
Exemple #5
0
def fitness(fingermask, pos, fil, size=None):
    """pos is the upper-left corner"""
    crop = fingermask.crop(
        (pos[0], pos[1], pos[0] + fil.size[0], pos[1] + fil.size[1]))
    if (ImageMath.eval("crop and crop", crop=crop) is False):
        return 0
    crop = crop.convert("I").point(lambda i: i * 0.00785 + (-1))
    conv = ImageMath.eval("crop*fil", crop=crop, fil=fil)
    s = 0
    pix = conv.load()
    for i in range(crop.size[0]):
        for j in range(crop.size[1]):
            # print "i=$i, j=$j, conv=$pix[$i,$j]"
            s += pix[i, j]
    return s
Exemple #6
0
    def _load(self, image, full=False, wait=True):
        if self.partials > 100:
            full = True

        image = image.convert('1', dither=Image.FLOYDSTEINBERG)

        if self.epd == None:  #dummy
            image.show()
            return

        if self.lastimage and not full:
            self.epd.setQuick(True)
            diff = ImageMath.eval("a-b", a=self.lastimage, b=image)
            box = diff.getbbox()
            if box == None:
                return


#      box=0,box[1],400,box[3]
            bits1 = self.epd.get_frame_window_buffer(self.lastimage, box)
            bits2 = self.epd.get_frame_window_buffer(image, box)
            self.epd.display_frame_window(bits1, bits2, box, wait)
            self.partials += 1

        else:
            self.epd.setQuick(False)
            if self.lastimage:
                bits1 = self.epd.get_frame_buffer(self.lastimage)
            else:
                bits1 = None
            bits2 = self.epd.get_frame_buffer(image)

            self.epd.display_frame(bits1, bits2, wait)
            self.partials = 0
        self.lastimage = image
Exemple #7
0
	def extract(self, source):
		"""Extract an image from *source*.

		If the image is supported an instance of PIL's Image is returned, otherwise None.
		"""
		p = Parser()
		f = open_pds(source)
		if self.log: self.log.debug("Parsing '%s'" % (source))
		self.labels = p.parse(f)
		if self.log: self.log.debug("Found %d labels" % (len(self.labels)))
		if self._check_image_is_supported():
			if self.log: self.log.debug("Image in '%s' is supported" % (source))
			dim = self._get_image_dimensions()
			loc = self._get_image_location()
			imageSampleBits = int(self.labels['IMAGE']['SAMPLE_BITS'])
			imageSampleType = self.labels['IMAGE']['SAMPLE_TYPE']
			md5Checksum = self._get_image_checksum()
			if self.log: self.log.debug("Image dimensions should be %s" % (str(dim)))
			if self.log: self.log.debug("Seeking to image data at %d" % (loc))
			f.seek(loc)
			if imageSampleBits == 8:
				readSize = dim[0] * dim[1]
			elif imageSampleBits == 16:
				readSize = dim[0] * dim[1] * 2
			print readSize
			if self.log: self.log.debug("Seek successful, reading data (%s)" % (readSize))
			# rawImageData = f.readline()
			# f.seek(-int(self.labels["RECORD_BYTES"]), os.SEEK_CUR)
			rawImageData = f.read(readSize)
			if md5Checksum:
				rawImageChecksum = hashlib.md5(rawImageData).hexdigest()
				checksumVerificationPassed = rawImageChecksum == md5Checksum and True or False
				if not checksumVerificationPassed:
					if self.log: self.log.debug("Secure hash verification failed")
					if self.raisesChecksumError:
						errorMessage = "Verification failed! Expected '%s' but got '%s'." % (md5Checksum, rawImageChecksum)
						raise ChecksumError, errorMessage
				else:
					if self.log: self.log.debug("Secure hash verification passed")
			if self.log: self.log.debug("Read successful (len: %d), creating Image object" % (len(rawImageData)))
			# The frombuffer defaults may change in a future release;
			# for portability, change the call to read:
			# frombuffer(mode, size, data, 'raw', mode, 0, 1).
			if (imageSampleBits == 16) and imageSampleType == ('MSB_INTEGER'):
				#img = Image.frombuffer('I', dim, rawImageData, 'raw', 'I;16BS', 0, 1)
				img = Image.frombuffer('F', dim, rawImageData, 'raw', 'F;16B', 0, 1)
				img = ImageMath.eval("convert(a/16.0, 'L')", a=img)
			else:
				img = Image.frombuffer('L', dim, rawImageData, 'raw', 'L', 0, 1)
			if self.log:
				self.log.debug("Image result: %s" % (str(img)))
				self.log.debug("Image info: %s" % (str(img.info)))
				self.log.debug("Image mode: %s" % (str(img.mode)))
				self.log.debug("Image size: %s" % (str(img.size)))
		else:
			if self.log: self.log.error("Image is not supported '%s'" % (source))
			img = None
		f.close()

		return img, self.labels
Exemple #8
0
def pilRgbaInvert(image):
	bands = image.split()
	outbands = []
	for band in bands:
		outbands.append(ImageMath.eval("convert(abs(~(254-a)),'L')",a=band))
	outimage = Image.merge("RGBA",outbands)
	return outimage
Exemple #9
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)
Exemple #10
0
def pilRgbaTwoImageMath(image1,image2,expression):
	bands1 = image1.split()
	bands2 = image1.split()
	outbands = []
	for band in range(4):
		outbands.append(ImageMath.eval(expression,a=bands1[band],b=bands2[band]))
	outimage = Image.merge("RGBA",outbands)
	return outimage
Exemple #11
0
def compute_difference(imfile, gtfile, outfile):
    """
   computes the difference image 
   """
    import Image, ImageMath
    im = Image.open(imfile)
    gt = Image.open(gtfile)

    tmp = ImageMath.eval("(float(imA)-float(imB))", imA=im, imB=gt)

    tmp.save(outfile)
Exemple #12
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
Exemple #13
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
Exemple #14
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)
Exemple #15
0
def convert_axpb(im, a, b):
    """
   Convert INT image to FLOAT, and apply axpb
   only works for gray images, for color ones must use something like
   bands=im.split()
   fbd=tuple([ ImageMath.eval('float(imA)', imA=m) for m in bands ])
   return Image.merge('F',fbd)
   """
    import Image, ImageMath
    return ImageMath.eval("float(imA)*paramA + paramB",
                          imA=im,
                          paramA=a,
                          paramB=b)
Exemple #16
0
def SNR(folder):
	# SNR is the ratio of signal average to the standard deviation of the signal
	statsfldr = folder + statsfldrext
	try:
		Image.open(statsfldr + "/SNR" + ext)
	except:
		av = Image.open(statsfldr + "/average" + ext)
		stdv = Image.open(statsfldr + "/StdDev" + ext)
		snr = ImageMath.eval("a/b",a=av,b=stdv)
		snr.save(statsfldr + "/SNR" + ext)
		print "Saved the SNR!"
		write_to_log('\t' + str(datetime.datetime.now()) + '    Saved the SNR!\n')
	return
def imconvert(infile, outfile):
    '''
    This method takes two filenames, one for in and one for out, then opens the infile
    resizes it to a more reasonable size, smooths for inconsistencies, then saves it
    as outfile.
    '''
    im = Image.open(infile)
    new = im.resize((100,75))
    new = new.filter(ImageFilter.SMOOTH)
    new = binarize(new)
    try:
        new.save(outfile)
    except IOError:
        print "cannot convert ", infile
Exemple #18
0
def makeColorTransparent(image, color, thresh2=0):
    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
Exemple #19
0
def average(dirlist, folder):
	statsfldr = folder + statsfldrext
	try: # these tries make sure that we are not recalculating images if they exist
		Image.open(statsfldr + "/average" + ext)
	except:
		sum0 = openfloat(folder + "/" + dirlist[0])
		sum0 = ImageMath.eval("a * 0.0",a=sum0)
		i = 0
		print "combining pictures:",
		for image in dirlist:
			try:
				img = openfloat(folder + "/" + image)
				sum0 = ImageMath.eval("a+b",a=img,b=sum0)
				print "%i" % i,
				i+=1
			except:
				print "Could not get file: %s" % image
		inv_i = 1.0 / i
		average = sum0.point(lambda k: k * inv_i)
		average.save(statsfldr + "/average" + ext)
		print "Saved the average!"
		write_to_log('\t' + str(datetime.datetime.now()) + '    Saved the average!\n')

	return
Exemple #20
0
def put_mask(image, mask, resample_mask, cache=None):
    if cache is None:
        cache = {}
    resample_mask = getattr(Image, resample_mask)
    id = mask + "_w%d_h%d" % image.size
    try:
        mask = cache[id]
    except KeyError:
        mask = cache[id] = open_image(mask).convert("L").resize(image.size, resample_mask)
    if not has_transparency(image):
        image = image.convert("RGBA")
    else:
        if has_transparency(image):
            image = image.convert("RGBA")
        alpha = imtools.get_alpha(image)
        mask = ImageMath.eval("convert(min(a, b), 'L')", a=alpha, b=mask)
    image.putalpha(mask)
    return image
Exemple #21
0
def put_mask(image, mask, resample_mask, cache=None):
    if cache is None:
        cache = {}
    resample_mask = getattr(Image, resample_mask)
    id = mask + '_w%d_h%d' % image.size
    try:
        mask = cache[id]
    except KeyError:
        mask = cache[id] = open_image(mask).convert('L').resize(
            image.size, resample_mask)
    if not has_transparency(image):
        image = image.convert('RGBA')
    else:
        if has_transparency(image):
            image = image.convert('RGBA')
        alpha = imtools.get_alpha(image)
        mask = (ImageMath.eval("convert(min(a, b), 'L')", a=alpha, b=mask))
    image.putalpha(mask)
    return image
Exemple #22
0
def mk_rand_bin_img_from_mask(mask_im):
    bin_font = ImageFont.truetype('consola.ttf', 9)
    bin_color = (0xc8, 0xff, 0xc8, 0xff)

    im = Image.new('RGBA', mask_im.size)
    draw = ImageDraw.Draw(im)

    width, height = im.size

    one = bin_font.getsize('1')
    zero = bin_font.getsize('0')
    
    start_x = 0
    start_y = 0

    import random

    for start_y in xrange(start_y, height, zero[1]):
        randstr = ''.join(random.choice(['1', '0']) for _ in xrange(100))
        draw.text((start_x, start_y), randstr, font=bin_font, fill=bin_color)

    display.display(im)

    import ImageMath

    bands = im.split()

    bands = [
        ImageMath.eval(
            'convert(min(mask, band), "L")',
            mask = mask_im,
            band = band
        )
        for band in bands
    ]

    new_im = Image.merge('RGBA', bands)

    with file('foo.jpg', 'wb') as f:
        new_im.save(f, format='jpeg')

    display.display(new_im)
Exemple #23
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
Exemple #24
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
Exemple #25
0
 def divide(ch):
     env = {"val": ch, "mask": maskgray}
     return ImageMath.eval("val*255/mask", env).convert("L")
Exemple #26
0
mult = 2
im.point(lambda i: i * mult).save(folder + "contrast_stretch.bmp") # multiply each pixel in the image by mult

''' thresholding
the following splits off channels and pastes back the areas that have red pixels less than a value and doubles the green value there
'''
source = im.split() # split the image into individual bands
R, G, B = 0, 1, 2
mask = source[R].point(lambda i: i < 200 and 255) # select regions where red is less than 10
out = source[G].point(lambda i: i * 2) # process the green band
source[G].paste(out, None, mask) # paste the processed band back, but only where red was < 100
imout = Image.merge(im.mode, source) # build a new multiband image
imout.save(folder + "masking.jpg")

''' image enhancement
ImageEnhance module can be used to enhance (stuff?, read up: http://effbot.org/imagingbook/imageenhance.htm)
'''
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).save(folder + "30percent_contrast_enhance.jpg")

''' image evaluation
this module is for doing calculations on images, like adding two
'''
ima = im.convert("L")
sum0 = ImageMath.eval("a + b",a=ima,b=ima) # automatically converts to 32 bit image when doing math as needed, therefore needs to be saved as tiff
sum0.save(folder + "sum.tiff")

def openfloat(image): # can feed this an image in greyscale to convert to floating point
    im = Image.open(image)
    im = ImageMath.eval("convert(a,'F')",a=im)
    return im
Exemple #27
0
def makeColorTransparent(image, color, thresh2=0):
    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
Exemple #28
0
def openfloat(image): # can feed this an image in greyscale to convert to floating point
    im = Image.open(image)
    im = ImageMath.eval("convert(a,'F')",a=im)
    return im
Exemple #29
0
def openfloat(image):
	im = Image.open(image)
	im = ImageMath.eval("convert(a,'F')",a=im)
	return im
Exemple #30
0
def color_to_alpha(image, color_value=None, select_color_by=None):
    image = image.convert('RGBA')
    width, height = image.size
    select = select_color_by
    color = color_value
    if select == OPTIONS[0]:
        color = HTMLColorToRGBA(color, 255)
    elif select == OPTIONS[1]:
        color = image.getpixel((0, 0))
    elif select == OPTIONS[2]:
        color = image.getpixel((width - 1, 0))
    elif select == OPTIONS[3]:
        color = image.getpixel((0, height - 1))
    elif select == OPTIONS[4]:
        color = image.getpixel((width - 1, height - 1))
    else:
        return image

    if color[3] == 0:
        # The selected color is transparent
        return image

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

    # 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)
Exemple #31
0
import Image, ImageMath

im1 = Image.open("image1.jpg")
im2 = Image.open("image2.jpg")

out = ImageMath.eval("convert(min(a, b), 'L')", a=im1, b=im2)
out.save("result.png")
Exemple #32
0
		def divide(ch):
			env = {"val": ch, "mask": maskgray}
			return ImageMath.eval("val*255/mask",env).convert("L")
Exemple #33
0
def RGBtoRGM(image):
    r, g, b = image.split()
    m = ImageMath.eval('convert(x+y,"L")', x=r, y=b)
    return Image.merge('RGB', (r, g, m))
def color_to_alpha(image, color_value=None, select_color_by=None):
    image = image.convert('RGBA')
    width, height = image.size
    select = select_color_by
    color = color_value
    if select == OPTIONS[0]:
        color = HTMLColorToRGBA(color, 255)
    elif select == OPTIONS[1]:
        color = image.getpixel((0, 0))
    elif select == OPTIONS[2]:
        color = image.getpixel((width - 1, 0))
    elif select == OPTIONS[3]:
        color = image.getpixel((0, height - 1))
    elif select == OPTIONS[4]:
        color = image.getpixel((width - 1, height - 1))
    else:
        return image

    if color[3] == 0:
        # The selected color is transparent
        return image

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

    # 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)
Exemple #35
0
def imageBlend(a, b, r):
	return ImageMath.eval("a+(b-a)*r", a=a,b=b,r=r)
def check_combination(seq):
    '''
    The main algorithmic portion of the program. Takes the png file, makes it a ppm
    file. Uses the pixel data of that smaller, better ppm file and converts it to
    binary 0's and 1's. Using that image, we compute the center of mass and bounding
    box. The ratio of these two tells us whether the image is splayed vs. fist.
    Then in the creativity portion, this is extended. We look at the number of
    connected components, as well as the rectangularness of the bounding box to
    determine the gesture being formed.
    '''
    #past gestures and unlock y/n
    history = ('','')
    result = 0
    
    for num in seq:
        # convert png files to ppm
        filename = 'images/h' + str(num) + '.png'
        outname =  'images/hh' + str(num) + '.ppm'
        imconvert(filename, outname)

        # convert to binary 0/1 file
        im = Image.open(outname)

        # calculate center of mass and bounding box for skin
        com = centermass(im)
        loc = im.getbbox() #left, upper, right, lower
        bbox_area = (loc[2] - loc[0])*(loc[3] - loc[1])

        # calculate ratio of bounding box area to actual skin area
        bc_ratio = bbox_area/float(com[0])

        #calclate bounding box width to length ratio
        bbox_width = (loc[2] - loc[0])
        bbox_height = (loc[3] - loc[1])
        bb_wh_ratio = bbox_width / float(bbox_height)

        #calculate the number of connected components
        cc = conn_comp(outname)

        #FROM ORIGINAL, not CREATIVITY:
        #if bc_ratio < 1.45:
        #    #FIST
        #        # UPPER LEFT                    #UPPER RIGHT
        #    if (com[0] < 40 and com[1] < 33) or (com[0] < 40 and com[1] > 45)
        #        or (com[0] > 60 and com[1] > 45) or (com[0] > 60 and com[1] < 33):
        #        # LOWER RIGHT                       #LOWER LEFT
        #        if(hist == "SPLAY_CEN"):
        #            return 1
        #        else
        #            hist == "FIST_COR"
        #elif bc_ratio > 2.0:
        #    #SPLAY
        #    if com[0] > 35 and com[0] < 65 and com[1] > 25 and com[1] < 53:
        #        #CENTER
        #        hist == "SPLAY_CEN"
        #else:
        #    #UNKNOWN
        #    hist = "?"
        
        #determine which gesture it is, and proper response based on history
        #CORRECT:
        cur = ""
        if cc == 2 and bb_wh_ratio < 1.2 and bb_wh_ratio > .7:
            # Circle "O" Symbol
            cur = "O"
        elif cc == 2 and bb_wh_ratio > 1.5 and bb_wh_ratio < 3.0:
            #"OK" Symbol
            cur = "OK"
        elif cc == 1 and bb_wh_ratio < 1.2 and bb_wh_ratio > 0.7:
            #Fist
            # automatic cancel if fist in lower right corner
            if com[0] > 60 and com[1] > 45:
                return 0;
            cur = "FIST"
        elif cc == 1 and bb_wh_ratio > 1.5 and bb_wh_ratio < 3.0:
            #splay palm
            cur = "SPLAY"
        elif cc == 1 and bb_wh_ratio > 4.0:
            #horizontal chop
            cur = "HCHOP"
        elif cc == 1 and bb_wh_ratio < 0.5:
            #vertical chop
            cur = "VCHOP"
        else:
            #UH-OH! Unknown - pretend it's another symbol not part of passcode
            cur = "?"
        #check if combo is good
        if history[1] == "VCHOP" and history[0] == "O":
            result = 1
        else:
        #update history
            history[1] = history[0]
            history[0] = cur
            
    return result
Exemple #37
0
def compare(im, ref):
    import ImageMath
    # See http://www.pythonware.com/library/pil/handbook/imagemath.htm
    mask = ImageMath.eval("min(abs(a - b), 1)", a=im, b=ref)
    gray = ref.convert('L')
Exemple #38
0
def decodeImageData(data,
                    size,
                    stride,
                    redMask,
                    greenMask,
                    blueMask,
                    alphaMask,
                    isLinear=True,
                    isPremultiplied=False):
    w, h = size[0], size[1]

    if debug:
        print "Decoding image data:"
        print "    Red mask: %08x" % redMask
        print "  Green mask: %08x" % greenMask
        print "   Blue mask: %08x" % blueMask
        print "  Alpha mask: %08x" % alphaMask

    # Imaging library fast paths
    if   redMask   == 0xff000000 and \
         greenMask == 0x00ff0000 and \
         blueMask  == 0x0000ff00 and \
         alphaMask == 0x000000ff:
        image = Image.fromstring("RGBA", size, data, "raw", "ABGR", stride)
    elif redMask   == 0x000000ff and \
         greenMask == 0x0000ff00 and \
         blueMask  == 0x00ff0000 and \
         alphaMask == 0xff000000:
        image = Image.fromstring("RGBA", size, data, "raw", "RGBA", stride)
    elif redMask   == 0x0000ff00 and \
         greenMask == 0x00ff0000 and \
         blueMask  == 0xff000000 and \
         alphaMask == 0x000000ff:
        image = Image.fromstring("RGBA", size, data, "raw", "ARGB", stride)
    elif redMask   == 0x00ff0000 and \
         greenMask == 0x0000ff00 and \
         blueMask  == 0x000000ff and \
         alphaMask == 0xff000000:
        image = Image.fromstring("RGBA", size, data, "raw", "BGRA", stride)
    elif redMask   == 0x00ff0000 and \
         greenMask == 0x0000ff00 and \
         blueMask  == 0x000000ff and \
         alphaMask == 0x00000000:
        image = Image.fromstring("RGB", size, data, "raw", "BGR", stride)
    elif redMask   == 0x000000ff and \
         greenMask == 0x0000ff00 and \
         blueMask  == 0x00ff00ff and \
         alphaMask == 0x00000000:
        image = Image.fromstring("RGB", size, data, "raw", "RGB", stride)
    else:
        redOffset = log2((1 << (log2(redMask) + 1)) - redMask)
        greenOffset = log2((1 << (log2(greenMask) + 1)) - greenMask)
        blueOffset = log2((1 << (log2(blueMask) + 1)) - blueMask)
        alphaOffset = log2((1 << (log2(alphaMask) + 1)) - alphaMask)

        redBits = log2(redMask >> redOffset) + 1
        greenBits = log2(greenMask >> greenOffset) + 1
        blueBits = log2(blueMask >> blueOffset) + 1
        alphaBits = log2(alphaMask >> alphaOffset) + 1
        bpp = redBits + greenBits + blueBits + alphaBits

        if debug:
            print "Warning: No fast path for image format"

        image = Image.new(alphaMask and "RGBA" or "RGBX", (w, h))
        dataOut = range(w * h)
        dataPos = 0

        for y in range(h):
            scanline = data[y * stride:(y + 1) * stride]
            for x in range(w):
                pixel = scanline[x * bpp:(x + 1) * bpp]
                pixel = sum(
                    [ord(p) * (1 << (i * 8)) for i, p in enumerate(pixel)])
                if redBits:
                    red = (255 * ((pixel >> redOffset) & redMask)) / (
                        (1 << redBits) - 1)
                else:
                    red = 0
                if greenBits:
                    green = (255 * ((pixel >> greenOffset) & greenMask)) / (
                        (1 << greenBits) - 1)
                else:
                    green = 0
                if blueBits:
                    blue = (255 * ((pixel >> blueOffset) & blueMask)) / (
                        (1 << blueBits) - 1)
                else:
                    blue = 0
                if alphaBits:
                    alpha = (255 * ((pixel >> alphaOffset) & alphaMask)) / (
                        (1 << alphaBits) - 1)
                else:
                    alpha = 255

                dataOut[dataPos] = (red, green, blue, alpha)
                dataPos += 1
        image.putdata(dataOut)

    if not isLinear:
        if alphaMask:
            r, g, b, a = image.split()
            r = r.point(sRGB_to_lRGB)
            g = g.point(sRGB_to_lRGB)
            b = b.point(sRGB_to_lRGB)
            image = Image.merge(image.mode, (r, g, b, a))
        else:
            r, g, b = image.split()
            r = r.point(sRGB_to_lRGB)
            g = g.point(sRGB_to_lRGB)
            b = b.point(sRGB_to_lRGB)
            image = Image.merge(image.mode, (r, g, b))

    if isPremultiplied and alphaMask:
        r, g, b, a = image.split()
        r = ImageMath.eval("convert(255 * color / alpha, 'L')",
                           color=r,
                           alpha=a)
        g = ImageMath.eval("convert(255 * color / alpha, 'L')",
                           color=g,
                           alpha=a)
        b = ImageMath.eval("convert(255 * color / alpha, 'L')",
                           color=b,
                           alpha=a)
        image = Image.merge(image.mode, (r, g, b, a))

    return image
Exemple #39
0
# PIL Divide Blend test

import Image
import ImageMath

imgA = Image.open('dirt05.jpg')
imgA.load()
imgB = Image.open('dirt05.jpg')
imgB.load()

# 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)+1)/256))", a=rA, b=rB).convert('L')
gTmp = ImageMath.eval("int(a/((float(b)+1)/256))", a=gA, b=gB).convert('L')
bTmp = ImageMath.eval("int(a/((float(b)+1)/256))", a=bA, b=bB).convert('L')

# merge channels into RGB image
imgOut = Image.merge("RGB", (rTmp, gTmp, bTmp))

imgOut.save('foi.png', 'PNG')

os.system('start.png')
Exemple #40
0
def decodeImageData(data, size, stride, redMask, greenMask, blueMask, alphaMask, isLinear=True, isPremultiplied=False):
    w, h = size[0], size[1]

    if debug:
        print "Decoding image data:"
        print "    Red mask: %08x" % redMask
        print "  Green mask: %08x" % greenMask
        print "   Blue mask: %08x" % blueMask
        print "  Alpha mask: %08x" % alphaMask

    # Imaging library fast paths
    if redMask == 0xFF000000 and greenMask == 0x00FF0000 and blueMask == 0x0000FF00 and alphaMask == 0x000000FF:
        image = Image.fromstring("RGBA", size, data, "raw", "ABGR", stride)
    elif redMask == 0x000000FF and greenMask == 0x0000FF00 and blueMask == 0x00FF0000 and alphaMask == 0xFF000000:
        image = Image.fromstring("RGBA", size, data, "raw", "RGBA", stride)
    elif redMask == 0x0000FF00 and greenMask == 0x00FF0000 and blueMask == 0xFF000000 and alphaMask == 0x000000FF:
        image = Image.fromstring("RGBA", size, data, "raw", "ARGB", stride)
    elif redMask == 0x00FF0000 and greenMask == 0x0000FF00 and blueMask == 0x000000FF and alphaMask == 0xFF000000:
        image = Image.fromstring("RGBA", size, data, "raw", "BGRA", stride)
    elif redMask == 0x00FF0000 and greenMask == 0x0000FF00 and blueMask == 0x000000FF and alphaMask == 0x00000000:
        image = Image.fromstring("RGB", size, data, "raw", "BGR", stride)
    elif redMask == 0x000000FF and greenMask == 0x0000FF00 and blueMask == 0x00FF00FF and alphaMask == 0x00000000:
        image = Image.fromstring("RGB", size, data, "raw", "RGB", stride)
    else:
        redOffset = log2((1 << (log2(redMask) + 1)) - redMask)
        greenOffset = log2((1 << (log2(greenMask) + 1)) - greenMask)
        blueOffset = log2((1 << (log2(blueMask) + 1)) - blueMask)
        alphaOffset = log2((1 << (log2(alphaMask) + 1)) - alphaMask)

        redBits = log2(redMask >> redOffset) + 1
        greenBits = log2(greenMask >> greenOffset) + 1
        blueBits = log2(blueMask >> blueOffset) + 1
        alphaBits = log2(alphaMask >> alphaOffset) + 1
        bpp = redBits + greenBits + blueBits + alphaBits

        if debug:
            print "Warning: No fast path for image format"

        image = Image.new(alphaMask and "RGBA" or "RGBX", (w, h))
        dataOut = range(w * h)
        dataPos = 0

        for y in range(h):
            scanline = data[y * stride : (y + 1) * stride]
            for x in range(w):
                pixel = scanline[x * bpp : (x + 1) * bpp]
                pixel = sum([ord(p) * (1 << (i * 8)) for i, p in enumerate(pixel)])
                if redBits:
                    red = (255 * ((pixel >> redOffset) & redMask)) / ((1 << redBits) - 1)
                else:
                    red = 0
                if greenBits:
                    green = (255 * ((pixel >> greenOffset) & greenMask)) / ((1 << greenBits) - 1)
                else:
                    green = 0
                if blueBits:
                    blue = (255 * ((pixel >> blueOffset) & blueMask)) / ((1 << blueBits) - 1)
                else:
                    blue = 0
                if alphaBits:
                    alpha = (255 * ((pixel >> alphaOffset) & alphaMask)) / ((1 << alphaBits) - 1)
                else:
                    alpha = 255

                dataOut[dataPos] = (red, green, blue, alpha)
                dataPos += 1
        image.putdata(dataOut)

    if not isLinear:
        if alphaMask:
            r, g, b, a = image.split()
            r = r.point(sRGB_to_lRGB)
            g = g.point(sRGB_to_lRGB)
            b = b.point(sRGB_to_lRGB)
            image = Image.merge(image.mode, (r, g, b, a))
        else:
            r, g, b = image.split()
            r = r.point(sRGB_to_lRGB)
            g = g.point(sRGB_to_lRGB)
            b = b.point(sRGB_to_lRGB)
            image = Image.merge(image.mode, (r, g, b))

    if isPremultiplied and alphaMask:
        r, g, b, a = image.split()
        r = ImageMath.eval("convert(255 * color / alpha, 'L')", color=r, alpha=a)
        g = ImageMath.eval("convert(255 * color / alpha, 'L')", color=g, alpha=a)
        b = ImageMath.eval("convert(255 * color / alpha, 'L')", color=b, alpha=a)
        image = Image.merge(image.mode, (r, g, b, a))

    return image
Exemple #41
0
def imageBlend(a, b, r):
    return ImageMath.eval("a+(b-a)*r", a=a, b=b, r=r)
Exemple #42
0
rot = i1.rotate(1.)
i6 = ImageChops.darker(rot, i4)

i7 = ImageChops.darker(marked, i2)
print i2.size
print i7.size
# Hard to believe this is the correct approach,
# but we look for white a and black b,
# meaning areas marked on b but not marked on a.
# These give us 1s as opposed to 0s.
# We then convert image result from "I" 32 bit signed integer pixels
# to "L"uminance 8 bit signed pixels, and invert the result.
# (Alternatively, we could paint the result onto the original image
# with only one color channel operating.)
i8 = ImageMath.eval("convert((a & ~b),'RGB')", a=i2, b=i7)
i8.save("/tmp/i8.jpg")
i8r, i8g, i8b = i8.split()

i8r = i2
i8b = i2
i8g = ImageChops.darker(i7, i2)
i9 = Image.merge('RGB', (i8r, i8g, i8b))
i9.save("/tmp/i9.jpg")

i8s = ImageStat.Stat(i8)
print "i8s.sum", i8s.sum

print "mask", crop_edges_get_sum(i4, "/tmp/i4.jpg")
print "half degree", crop_edges_get_sum(i5, "/tmp/i5.jpg")
print "full degree", crop_edges_get_sum(i6, "/tmp/i6.jpg")