Esempio n. 1
0
def create_photo_strips():
    '''using the original images we build a color and black and white photo strip and save it to photos/strips'''
    strip = Image.new('RGB', (PHOTO_HEIGHT + (BORDER_WIDTH * 2) + FOOTER_HEIGHT, (PHOTO_WIDTH * PHOTO_COUNT) + (BORDER_WIDTH * 2)), BG_COLOR)    

    for i in range(PHOTO_COUNT):
        photo = Image.open(PHOTO_FOLDER + str(i+1) + '.' + PHOTO_FILE_EXTENSION)
        
        w, h = map(lambda x: x/2, photo.size)
        
        photo = ImageOps.fit(photo, (PHOTO_WIDTH, PHOTO_HEIGHT), centering=(0.5, 0.5))
        photo = photo.rotate(270)
        photo = ImageOps.autocontrast(photo, cutoff=0)
        
        strip.paste(photo, (FOOTER_HEIGHT, (i * PHOTO_WIDTH) + (i * BORDER_WIDTH)))

    #append footer

    font = ImageFont.truetype('font_1.ttf', 40)

    footer_img = Image.new("RGB", ((PHOTO_COUNT * PHOTO_WIDTH) + (PHOTO_COUNT * BORDER_WIDTH), FOOTER_HEIGHT), BG_COLOR)
    draw = ImageDraw.Draw(footer_img)
    draw.text((220, 40), "ashley & david's wedding, july 28, 2012", font=font, fill=(100,100,0))
    strip.paste(footer_img.rotate(270), (0,0))

    strip.save(COLOR_FOLDER + current_timestamp() + '.png', PHOTO_FORMAT)
    ImageOps.grayscale(strip).save(GREYSCALE_FOLDER + current_timestamp() + '.png', PHOTO_FORMAT)

    strip_to_print = Image.new('RGB', (PAGE_WIDTH, PAGE_HEIGHT), BG_COLOR)
    strip_to_print.paste(ImageOps.grayscale(strip), (-BORDER_WIDTH, -BORDER_WIDTH))

    strip_to_print.save('to_print.png', PHOTO_FORMAT)
    
    return 'to_print.png'
Esempio n. 2
0
def get_difference_image(im1, im2):
    try:
        import cv2
        result = cv2.matchTemplate(numpy.array(im1),
                                   numpy.array(im2)[32:-32, 32:-32],
                                   cv2.TM_CCOEFF_NORMED)
        #Image.fromarray(result * 255).show()
        off = numpy.unravel_index(result.argmax(), result.shape)
        minoff = off[0] - 32, off[1] - 32
    except ImportError:
        # pick a sample
        pix1 = numpy.array(ImageOps.grayscale(im1))[32:64, 32:64]
        pix2 = numpy.array(ImageOps.grayscale(im2))[32:64, 32:64]

        mindiff = sys.maxint
        minoff = (0, 0)

        # find best alignment for the sample
        for xoff in range(-20, 20):
            for yoff in range(-20, 20):
                #print xoff, yoff
                pix2off = pix2
                pix2off = numpy.roll(pix2off, xoff, 0)
                pix2off = numpy.roll(pix2off, yoff, 1)
                diff = sum((numpy.maximum(pix1, pix2off) -
                            numpy.minimum(pix1, pix2off)).flatten())
                if diff < mindiff:
                    mindiff = diff
                    minoff = xoff, yoff
                    print mindiff, minoff

    # align the full images
    xoff, yoff = minoff

    pix1 = numpy.array(im1)
    pix2 = numpy.array(im2)

    pix2off = pix2
    pix2off = numpy.roll(pix2off, minoff[0], 0)
    pix2off = numpy.roll(pix2off, minoff[1], 1)

    diff = numpy.maximum(pix1, pix2off) - numpy.minimum(pix1, pix2off)

    # only show the overlap
    xoff = abs(xoff)
    yoff = abs(yoff)
    diff = diff[xoff:diff.shape[0] - 2 * xoff, yoff:diff.shape[1] - 2 * yoff]

    #Image.fromarray(diff).show()

    return diff
Esempio n. 3
0
def get_difference_image(im1, im2):
    try:
        import cv2
        result = cv2.matchTemplate(numpy.array(im1), numpy.array(im2)[32:-32, 32:-32], cv2.TM_CCOEFF_NORMED)
        #Image.fromarray(result * 255).show()
        off = numpy.unravel_index(result.argmax(), result.shape)
        minoff = off[0]-32, off[1]-32
    except ImportError:
        # pick a sample
        pix1 = numpy.array(ImageOps.grayscale(im1))[32:64, 32:64]
        pix2 = numpy.array(ImageOps.grayscale(im2))[32:64, 32:64]

        mindiff = sys.maxint
        minoff = (0, 0)

        # find best alignment for the sample
        for xoff in range(-20, 20):
            for yoff in range(-20, 20):
                #print xoff, yoff
                pix2off = pix2
                pix2off = numpy.roll(pix2off, xoff, 0)
                pix2off = numpy.roll(pix2off, yoff, 1)
                diff = sum((numpy.maximum(pix1, pix2off) - numpy.minimum(pix1, pix2off)).flatten())
                if diff < mindiff:
                    mindiff = diff
                    minoff = xoff, yoff
                    print mindiff, minoff

    # align the full images
    xoff, yoff = minoff

    pix1 = numpy.array(im1)
    pix2 = numpy.array(im2)

    pix2off = pix2
    pix2off = numpy.roll(pix2off, minoff[0], 0)
    pix2off = numpy.roll(pix2off, minoff[1], 1)

    diff = numpy.maximum(pix1, pix2off) - numpy.minimum(pix1, pix2off)

    # only show the overlap
    xoff = abs(xoff)
    yoff = abs(yoff)
    diff = diff[xoff:diff.shape[0]-2*xoff, yoff:diff.shape[1]-2*yoff]

    #Image.fromarray(diff).show()

    return diff
def getSeatSix():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+530,yPad+60,xPad+593,yPad+76)))
    a = array(im.getcolors())
    im.save(os.getcwd() + '\\SeatSixBubble.png', 'PNG')
    print 'table 6 bubble = %d' % a.sum()
    return a.sum()
def getSeatFive():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+429,yPad+60,xPad+492,yPad+76)))
    a = array(im.getcolors())
    im.save(os.getcwd() + '\\SeatFiveBubble.png', 'PNG')
    print 'table 5 bubble = %d' % a.sum()
    return a.sum()
def getSeatFour():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+328,yPad+60,xPad+391,yPad+76)))
    a = array(im.getcolors())
    im.save(os.getcwd() + '\\SeatFourBubble.png', 'PNG')
    print 'table 4 bubble = %d' % a.sum()
    return a.sum()
def getSeatTwo():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+126,yPad+60,xPad+189,yPad+76)))
    im.save(os.getcwd() + '\\SeatTwoBubble.png', 'PNG')
    a = array(im.getcolors())
    print 'table 2 bubble = %d' % a.sum()
    return a.sum()
Esempio n. 8
0
def getSeatThree():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+227,yPad+60,xPad+290,yPad+76)))
    a = array(im.getcolors())
##    im.save(os.getcwd() + '\\SeatThreeBubble.png', 'PNG')
    print 'table 3 bubble = %d' % a.sum()
    return a.sum()
Esempio n. 9
0
def geticonshape(shape, dim_horiz, dim_vert):
    iconimage = ''.join([shape, '_icon.png'])
    img = Image.open(iconimage)
    img = ImageOps.grayscale(img)
    img = ImageOps.autocontrast(img)
    img = img.resize((dim_horiz, dim_vert), Image.BILINEAR)
    return img
Esempio n. 10
0
def plotfig2image(fig):
    """Convert a matplotlib pyplot figure to a numpy image."""
    imgdata = StringIO.StringIO()
    fig.savefig(imgdata, format='png')
    imgdata.seek(0)  # rewind the data
    im = ImageOps.grayscale(Image.open(imgdata))
    return numpy.asarray(im)
Esempio n. 11
0
def filter(infile, outfile):
    # img = Image.open(infile)
    img = ImageOps.grayscale(Image.open(infile))

    # differrentiate
    # flist = [-1, 0, 1,
    #         -2, 0, 2,
    #         -1, 0, 1]

    # 8傍近接ラプラシアン
    # flist = [1,  1, 1,
    #         1, -8, 1,
    #         1,  1, 1]

    # 4傍近接ラプラシアン
    # flist = [0,  1, 0,
    #         1, -4, 1,
    #         0,  1, 0]
    flist = [-0.1, -0.2, -0.1, -0.2, 2.2, -0.2, -0.1, -0.2, -0.1]

    # flt = ImageFilter.Kernel((3,3), flist, scale=1, offset=128)
    flt = ImageFilter.Kernel((3, 3), flist, scale=1)
    imgx = img.filter(flt)

    # imgx = img.filter(ImageFilter.EMBOSS)
    # imgx.show()
    imgx.save(outfile)

    return
Esempio n. 12
0
def extract_region(image, coordinates):
    """
    Crop the given image using the given coordinates into output file.
    """
    output = hashlib.md5(image + coordinates).hexdigest()
    root = '/var/ccsd-scripts/regions/%s/%s/' % (output[:2], output[2:4])
    if not os.path.isdir(root):
        os.makedirs(root)
    output = os.path.join(root, output + '.tiff')
    if not os.path.exists(output):
        print("extracting_region(%r, %r)" % (image, coordinates))
        # Cache the Image object to speed things up.
        #
        # This way, we only open an original image up once and crop as
        # many times as needed -- rather than opening the same
        # original image a bunch of times.
        #
        # We only store the active Image object and discard it once we
        # move onto the next image to keep the cache from growing too
        # big. Since we only open image files once, this isn't a huge
        # deal.
        if not IMAGE_CACHE['active'] == image:
            IMAGE_CACHE['active'] = image
            IMAGE_CACHE['im'] = Image.open(image)
        im = IMAGE_CACHE['im']
        box = coords(coordinates)
        region = im.crop(box)
        pix = region.load()
        # If the top-leftmost pixel isn't white, coerce to black and white.
        if pix[0,0] != (255, 255, 255):
            region = ImageOps.grayscale(region)
            # http://stackoverflow.com/questions/6485254/how-to-i-use-pil-image-pointtable-method-to-apply-a-threshold-to-a-256-gray-im
            region = region.point(lambda p: p > 50 and 255)
        region.save(output)
    return output
Esempio n. 13
0
def grab():
    box = (c,b,z,q)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    print a
    return a
Esempio n. 14
0
def grab():
	box = (X_PAD + 1, Y_PAD +1,X_PAD + 640, Y_PAD + 480)
	im = ImageOps.grayscale(ImageGrab.grab(box))
	a = array(im.getcolors())
	a = a.sum()
	print a
	return a
Esempio n. 15
0
def main(argv):
    if len(argv) != 2:
        raise ValueError(
            'Expected path to image. Usage: ./{0} <path-to-image>'.format(
                argv[0]))

    filename = argv[1]
    img = ImageOps.grayscale(Image.open(filename))

    packed_grayscales = []
    data = img.getdata()
    for i in xrange(0, len(data), 4):
        packed_int = 0
        for j in xrange(4):
            if i + j >= len(data):
                break
            packed_int <<= 8
            packed_int += data[i + j]
        packed_grayscales.append(packed_int)

    width, height = img.size
    print string.Template(_TEMPLATE).substitute(
        width=width,
        height=height,
        grayscales=', '.join(str(p) for p in packed_grayscales))
Esempio n. 16
0
def plotfig2image(fig):
    """Convert a matplotlib pyplot figure to a numpy image."""
    imgdata = StringIO.StringIO()
    fig.savefig(imgdata, format='png')        
    imgdata.seek(0)  # rewind the data
    im = ImageOps.grayscale(Image.open(imgdata))
    return numpy.asarray( im )
Esempio n. 17
0
def get_bar():  #returns whether the bar is red or gray
    box = (Cord.redBar[0], Cord.redBar[1], Cord.redBar[0] + 2,
           Cord.redBar[1] + 5)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    return a
Esempio n. 18
0
def tats(image):
    image = image.convert('RGB')
    colours = util.get_dominant_colours(image, 9)
    colours = util.order_colours_by_brightness(colours)

    bg = random.choice(colours[:3])
    light = random.choice(colours[3:6])
    dark = random.choice(colours[6:])

    dist = math.sqrt(sum(map(lambda (a, b): math.pow(a - b, 2), zip(light, dark))))
    if dist < 100:
        light = util.modify_hls(light, l=lambda l: l + 100)

    light = util.modify_hls(light, s=lambda s: s + 100)
    dark = util.modify_hls(dark, s=lambda s: s + 100)

    layer = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' +
                       'assets/tats.png')
    layer.load()
    r, g, b, a = layer.split()
    layer = layer.convert('RGB')
    layer = ImageOps.grayscale(layer)
    layer = ImageOps.colorize(layer, tuple(dark), tuple(light))
    layer.putalpha(a)
    im = Image.new('RGB', layer.size, tuple(bg))
    im.paste(layer, mask=layer)
    return im
Esempio n. 19
0
def getSeatTwo():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+126,yPad+60,xPad+189,yPad+76)))
##    im.save(os.getcwd() + '\\SeatTwoBubble.png', 'PNG')
    a = array(im.getcolors())
    print 'table 2 bubble = %d' % a.sum()
    return a.sum()
	def __init__(self, player):
		self.board = Board()
		self.player = player
		sig = Image.open("sig.png")
		sig = ImageOps.grayscale(sig)
		sigp = sig.load()

		n = []
		for i in range(sig.size[0]):
			n.append(sigp[i, 0])

		# Assinatura em formato de string
		n = ' '.join(map(str, n))

		raw_input("Posicione a janela e pressione enter para comecar...")
		sleep(2)
		scp = self.screenCapture()

		w = scp[1]
		h = scp[2]
		scp = scp[0]


		for j in range(h):
			cl = []
			for i in range(w):
				cl.append(scp[i, j])
			h = ' '.join(map(str, cl))
			m = h.find(n)
			if m >= 0:
				m = len(h[0:m].split(" "))
				print "Signature found on %d, %d" % (m, j)
				#self.offset = (m, j-18)
				self.offset = (m+1, j+4)
				break
Esempio n. 21
0
def tats(image):
    image = image.convert('RGB')
    colours = util.get_dominant_colours(image, 9)
    colours = util.order_colours_by_brightness(colours)

    bg = random.choice(colours[:3])
    light = random.choice(colours[3:6])
    dark = random.choice(colours[6:])

    dist = math.sqrt(
        sum(map(lambda (a, b): math.pow(a - b, 2), zip(light, dark))))
    if dist < 100:
        light = util.modify_hls(light, l=lambda l: l + 100)

    light = util.modify_hls(light, s=lambda s: s + 100)
    dark = util.modify_hls(dark, s=lambda s: s + 100)

    layer = Image.open(
        os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/tats.png')
    layer.load()
    r, g, b, a = layer.split()
    layer = layer.convert('RGB')
    layer = ImageOps.grayscale(layer)
    layer = ImageOps.colorize(layer, tuple(dark), tuple(light))
    layer.putalpha(a)
    im = Image.new('RGB', layer.size, tuple(bg))
    im.paste(layer, mask=layer)
    return im
Esempio n. 22
0
def getSeatSix():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+530,yPad+60,xPad+593,yPad+76)))
    a = array(im.getcolors())
##    im.save(os.getcwd() + '\\SeatSixBubble.png', 'PNG')
    print 'table 6 bubble = %d' % a.sum()
    return a.sum()
Esempio n. 23
0
def ocr_cell(im, cells, x, y):
    """Return OCRed text from this cell"""
    fbase = "working/%d-%d" % (x, y)
    ftif = "%s.tif" % fbase
    ftxt = "%s.txt" % fbase
    cmd = "tesseract %s %s" % (ftif, fbase)
    # extract cell from whole image, grayscale (1-color channel), monochrome
    region = im.crop(cells[x][y])
    region = ImageOps.grayscale(region)
    region = region.point(lambda p: p > 200 and 255)
    # determine background color (most used color)
    histo = region.histogram()
    if histo[0] > histo[255]: bgcolor = 0
    else: bgcolor = 255
    # trim borders by finding top-left and bottom-right bg pixels
    pix = region.load()
    x1,y1 = 0,0
    x2,y2 = region.size
    x2,y2 = x2-1,y2-1
    while pix[x1,y1] != bgcolor:
        x1 += 1
        y1 += 1
    while pix[x2,y2] != bgcolor:
        x2 -= 1
        y2 -= 1
    # save as TIFF and extract text with Tesseract OCR
    trimmed = region.crop((x1,y1,x2,y2))
    trimmed.save(ftif, "TIFF")
    subprocess.call([cmd], shell=True, stderr=subprocess.PIPE)
    lines = [l.strip() for l in open(ftxt).readlines()]
    return lines[0]
Esempio n. 24
0
def grab():
	box = (X_PAD + 1, Y_PAD +1,X_PAD + 640, Y_PAD + 480)
	im = ImageOps.grayscale(ImageGrab.grab(box))
	a = array(im.getcolors())
	a = a.sum()
	print a
	return a
Esempio n. 25
0
    def __init__(self, player):
        self.board = Board()
        self.player = player
        sig = Image.open("sig.png")
        sig = ImageOps.grayscale(sig)
        sigp = sig.load()

        n = []
        for i in range(sig.size[0]):
            n.append(sigp[i, 0])

        # Assinatura em formato de string
        n = ' '.join(map(str, n))

        raw_input("Posicione a janela e pressione enter para comecar...")
        sleep(2)
        scp = self.screenCapture()

        w = scp[1]
        h = scp[2]
        scp = scp[0]

        for j in range(h):
            cl = []
            for i in range(w):
                cl.append(scp[i, j])
            h = ' '.join(map(str, cl))
            m = h.find(n)
            if m >= 0:
                m = len(h[0:m].split(" "))
                print
                "Signature found on %d, %d" % (m, j)
                # self.offset = (m, j-18)
                self.offset = (m + 1, j + 4)
                break
Esempio n. 26
0
    def addUniqueData(self, filename, inputType, normalized=False):
        import os
        if not os.path.isfile(filename):
            raise Exception("addUniqueData : \"" + filename + "\" is not a file")
        if inputType >= DataCategory.TRAIN and inputType <= DataCategory.TEST:
            im = Normalize(self.Size(), filename, offset=self.__offset)
            array = []
            import ImageOps
            if self.__grayScale:
                im = ImageOps.grayscale(im)
                if self.__negate:
                    im = ImageOps.invert(im)
                if normalized:
                   array = [float(x) / 255. for x in list(im.getdata())]
                else:
                   array = [x for x in list(im.getdata())]
            else:
                for p in list(im.getdata()):
#                    array.append(zip([float(x)/255. for x in p]))
                    for i in xrange(len(p)):
                        if normalized:
                            array.append(float(p[i]) / 255.)
                        else:
                            array.append(p[i])
                    array = [x for x in array]
            self.Inputs()[inputType].append(array)
            import string
            groundTruth = string.split(os.path.splitext(os.path.split(filename)[1])[0], '-')[0]
            self.Targets()[inputType].append(int(groundTruth))
        else:
            raise Exception("Incorrect DataCategory")
Esempio n. 27
0
def getSeatThree():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+227,yPad+60,xPad+290,yPad+76)))
    a = array(im.getcolors())
##    im.save(os.getcwd() + '\\SeatThreeBubble.png', 'PNG')
    print 'table 3 bubble = %d' % a.sum()
    return a.sum()
Esempio n. 28
0
def display_file(epd, file_name):
    """display centre of image then resized image"""

    image = Image.open(file_name)
    image = ImageOps.grayscale(image)

    # crop to the middle
    w,h = image.size
    x = w / 2 - epd.width / 2
    y = h / 2 - epd.height / 2

    cropped = image.crop((x, y, x + epd.width, y + epd.height))
    bw = cropped.convert("1", dither=Image.FLOYDSTEINBERG)

    epd.display(bw)
    epd.update()


    time.sleep(3) # delay in seconds

    rs = image.resize((epd.width, epd.height))
    bw = rs.convert("1", dither=Image.FLOYDSTEINBERG)

    epd.display(bw)
    epd.update()

    time.sleep(3) # delay in seconds
Esempio n. 29
0
def getSeatFour():
    im = ImageOps.grayscale(ImageGrab.grab
                            ((xPad+328,yPad+60,xPad+391,yPad+76)))
    a = array(im.getcolors())
##    im.save(os.getcwd() + '\\SeatFourBubble.png', 'PNG')
    print 'table 4 bubble = %d' % a.sum()
    return a.sum()
Esempio n. 30
0
def game_logic(screen, dt, player):
    global TRACES
    im = screen_grab(box=PLAYABLE_BOX)
    #return True
    
    #im = screen_grab(box=PLAYABLE_BOX)
    im_gray = ImageOps.grayscale(im)
    
    coords = get_coords()
    if coords[0] < 0 or coords[1] < 0:
        print "Mouse out"
        return False
    
    if im.getpixel(END_GAME_OK) == (232, 97, 1):
        return True
    if im.getpixel(GET_READY) == (244, 198, 0) or im.getpixel(START_BUTTON) == (217, 83, 14):
        return True
    


    diff_array = asarray(ImageChops.difference(im_gray,BACKGROUND_GRAY))
    #grayscale_array_to_pygame(screen, diff_array)

    bird, pipes = find_elements(diff_array)
    draw_game(screen, bird, pipes)
    player.see(dt, bird, pipes)
    pygame.draw.rect(screen, BLUE, [player.x - 3, player.y - 3, 6, 6])
    font = pygame.font.SysFont("monospace", 15)
    label = font.render("%d %d"%(player.speed_y, player.accel_y), 1, (255,255,0))
    screen.blit(label, (10, FLOOR_Y + 26))
    player.play()
    

    return True
Esempio n. 31
0
def image_file_features(infile, cl_options):
    im = Image.open(infile)

    hist_features = {}
    if cl_options.histogram:
        hist_features = array_to_features(im.histogram(), 'pixhist_')

    if cl_options.equalize:
        im = ImageOps.grayscale( ImageOps.equalize(im) )

    if cl_options.blur:
        im_blur = scipy.ndimage.gaussian_filter(im, sigma=cl_options.blur)
        im = Image.fromarray(numpy.uint8(im_blur)) # from numpy->Grayscale Image

    if cl_options.horiz_ema:
        # scale to be independent of image size ?????
        im_ema = horiz_exp_mov_avg(im, cl_options.horiz_ema)
        im = Image.fromarray(numpy.uint8(im_ema)) # from numpy->Grayscale Image

    if cl_options.thumb_size:
        thumb_size = (cl_options.thumb_size, cl_options.thumb_size)
        im.thumbnail(thumb_size, Image.ANTIALIAS)

    if cl_options.thumb_dir:
        basename = os.path.basename(infile).split('.')[0]
        thumb_file = cl_options.thumb_dir + '/' + basename + '.png'
        im.save(thumb_file, "png")

    pix_features = {}
    if cl_options.pixels:
        pix_values = im.getdata() # returns a 1-D/flattened sequence of pixel values
        pix_features = array_to_features(pix_values, 'pix_')

    return dict(pix_features.items() + hist_features.items()) 
Esempio n. 32
0
def grab():  #screenshots of the game area
    box = (x_padding + 1, y_padding + 1, x_padding + 1824, y_padding + 476)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    print a
    return a
Esempio n. 33
0
def geticonshape(shape, dim_horiz, dim_vert):
  iconimage = ''.join([shape, '_icon.png'])
  img = Image.open(iconimage)
  img = ImageOps.grayscale(img)
  img = ImageOps.autocontrast(img)
  img = img.resize((dim_horiz, dim_vert), Image.BILINEAR)
  return img
Esempio n. 34
0
def grayscale(image, amount=100):
    grayscaled = ImageOps.grayscale(image)
    if amount < 100:
        grayscaled = imtools.blend(image, grayscaled, amount / 100.0)
    if image.mode == "RGBA":
        grayscaled.putalpha(imtools.get_alpha(image))
    return grayscaled
Esempio n. 35
0
 def composeForFacebook(self,images):
     print("composing for facebook")
     strip = Image.new('RGB', (self.facebookLayout["width"], self.facebookLayout["width"]), (0,0,0)) 
     count=0
     dim=self.facebookLayout["photoDim"]
     positions={0:[5,5],1:[dim,5],2:[5,dim],3:[dim,dim]}
     #for inFile in glob.glob(os.path.join(imageDir, '*.JPG')):
     for img in images:
         if count>3:break
        # print("\t"+str(inFile))
         #img=Image.open(inFile)
         
         posX,posY=positions[count]
         bbox=img.getbbox()
         img=img.crop(((bbox[2]/2)-(bbox[3]/2),0,(bbox[2]/2)+(bbox[3]/2),bbox[3]))
         img=img.resize((dim-10,dim-10))
         #img = ImageOps.autocontrast(img, cutoff=2)
         if self.grey:
             img=ImageOps.grayscale(img)
             enh=ImageEnhance.Brightness(img)
             img=enh.enhance(0.8)
             enh=ImageEnhance.Contrast(img)
             img=enh.enhance(1.3)
         strip.paste(img,(posX,posY))
         count=count+1        
     overlay=self.facebookLayout["overlay"]
     strip.paste(overlay,None,overlay)
     #path=os.path.join(imageDir, 'facebookStrip.PNG')
     #path=self.saveImageToOutgoing(strip,"facebook")
     #dateString=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M')
     #path=os.path.join(self.outgoingPath,dateString+'_facebook.PNG')
     #strip.save(path, 'PNG')
     print("\n")
     return [strip,"facebook"]
def transformer(image, seuil, ampl_theta=1):
    # Prend en paramètres une image pré-traitée (une image don't il ne reste que les contours) et un seuil qui est une entier naturel compris entre 0 et 255
    longueur, hauteur = image.size
    image = ImageOps.grayscale(image)
    pixels = image.load() 
    theta_m = math.atan(hauteur/float(longueur))
    print theta_m
    dim_espace_hough = (180,int(longueur*math.cos(theta_m)+hauteur*math.sin(theta_m)))
    image_hough = Image.new("L", (dim_espace_hough[0],dim_espace_hough[1]))
    pix = image_hough.load()
    za = ImageDraw.Draw(image_hough)
    print dim_espace_hough
    for x in range(longueur):
        for y in range(hauteur):
            if pixels[(x,y)] > seuil:
                for theta in range(dim_espace_hough[0]):
                    rho = x * math.cos(math.radians(theta))+ y * math.sin(math.radians(theta))
                    # print rho
                    if pix[theta,(int(rho)%dim_espace_hough[1])] == 255:
                        pass
                    else:
                        za.point((theta, (int(rho)%dim_espace_hough[1])), fill = 100 + pix[theta,int(rho)%dim_espace_hough[1]])
                    pix = image_hough.load()
    return image_hough
    """
Esempio n. 37
0
def grayscale(image, amount=100):
    grayscaled = ImageOps.grayscale(image)
    if amount < 100:
        grayscaled = imtools.blend(image, grayscaled, amount / 100.0)
    if image.mode == 'RGBA':
        grayscaled.putalpha(imtools.get_alpha(image))
    return grayscaled
def grab():
    box = (x_pad + 1,y_pad+1,x_pad+640,y_pad+480)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    print a
    return a
Esempio n. 39
0
def grab():
    im = ImageOps.grayscale(
        ImageGrab.grab(bbox=(x_pad + 1, y_pad + 1, x_pad + 641, y_pad + 480)))
    a = array(im.getcolors())
    a = a.sum()
    print a
    return a
Esempio n. 40
0
 def _capture_interesting_frame(self, pad, buffer):
     """
     this is the buffer probe which processes every frame that is being
     played by the capture pipeline. since the first frame is not random, we
     skip this frame by setting the self.first_analyze flag.
     if the current frame is found intersting we save it. if not we decrease
     self.tries to limit the number of tries
     """
     if not self.first_analyze:
         #get current buffer's capabilities
         caps = buffer.get_caps ()
         #we are interested in it's dimension
         height, width = caps[0]['height'], caps[0]['width']
         #using PIL we grab the image in raw RGB mode from the buffer data
         im = Image.frombuffer('RGB', (width, height), buffer.data,'raw', 'RGB', 0, 1)
         #here we check the standard variance of a grayscale version of the
         #current frame against the BORING_IMAGE_VARIANCE
         if ImageStat.Stat(ImageOps.grayscale(im)).var[0] > \
             BORING_IMAGE_VARIANCE:
             #success! save our interesting image
             self.image = im
         else:
             #the image is just useless... retry...
             self.tries -= 1
     else:
         self.first_analyze = False
     return True
    def processImage(self, im):
        im = im.resize((320, 240))
        im = ImageOps.grayscale(im)
        im = im.filter(ImageFilter.BLUR)

        if not self.prevImage:
            self.prevImage = im
            return

        imd = ImageChops.difference(im, self.prevImage)

        def mappoint(pix):
            if pix > 20:
                return 255
            else:
                return 0

        imbw = imd.point(mappoint)

        hist = imbw.histogram()
        percentWhitePix = hist[-1] / (hist[0] + hist[-1])
        motionDetected = (percentWhitePix > self.DETECTION_THRESHOLD)
        self.factory.motionStateMachine.step(motionDetected)
        motionSustained = self.factory.motionStateMachine.inSustainedMotion()

        print '%d %d' % (motionDetected, motionSustained)
        sys.stdout.flush()

        self.prevImage = im
Esempio n. 42
0
def ImageListFile2Array(filename):
    patch_size = (8,8)
    stride_size = (6,6)
    imgArray = None
    image_list = open(filename)
    for image_file in image_list:
        #delete the enter space
        image_file =  image_file.rstrip()
        print image_file

        #read images
        im = Image.open(image_file)

        #convert to grayscal
        gray_im = ImageOps.grayscale(im)

        w = gray_im.size[0] - patch_size[0]
        h = gray_im.size[1] - patch_size[1]
        y = 0
        while y <= h:
            x = 0
            while x <= w:
                box = (x,y,x+patch_size[0],y+patch_size[1])
                crop_im = gray_im.crop(box)

                data = np.asarray(crop_im)
                data = data.reshape(1,data.size)
                if imgArray is None:
                    imgArray = data
                else:
                    imgArray = np.vstack((imgArray, data))
                x+=stride_size[0]
            y+=stride_size[1]
    return imgArray
Esempio n. 43
0
def CalcLBP(img, radius=1, neighborPixels=8):
	#Function to calculate local binary pattern of an image 
	#pass in a img
	#returns an lbp list
	xmax = img.size[0]
	ymax = img.size[1] 
	#convert image to grayscale
	grayimage = ImageOps.grayscale(img)
	#make a copy to return
	returnimage = Image.new("L", (xmax,ymax))
	uniform_hist = numpy.zeros(256, int)
	#print "uniform_hist = ", uniform_hist
	#print "size = ", uniform_hist.ndim
	meanRGB = 0
	imagearray = grayimage.load()
	neighborRGB = numpy.empty([8], dtype=int)
	center = (5,5)
	radius = 1
	angleStep = 360 / neighborPixels
 	lbp_list = []
	for y in range(1, ymax-1, 1):
		for x in range(1, xmax-1, 1):
			centerRGB = imagearray[x, y]
			#print 'Center Pixel = ', x, y
			#meanRGB = centerRGB
			index = 0
			lbp = 0
			for ang in range(0, 359, angleStep):
				xx = round(x + radius * math.cos(math.radians(ang)))
				yy = round(y + radius * math.sin(math.radians(ang)))
				neighborRGB[index] = imagearray[xx,yy]
				#print 'pixel = ',xx, yy, 'neighbor# = ', index, 'center val = ', centerRGB, 'current pixel val = ', neighborRGB[index]
				if imagearray[xx,yy] >= centerRGB:
					lbp = lbp + (2**index)
				index = index + 1
			#print "LBP = ", lbp
			#lbp = 0
			#for i in range(neighborPixels):
			#comparing against mean adds a sec vs comparing against center pixel
				#if neighborRGB[i] >= meanRGB:
			#	if neighborRGB[i] >= centerRGB:
			#		lbp = lbp + (2**i)
			#comparing against mean adds a sec vs comparing against center pixel
			#meanRGB= centerRGB + neighborRGB.sum()
			#meanRGB = meanRGB / (neighbors+1)
			#compute Improved local binary pattern (center pixel vs the mean of neighbors)
			#putpixel adds 1 second vs storing to array
			uniform = is_uniformLBP( digitlist(lbp, numdigits=8, base=2))
			#print "LBP = ", lbp, " bits = ", decimal2binary(lbp), digitlist(lbp, numdigits=8, base=2), " is_uniformLBP(digits) = ", uniform
			get_uniform_variations(lbp)
			lbp_list.append(lbp)
			#time.sleep(1)
			returnimage.putpixel((x,y), lbp)
	#print "LBP LIST = ", lbp_list, "  count = ", len(lbp_list)
	LBP_Section_Histogram = get_LBP_uniform_histogram(lbp_list)
	#print 'LBP fingerprint for that section = ', LBP_Section_Histogram
	#print returnimage.histogram()
	#return returnimage
	return LBP_Section_Histogram
Esempio n. 44
0
def triangles(original, n=30, size=150, width=700,
              height=700, min_distance=70, opacity=220):
    original = original.convert('RGB')
    colours = util.get_dominant_colours(original, 8)
    colours_ordered = util.order_colours_by_brightness(colours)
    brightest_colour = list(random.choice(colours_ordered[:3]))
    brightest_colour.append(0)

    new = Image.new('RGBA', (width, height), tuple(brightest_colour))

    draw = aggdraw.Draw(new)

    centres = []

    def is_too_close(x, y):
        for centre in centres:
            if math.sqrt(math.pow(centre[0] - x, 2) + 
                         math.pow(centre[1] - y, 2)) < min_distance:
                return True
        return False

    for i in xrange(n):

        colour = tuple(colours[int(random.randint(0, len(colours) - 1))])
        x = random.randint(size / 2, width - 1 - size / 2)
        y = random.randint(size / 2, height - 1 - size / 2)

        if is_too_close(x, y):
            continue

        centres.append((x, y))

        brush = aggdraw.Brush(colour, opacity)
        points = get_triangle_path(x, y, size / 2, size / 2)
        draw.polygon(points, None, brush)
    draw.flush()

    brightest_colour = brightest_colour[0:3]

    texture = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' +
                         'assets/airbrush.png')
    texture = texture.convert('RGBA')
    r, g, b, a = texture.split()
    texture = ImageOps.grayscale(texture)
    texture = ImageOps.colorize(texture, (0, 0, 0), tuple(brightest_colour))
    texture = texture.convert('RGBA')
    texture.putalpha(a)

    r, g, b, a = new.split()

    texture = texture.crop((0, 0, width, height))
    texture_layer = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    texture_layer.paste(texture, mask=new)
    new.paste(texture_layer, mask=texture_layer)

    im = Image.new('RGB', (width, height), tuple(brightest_colour))
    im.paste(new, mask=a)

    return im
Esempio n. 45
0
def get_seat_six():
    box = (x_pad + 1 + 636, y_pad + 74, x_pad + 710, y_pad + 90)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    # im.save(os.getcwd() + '\\seat_six__' + str(int(time.time())) + '.png', 'PNG')
    a = array(im.getcolors())
    a = a.sum()
    print(a)
    return a
Esempio n. 46
0
def get_seat_two():
    im = ImageOps.grayscale(
        ImageGrab.grab(bbox=(x_pad + 129, y_pad + 61, x_pad + 129 + 59,
                             y_pad + 61 + 15)))
    a = array(im.getcolors())
    a = a.sum()
    ##im.save(os.getcwd() + '\\seat_two__' + str(int(time.time())) + '.png', 'PNG')
    return a
Esempio n. 47
0
def get_seat_one():
    box = (x_pad + 29, y_pad + 72, x_pad + 103, y_pad + 89)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    # im.save(os.getcwd() + '\\seat_one__' + str(int(time.time())) + '.png', 'PNG')
    a = array(im.getcolors())
    a = a.sum()
    print(a)
    return a
Esempio n. 48
0
def grayscale_grab():
    box = (x_pad, y_pad, x_pad + 640, y_pad + 480)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    print a
    # im.save(os.getcwd() + '\\Snap__' + str(int(time.time())) + '.png', 'PNG')
    return a
Esempio n. 49
0
def getGrayscale(cords):
    global inc
    box = (cords[0][0]+x_pad, cords[0][1] + y_pad, cords[1][0] + x_pad, cords[1][1] + y_pad)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    #im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) + '.png', 'PNG')
    a = array(im.getcolors())
    a = a.sum()
    return a
Esempio n. 50
0
def continue_box():
    box = (c+112,b+70,c+455,b+342)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    print a
    ##im.save(os.getcwd() + '\\seat_six__' + str(int(time.time())) + '.png', 'PNG')
    return a
Esempio n. 51
0
def grab():
    box = (x_pad + 70, y_pad + 150, x_pad + 250, y_pad + 151)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    #im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) + '.png', 'PNG')
    b = array(im.getcolors())
    b = b.sum()
    print b
    return b
def get_slot3():
    box = (748, 397, 762, 402)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    print 'T1: ' + str(a)
    im.save(os.getcwd() + '\\slot_three__' + str(int(time.time())) + '.png', 'PNG')   
    return a
Esempio n. 53
0
def get_seat_six():
    box = (c+474,b+55,c+474+55,b+55+12)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    ##print "seat 6", a
    im.save(os.getcwd() + '\\seat_six__' + str(int(time.time())) + '.png', 'PNG')
    return a
def get_slot4():
    box = (747, 371, 762, 376)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    print 'T2: ' + str(a)
    im.save(os.getcwd() + '\\slot_four__' + str(int(time.time())) + '.png', 'PNG')   
    return a
Esempio n. 55
0
def get_seat_six():
	box = (X_PAD + 531, Y_PAD + 61, X_PAD + 531+63, Y_PAD + 61 + 16)
	im = ImageOps.grayscale(ImageGrab.grab(box))
	a = array(im.getcolors())
	a = a.sum()
	#print a
	#im.save(CWD + "\\seat_six__" + str(int(time.time())) +	'.png', "PNG")	
	return a	
Esempio n. 56
0
def getSeatSix():
    box = (x_pad + 530, y_pad + 63, x_pad + 530 + 64, y_pad + 63 + 11)
    im = ImageOps.grayscale(ImageGrab.grab(box))
    a = array(im.getcolors())
    a = a.sum()
    print a
    im.save(os.getcwd() + '\\seat_six__' + str(int(time.time())) + '.png',
            'PNG')
    return a
Esempio n. 57
0
def build_mat_from_grayscale_image(path):
    img = Image.open(str(path))
    img = ImageOps.grayscale(img)
    imgData = img.getdata()
    imgTab = numpy.array(imgData)
    w, h = img.size
    imgMat = numpy.reshape(imgTab, (h, w))

    return imgMat
Esempio n. 58
0
def get_all_grayscale_sums(chat_bubble_coordinates):
    seat_color_sums = [0, 0, 0, 0, 0, 0]
    for seat in range(0, 6):
        image = ImageOps.grayscale(
            ImageGrab.grab(chat_bubble_coordinates[seat]))
        color_sum = array(image.getcolors())
        color_sum = color_sum.sum()
        seat_color_sums[seat] = color_sum
    return seat_color_sums
Esempio n. 59
0
 def _get_image(self,p):
     """
     If necessary as indicated by the parameters, get a new image,
     assign it to self._image and return True.  If no new image is
     needed, return False.
     """
     if p.filename!=self.last_filename or self._image is None:
         self.last_filename=p.filename
         self._image = ImageOps.grayscale(Image.open(p.filename))
     return self._image