def color_tiles(img): size = img.size small_img = img.resize((size[0]/2, size[1]/2), BILINEAR) bw_img = small_img.convert('1', dither=False) gray_img = bw_img.convert('L') result = Image.new('RGB', size) tile1 = ImageOps.colorize(gray_img, 'green', 'red') tile2 = ImageOps.colorize(gray_img, 'purple', 'yellow') tile3 = ImageOps.colorize(gray_img, 'yellow', 'brown') tile4 = ImageOps.colorize(gray_img, 'red', 'cyan') result.paste(tile1, (0, 0)) result.paste(tile2, (size[0]/2, 0)) result.paste(tile3, (0, size[1]/2)) result.paste(tile4, (size[0]/2, size[1]/2)) return result
def color_tiles(img): size = img.size small_img = img.resize((size[0] / 2, size[1] / 2), BILINEAR) bw_img = small_img.convert('1', dither=False) gray_img = bw_img.convert('L') result = Image.new('RGB', size) tile1 = ImageOps.colorize(gray_img, 'green', 'red') tile2 = ImageOps.colorize(gray_img, 'purple', 'yellow') tile3 = ImageOps.colorize(gray_img, 'yellow', 'brown') tile4 = ImageOps.colorize(gray_img, 'red', 'cyan') result.paste(tile1, (0, 0)) result.paste(tile2, (size[0] / 2, 0)) result.paste(tile3, (0, size[1] / 2)) result.paste(tile4, (size[0] / 2, size[1] / 2)) return result
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
def put_contour(image, size=1, offset=0, contour_color=0, fill_color=0, opacity=100, include_image=True): if not has_transparency(image): return put_border(image, size, offset, contour_color, fill_color, opacity, include_image) image = image.convert('RGBA') mask = imtools.get_alpha(image) w, h = image.size outer_mask = mask.resize( (w + 2 * (size + offset), h + 2 * (size + offset)), Image.ANTIALIAS) inner_mask = mask.resize((w + 2 * offset, h + 2 * offset), Image.ANTIALIAS) inner_mask = ImageOps.expand(inner_mask, border=size, fill=0) paste(outer_mask, (255 * opacity) / 100, mask=inner_mask) if include_image: image = ImageOps.expand(image, border=size + offset, fill=(0, 0, 0, 0)) mask = ImageOps.expand(mask, border=size + offset, fill=0) paste(outer_mask, 255, mask=mask) contour = ImageOps.colorize(outer_mask, (255, 255, 255), contour_color) paste(contour, fill_color, mask=inner_mask) if include_image: paste(contour, image, mask=image) contour.putalpha(outer_mask) return contour
def put_contour(image, size=1, offset=0, contour_color=0, fill_color=0, opacity=100, include_image=True): if not has_transparency(image): return put_border( image, size, offset, contour_color, fill_color, opacity, include_image) image = image.convert('RGBA') mask = imtools.get_alpha(image) w, h = image.size outer_mask = mask.resize( (w + 2 * (size + offset), h + 2 * (size + offset)), Image.ANTIALIAS) inner_mask = mask.resize( (w + 2 * offset, h + 2 * offset), Image.ANTIALIAS) inner_mask = ImageOps.expand(inner_mask, border=size, fill=0) paste(outer_mask, (255 * opacity) / 100, mask=inner_mask) if include_image: image = ImageOps.expand(image, border=size + offset, fill=(0, 0, 0, 0)) mask = ImageOps.expand(mask, border=size + offset, fill=0) paste(outer_mask, 255, mask=mask) contour = ImageOps.colorize(outer_mask, (255, 255, 255), contour_color) paste(contour, fill_color, mask=inner_mask) if include_image: paste(contour, image, mask=image) contour.putalpha(outer_mask) return contour
def rotate_and_draw_date(img, x_position, row_y, current_day, color): font = ImageFont.truetype("arial.ttf", 14) txt = Image.new('L', (100, 25)) d = ImageDraw.Draw(txt) d.text((0, 0), current_day.__str__(), font=font, fill=255) w = txt.rotate(-90, expand=1) img.paste(ImageOps.colorize(w, (0, 0, 0), color), (x_position, row_y), w)
def run(self): ''' Limpia las imagenes empleando PIL ''' # notificar el inicio de operaciones self.notificador.inicio_operacion.emit() import Image, ImageChops, ImageOps, ImageEnhance for i in range(len(self.imagenesIn)): im = Image.open(self.imagenesIn[i]) if im: im1 = ImageChops.invert(im) im = ImageChops.subtract(im1, im) im = im.convert('L') im = ImageChops.invert(im) im = ImageEnhance.Brightness(im).enhance(2.0) im = ImageOps.colorize(im, (0, 0, 0), (255, 255, 255)) im.save(self.imagenesOut[i]) else: self.notificador.error.emit('Error al procesar la imagen: ' + self.imagenesIn[i]) return # notificar a la aplicacion el resultado de la operacion self.notificador.correcto.emit(self.plugin.nombre()) # notificar el fin de operaciones self.notificador.fin_operacion.emit() return
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
def cf_image(cfs, coords, width=None, height=None, pos=(0,0), size=26, border=5, bg=(0,0,0), colmap=None): """ Returns a PIL image showing the selected connection fields (CFS) as supplied by extract_CFs. Does not support non-square CF shapes. 'cfs' is an ndarray of N dstacked cfs, each of shape (X,X): (X,X,N) 'coords' is an ndarray of N coordinates: (N,2) 'width' and 'height' are either None (full) of integer grid sizes 'pos' is the starting position of the block, (x,y) 'size' and 'border' are the cf image size and the border size in pixels. 'colmap' is an RGB array shape (N,M,3) with values between 0.0 and 1.0. """ normalize = lambda arr: (arr - arr.min()) / (arr.max() - arr.min()) cf_im = lambda cf, size: greyscale(normalize(cf)).resize((size,size), Image.NEAREST) (posx, posy) = pos (d1,d2) = zip(*coords) density = len(set(d1)) assert density == len(set(d2)), "Not implemented for non-square sets" height = density if height is None else height width = density if width is None else width assert height>0 and width>0, "Height and width must be None or greater than zero" assert posx+width <= density, "X position and width greater than density" assert posy+height <= density, "Y position and width greater than density" # Functions mapping original coordinates onto consecutive grid indices fst_map = dict(((ind,i) for (i,ind) in enumerate(sorted(set(d1))))) snd_map = dict(((ind,i) for (i,ind) in enumerate(sorted(set(d2))))) # Generating a dictionary from the grid coordinates to the CF index mapped_coords = [(fst_map[fst],snd_map[snd]) for [fst,snd] in coords] indexed_coords = dict((coord,i) for (i, coord) in enumerate(mapped_coords)) # Initialising the image imwidth = width*size+(width-1)*border imheight = height*size+(height-1)*border cf_block = Image.new('RGB', (imwidth, imheight), bg) # Building image row by row, top to bottom. for yind in range(height): for xind in range(width): # Swapped coordinate system cf_ind = indexed_coords[(yind+posy, xind+posx)] # Get color from the color map if available if colmap is not None: crd1, crd2 = coords[cf_ind] r,g,b = colmap[crd1, crd2, :] color = (r*255,g*255,b*255) else: color = (255, 255, 255) cf = cfs[:,:,cf_ind] (cf_dim1, cf_dim2) = cf.shape assert cf_dim1 == cf_dim2, "Only supports square CFs." cf_image = ImageOps.colorize(cf_im(cf, size), (0, 0, 0, 0), color) xoffset = xind*border yoffset = yind*border paste_coord = (xoffset+xind*size, yoffset+yind*size) cf_block.paste(cf_image, paste_coord) return cf_block
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
def changeColor(self, image, mask, color1, color2=(0, 0, 0, 0)): """Take an image and change its color, color is a tuple (R,G,B)""" print 'changing color of image to (%i, %i, %i, %i)' % color1 self.imageAttr(image) image = ImageOps.colorize(image, color1, color2) xsize, ysize = image.size blank = Image.open('%s%i.png' % (self.templatePath, xsize)) mask = Image.open(mask) image = Image.composite(image, blank, mask) return image
def colorize_pixbuf (pixbuf, black, white): i = pixbuf_to_pil(pixbuf) i.save('/tmp/test_pb.png','png') irgb = Image.open('/tmp/test_pb.png') irgb.save('/tmp/test_rgb.png','png') ig = irgb.convert('L') ig.save('/tmp/test_L.png','png') icol = ImageOps.colorize(ig,black,white) icol.save('/tmp/test.png','png') return pil_to_pixbuf(icol)
def colorize(image, black, white, amount=100): """Apply a filter - amount: 0-1""" if image.mode != 'L': im = image.convert('L') else: im = image colorized = ImageOps.colorize(im, black, white) if image.mode == 'RGBA': colorized = colorized.convert('RGBA') colorized.putalpha(imtools.get_alpha(image)) if amount < 100: return imtools.blend(image, colorized, amount / 100.0) return colorized
def ombre(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 12) colours = util.order_colours_by_brightness(colours) light = random.choice(colours[:3]) dark = random.choice(colours[-3:]) layer = Image.open( os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/ombre.jpg') layer = util.random_crop(layer, util.WIDTH, util.HEIGHT) layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, dark, light) return layer
def ombre(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 12) colours = util.order_colours_by_brightness(colours) light = random.choice(colours[:3]) dark = random.choice(colours[-3:]) layer = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/ombre.jpg') layer = util.random_crop(layer, util.WIDTH, util.HEIGHT) layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, dark, light) return layer
def mkImage (f, s, r): img = Image.new("RGB", (28,28), "#FFFFFF"); #draw = ImageDraw.Draw(image); font = ImageFont.truetype(f, 32); t = Image.new('L', (100,100)); d = ImageDraw.Draw(t); size = d.textsize(s, font=font); d.text((50,55), " "+s+" ", font=font, fill=255); t = t.rotate(r, expand=1); xsum = 0; ysum = 0; minx = 100; miny = 100; maxx = 0; maxy = 0; pixcount = 0; for i in range (0,t.size[0]): for j in range (0, t.size[1]): if (t.getpixel((i,j)) > 200): if ( minx > i ): minx = i; if ( miny > j ): miny = j; if ( maxx < i ): maxx = i; if ( maxy < j ): maxy = j; t.putpixel((i,j), 255); xsum += i; ysum += j; pixcount += 1; # xavr = xsum / (pixcount); # yavr = ysum / (pixcount); midx = (minx + maxx)/2; midy = (miny + maxy)/2; # if ( pixcount == 0 ): # print "pixcount == 0 at ", f, s; #d.text((14-size[0]/2,14-size[1]/2), s, font=font, fill=255); #img.paste(t, (0,0,t.size[0],t.size[1])); img.paste(ImageOps.colorize(t,(0,0,0),(0,0,0)), (14-midx,14-midy),t); return img;
def render(self,im): im2 = im.copy() if self.grayscale: im2 = ImageOps.grayscale(im2) im2 = ImageOps.colorize(im2,"black","white") if self.posterized: im2 = ImageOps.autocontrast(im2) im2 = ImageOps.posterize(im2,self.posterize_bits) im2 = ImageOps.autocontrast(im2) if self.gridlines > 0: im2 = draw_grid(im2,self.gridlines) data = im2.tostring() surface = pygame.image.fromstring(data, im2.size, im2.mode) screen.blit(surface,(0,0)) pygame.display.flip()
def process_bmp ( Data): Size = [0,0] Size[0] = ord(Data[0]) | (ord(Data[1]) << 8) Size[1] = ord(Data[2]) | (ord(Data[3]) << 8) Im = Image.fromstring( "1", (Size[1], Size[0]), Data[4:], "raw", "1;IR", 0, 1) Im = Im.rotate(90).transpose(Image.FLIP_TOP_BOTTOM).convert('L') Im = ImageOps.colorize( Im, LCD_CHAR_COLOR, LCD_BACKLIGHT_COLOR) Size = (Im.size[0] + BORD_W*2, Im.size[1] + BORD_W*2) # Add space for border newIm = Image.new( 'RGBA', Size) newIm.paste( Im, (1,1)) del Im Draw = ImageDraw.Draw(newIm) Draw.rectangle([(0,0), (Size[0] - 1, Size[1] - 1)], outline = BORD_COLOR) del Draw return newIm
def load_images(self): self.puff_images = {} for color in self.colors: p_color = ui.parse_color(color) self.puff_images[p_color] = [] for i in range(25): with io.BytesIO( ui.Image(self.puff_image_name + str(i).zfill(2)).to_png()) as fp: orig_puff = pilImage.open(fp) gray_img = orig_puff.convert('L') color_puff = ImageOps.colorize(gray_img, 'black', color) with io.BytesIO() as fp2: color_puff.save(fp2, 'PNG') self.puff_images[p_color].append( ui.Image.from_data(fp2.getvalue()))
def bokeh(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 8) colours = util.order_colours_by_brightness(colours)[2:7] colour = random.choice(colours) colour = util.modify_hsv(colour, s=lambda s: 255, v=lambda v: 255) light = (255, 244, 180) layer = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/bokeh.png') layer = util.random_crop(layer, util.WIDTH, util.HEIGHT) r, g, b, a = layer.split() layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, colour, light) layer.putalpha(a) im = Image.new('RGB', layer.size) im.paste(layer, (0, 0), layer) return im
def plaid(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 12) colours = util.order_colours_by_brightness(colours) indices = sorted(random.sample(range(len(colours)), 3)) colours = [colours[i] for i in indices] light, bg, dark = map(tuple, colours) layer = Image.open( os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/plaid.png') layer.load() r, g, b, a = layer.split() layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, dark, light) layer.putalpha(a) im = Image.new('RGB', layer.size, bg) im.paste(layer, mask=layer) return im
def bokeh(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 8) colours = util.order_colours_by_brightness(colours)[2:7] colour = random.choice(colours) colour = util.modify_hsv(colour, s=lambda s: 255, v=lambda v: 255) light = (255, 244, 180) layer = Image.open( os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/bokeh.png') layer = util.random_crop(layer, util.WIDTH, util.HEIGHT) r, g, b, a = layer.split() layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, colour, light) layer.putalpha(a) im = Image.new('RGB', layer.size) im.paste(layer, (0, 0), layer) return im
def draw(**kw): shape_size = 50, 90 space = shape_size[0]//3 margin = 10 card = Image.new( 'RGB', ((shape_size[0]*3)+((margin+space)*2), shape_size[1] + (margin * 2) ), 'white' ) if not os.path.isfile('shapes.png') \ or Image.open('shapes.png').size != (shape_size[0]*3, shape_size[1]*3): #print "regenerating shapes.png... please stand by" create('shapes.png', shape_size) try: number = Card.numbers.index(kw['number']) + 1 x1 = Card.shades.index(kw['shade']) * shape_size[0] x2 = x1 + shape_size[0] y1 = Card.shapes.index(kw['shape']) * shape_size[1] y2 = y1 + shape_size[1] shapes = Image.open('shapes.png') shape = shapes.crop( (x1,y1,x2,y2) ) im = Image.new( 'L', (number*(shape_size[0]+space)-space, shape_size[1]), 'white' ) for n in xrange(number): a = (shape_size[0]+space) * n b = a + shape_size[0] box = (a, 0, b, shape_size[1]) im.paste(shape, box) im = ImageOps.colorize(im, kw['color'], 'white') card.paste(im, center(im, card.size)) except Exception as e: draw = ImageDraw.Draw(card) error = traceback.format_exc() attributes = ' '.join(kw.values()) for n, errLine in enumerate([attributes] + error.split('\n')): draw.text((0,15*n), errLine, fill='black') #card.show() ret = cStringIO.StringIO() card.save(ret, 'PNG') return ret
def plaid(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 12) colours = util.order_colours_by_brightness(colours) indices = sorted(random.sample(range(len(colours)), 3)) colours = [colours[i] for i in indices] light, bg, dark = map(tuple, colours) layer = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/plaid.png') layer.load() r, g, b, a = layer.split() layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, dark, light) layer.putalpha(a) im = Image.new('RGB', layer.size, bg) im.paste(layer, mask=layer) return im
def topics2image2(ar, zoom = 1): square_size = int(math.sqrt(len(ar[0]))) topics = Image.new("L", ((square_size*zoom+5)* len(ar), square_size*zoom+10),200) imzoom = numpy.ones((zoom,zoom), numpy.uint8) maxval = numpy.ones(square_size) for topic in range(len(ar)): pixels = numpy.zeros((square_size,square_size), numpy.uint8) for i in range(square_size): pixels[i,:] = map(lambda x:255*x, ar[topic][i*square_size:(i+1)*square_size ]) #print pixels pixels = numpy.kron(pixels, imzoom) pixels = (255 - pixels) img = Image.fromarray(pixels,"L")#.convert("RGB") # img = ImageOps.convert(img) img = ImageOps.autocontrast(img) img = ImageOps.colorize(img, (0,0,0), (255,255,255)) topics.paste(img, (1+(square_size*zoom+5)*topic, 5)) return topics
def leaves(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 8) light, dark = [colours[i] for i in random.sample(range(len(colours)), 2)] layer = Image.open( os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/leaves.png') layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, dark, light) width, height = layer.size # shift half of the image horizontally left = layer.crop((0, 0, width / 2, height)) right = layer.crop((width / 2, 0, width, height)) new = Image.new('RGB', (width, height)) new.paste(left, (width / 2, 0)) new.paste(right, (0, 0)) return new
def leaves(image): image = image.convert('RGB') colours = util.get_dominant_colours(image, 8) light, dark = [colours[i] for i in random.sample(range(len(colours)), 2)] layer = Image.open(os.path.dirname(os.path.abspath(__file__)) + '/' + 'assets/leaves.png') layer = layer.convert('RGB') layer = ImageOps.grayscale(layer) layer = ImageOps.colorize(layer, dark, light) width, height = layer.size # shift half of the image horizontally left = layer.crop((0, 0, width / 2, height)) right = layer.crop((width / 2, 0, width, height)) new = Image.new('RGB', (width, height)) new.paste(left, (width / 2, 0)) new.paste(right, (0, 0)) return new
def topics2image2(ar, zoom=1): square_size = int(math.sqrt(len(ar[0]))) topics = Image.new( "L", ((square_size * zoom + 5) * len(ar), square_size * zoom + 10), 200) imzoom = numpy.ones((zoom, zoom), numpy.uint8) maxval = numpy.ones(square_size) for topic in range(len(ar)): pixels = numpy.zeros((square_size, square_size), numpy.uint8) for i in range(square_size): pixels[i, :] = map( lambda x: 255 * x, ar[topic][i * square_size:(i + 1) * square_size]) #print pixels pixels = numpy.kron(pixels, imzoom) pixels = (255 - pixels) img = Image.fromarray(pixels, "L") #.convert("RGB") # img = ImageOps.convert(img) img = ImageOps.autocontrast(img) img = ImageOps.colorize(img, (0, 0, 0), (255, 255, 255)) topics.paste(img, (1 + (square_size * zoom + 5) * topic, 5)) return topics
def makecolourediconset(shape, icon_colours, bg): coloured_images = [] for col in icon_colours: coloured_images.append(ImageOps.colorize(shape, col, bg)) coloured_images.append(ImageOps.colorize(shape, bg, bg)) return coloured_images
def mkImage (f, s, r): img = Image.new("RGB", (28,28), "#FFFFFF"); #draw = ImageDraw.Draw(image); minx = 100; miny = 100; maxx = 0; maxy = 0; t = Image.new('L', (100,100)); for fontsize in range(1,9): font = ImageFont.truetype(f, 16+fontsize*5); t = Image.new('L', (500,500)); d = ImageDraw.Draw(t); size = d.textsize(s, font=font); d.text((50,50), " "+s+" ", font=font, fill=255); t = t.rotate(r, expand=1); #xsum = 0; #ysum = 0; minx = 100000; miny = 100000; maxx = 0; maxy = 0; #pixcount = 0; for i in range (0,t.size[0]): for j in range (0, t.size[1]): if (t.getpixel((i,j)) > 100): if ( minx > i ): minx = i; if ( miny > j ): miny = j; if ( maxx < i ): maxx = i; if ( maxy < j ): maxy = j; t.putpixel((i,j), 255); #xsum += i; #ysum += j; #pixcount += 1; xwidth = maxx-minx; ywidth = maxy-miny; # print minx, maxx, miny, maxy if ( xwidth > 18 and xwidth < 28): break; if ( ywidth > 18 and ywidth < 28): break; # xavr = xsum / (pixcount); # yavr = ysum / (pixcount); midx = (minx + maxx)/2; midy = (miny + maxy)/2; print minx, maxx, miny, maxy, midx, midy # if ( pixcount == 0 ): # print "pixcount == 0 at ", f, s; #d.text((14-size[0]/2,14-size[1]/2), s, font=font, fill=255); #img.paste(t, (0,0,t.size[0],t.size[1])); img.paste(ImageOps.colorize(t,(0,0,0),(0,0,0)), (14-midx,14-midy),t); return img;
def vdiff(im0, im1): im0 = ImageOps.colorize( im0.convert('L'), (255, 0, 0), (255, 255, 255)) im1 = ImageOps.colorize( im1.convert('L'), (0, 255, 0), (255, 255, 255)) ImageChops.multiply(im0, im1).show()
def counting(c_std, a_std, imageFile): image_list = [imageFile] c_std = float(c_std) if image_list[0][-3:] == 'tif': for f, filename in enumerate(image_list): subprocess.call(["convert", filename, filename + '.png']) image_list[f] = filename + '.png' output_filename_hash = (datetime.datetime.now().minute * 60 + datetime.datetime.now().second) images = [ scipy.misc.imread(filename).astype(np.uint16) for filename in image_list ] #correlation_matrix = np.array([[-1, -1, -1, -1, -1], # [-1, -1, -1, -1, -1], # [-1, -1, 24, -1, -1], # [-1, -1, -1, -1, -1], # [-1, -1, -1, -1, -1]]) correlation_matrix = np.array([[-5935, -5935, -5935, -5935, -5935], [-5935, 8027, 8027, 8027, -5935], [-5935, 8027, 30742, 8027, -5935], [-5935, 8027, 8027, 8027, -5935], [-5935, -5935, -5935, -5935, -5935]]) median_diameter = 5 local_max = 3 #c_std = 1 processed_images = [np.copy(image).astype(np.int64) for image in images] processed_images = \ [np.subtract(image, np.minimum(spf.median_filter(image, median_diameter), image)) for image in images] processed_images = \ [np.maximum(scipy.signal.correlate(image, correlation_matrix, mode='same'), np.zeros_like(image)).astype(np.int64) for image in processed_images] thresholded_images = [ image > np.mean(image) + c_std * np.std(image) #images[i] > np.mean(images[i]) + a_std * np.std(images[i]) #images[i] > a_std for i, image in enumerate(processed_images) ] for i, mask in enumerate(thresholded_images): for (h, w), valid in np.ndenumerate(mask): if valid: local_slice = \ np.copy(processed_images[i][h - local_max:h + local_max + 1, w - local_max:w + local_max + 1]) if (h + local_max >= mask.shape[0] or w + local_max >= mask.shape[1] or h - local_max < 0 or w - local_max < 0): mask[h, w] = False continue local_slice[local_max, local_max] = 0 if np.amax(local_slice) >= processed_images[i][h, w]: mask[h, w] = False size = 4 for i, image in enumerate(images): i_std = np.std(image) i_median = np.median(image) - i_std i_max = np.amax(image) for (h, w), value in np.ndenumerate(image): if image[h, w] > i_median: image[h, w] = int( np.around( math.sqrt(image[h, w] - i_median) / math.sqrt(i_max - i_median) * float(2**8 - 1))) else: image[h, w] = 0 output_images = [ ImageOps.colorize( Image.fromstring('L', image.shape, image.astype(np.uint8)), (0, 0, 0), (255, 255, 255)) for image in images ] for i, image in enumerate(images): for (h, w), value in np.ndenumerate(image): if thresholded_images[i][h, w]: box = ((w - size, h - size), (w + size, h + size)) draw = ImageDraw.Draw(output_images[i]) draw.rectangle(box, fill=None, outline='blue') # Editing the output file name; Will have the same as the filename + png [ image.save( str(i).zfill(int(np.ceil(math.log(len(output_images), 10)))) + ' SIMPLE ' + str(output_filename_hash) + '.png') for i, image in enumerate(output_images) ] for i, image in enumerate(thresholded_images): print( str(i).zfill(int(np.ceil(math.log(len(thresholded_images), 10)))) + ' ' + str(np.sum(np.sum(image))))
return 5 + ulpaste[1] + im.size[1] - slotwidth * (i + 1) for i in xrange(slots): draw.text((ulpaste[0] - 6 * slotwidth, getrow(i)), "0x%08x" % (i * 0x02000000), fill="#444444", font=dpf) for row in xrange(32): txt = Image.new("L", (600, 60)) d = ImageDraw.Draw(txt) d.text((0, 0), "0x%08x" % (row * 0x00100000), fill=255, font=dpf) del d rtxt = txt.rotate(17.5, expand=1) fim.paste(ImageOps.colorize(rtxt, "#ffffff", "#444444"), (ulpaste[0] + (row * (p_per_col / 32) * pheight), ulpaste[1] - 4 * slotwidth), rtxt) del txt del rtxt #draw.text ((ulpaste[0] + 0x00011000 * p_per_col*pheight / (32*1024*1024), ulpaste[1] + 65*slotwidth), # "Code/Data", fill="#000000", font=dpf) #draw.text ((ulpaste[0] + 0x018C0000 * p_per_col*pheight / (32*1024*1024), ulpaste[1] + 65*slotwidth), # "Stack/Heap", fill="#000000", font=dpf) def writerow(i, str): draw.text((10 * slotwidth, getrow(i)), str, fill="#000000", font=dpf)
# figure out layout such that there are more columns than rows while n_cols < n_rowsAdj: n_cols = n_cols + 1 n_rowsAdj = n_rows/n_cols if n_rows % n_cols*n_rowsAdj > 0: #n_rowsAdj = n_rowsAdj+1 n_cols = n_cols + 1 #fig = plt.figure() for i in range(n_clusters): iout = im.new('L',(m_frameBinned,n_frameBinned),"black") g0 = code==i g0 = g0.astype(np.uint8)*255 iout.putdata(list(g0)) iout = iops.colorize(iout,(0,0,0),(255,0,0)) #iout.save("cluster_0.tif") # blend mean of stack with this cluster's regions. flip image top to bottom ioutBlend = (im.blend(imean,iout,0.5)).transpose(im.FLIP_TOP_BOTTOM) #ioutBlend.save("cluster_" + str(i) + ".tif") #ax = fig.add_subplot(n_rowsAdj,n_cols,i+1,frame_on=False) ax = plt.subplot(n_rowsAdj,n_cols,i+1) plt.imshow(ioutBlend) plt.xlabel(str(i+1)) plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) plt.savefig(sz_fbase + "_clusters.pdf",dpi=300,format="pdf") plt.clf() # save traces out to text file fout = open(sz_fbase + "_signals.txt",'w')
details = get_data("details.xls") for customer_detail in details["Sheet1"]: im=Image.open("2.png") f = ImageFont.truetype("avantgarde.otf",14) name_txt=Image.new('L', (500,500)) name_block = ImageDraw.Draw(name_txt) name_block.text( (15, 38), customer_detail[0], font=f, fill=255) w=name_txt.rotate(0, expand=3) im.paste( ImageOps.colorize(w, (0,0,0), (255,203,4)), (242,60), w) phone_txt = Image.new('L',(500,500)) phone_block = ImageDraw.Draw(phone_txt) phone_block.text( (15,70), str(customer_detail[1]), font=f, fill=255) w=phone_txt.rotate(0, expand=3) im.paste( ImageOps.colorize(w, (0,0,0), (0,0,0)), (242,60), w) comp_txt= Image.new('L',(500,500)) comp_block = ImageDraw.Draw(comp_txt) comp_block.text( (30,98), customer_detail[2], font=f, fill=255) w=comp_txt.rotate(0, expand=3) im.paste( ImageOps.colorize(w, (0,0,0), (0,0,0)), (242,60), w) route_txt= Image.new('L',(500,500)) route_block = ImageDraw.Draw(route_txt)
def WeatherScreenshot(): debug("\n ### WeatherScreenshot [%s] ### " % time.ctime()) debug("Threading image acquisition") #th = threading.Thread(target=GetPhoto) #th.start() #twd = threading.Thread(target=TheWalkingDead, args=(th,)) #twd.walker = "Testing" #twd.start() #if not twd.is_alive(): # sys.exit(1) ReadConfig() debug("Autenticating in Twitter") # App python-tweeter # https://dev.twitter.com/apps/815176 tw = twitter.Api( consumer_key = cons_key, consumer_secret = cons_sec, access_token_key = acc_key, access_token_secret = acc_sec ) #debug("Retrieving info...") #msg = get_content() #th.join() #twd.join() #if FAILCOUNTER < 0: # print "Failed to acquire image. Quitting..." # sys.exit(1) #if not msg: msg = "Just another reboot at %s" % \ time.strftime("%H:%M", time.localtime()) tw.PostUpdate(status = msg) if False: msg_body = "\n".join(msg[1:]) im = Image.open(filename) # just get truetype fonts on package ttf-mscorefonts-installer try: f_top = ImageFont.truetype(font="Arial", size=60) except TypeError: # older versions hasn't font and require full path arialpath = "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf" f_top = ImageFont.truetype(arialpath, size=60) try: f_body = ImageFont.truetype(font="Arial", size=20) except TypeError: # older versions hasn't font and require full path arialpath = "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf" f_body = ImageFont.truetype(arialpath, size=20) # SHADOW step = 1 for c in [ WHITE, BLACK ]: txt = Image.new('L', IMGSIZE) d = ImageDraw.Draw(txt) d.text( (10 + step, 10 + step), msg[0], font=f_top, fill=255) position = 80 for m in msg[1:]: d.text( (10 + step, position + step), m, font=f_body, fill=255) position += 20 w = txt.rotate(0, expand=1) step = 0 im.paste(ImageOps.colorize(w, c, c), (0,0), w) im.save(filename) # adding the credit to the right guys (awesome guys btw) msg = u"%s \nvia http://forecast.io/#/f/59.4029,17.9436" % "\n".join(msg) try: print u"%s" % msg except UnicodeEncodeError: # I just hate this... pass if sys.argv[-1] == "dry-run": debug("Just dry-run mode. Done!") return try: #tw.PostMedia(status = msg,media = filename) tw.Post(status = msg) debug("done!") except: print "Failed for some reason..." # it failed so... deal w/ it. pass else: print "no message available"
def sphereToPicture(sphere): picture = normalize(sphere) picture = ImageOps.colorize(picture, (10, 0, 100), (0, 256, 0)) picture = imageToPygame(picture) return picture
def draw_and_compare(): #global save_im, remaining, fail_count, last_saved_count global colors save_im_copy = whistler.save_im.copy() #poly_rect_area = get_rand_rect() rx1, ry1 = randint(0, whistler.width), randint(0, whistler.height) rim = choice(imgs) canvasOffset = 0 rx1 = (rx1 - ((rx1 - canvasOffset) % rim.size[0])); ry1 = (ry1 - ((ry1 - canvasOffset) % rim.size[1])); offset = choice([1,2,3,4,5,6]) if offset==1: rx1 = rx1 - rim.size[0]/2 ry1 = ry1 - rim.size[1]/2 if offset==2: rx1 = rx1 - rim.size[0]/2 ry1 = ry1 + rim.size[1]/2 if offset==3: rx1 = rx1 + rim.size[0]/2 ry1 = ry1 - rim.size[1]/2 if offset==4: rx1 = rx1 + rim.size[0]/2 ry1 = ry1 + rim.size[1]/2 rangle = randint(0,359) rim = rim.rotate(rangle, Image.NEAREST, expand=True) if choice([1,2]) == 2: rim = rim.transpose(Image.FLIP_LEFT_RIGHT) if choice([1,2]) == 2: rim = rim.transpose(Image.FLIP_TOP_BOTTOM) rx2 = rx1 + rim.size[0] ry2 = ry1 + rim.size[1] #save_im_crop = whistler.save_im.crop((rx1, ry1, rx2, ry2)) #save_im_crop.load() #draw_rand_polys(save_im_crop) im_crop = whistler.im.crop((rx1, ry1, rx2, ry2)) save_im_copy_crop = save_im_copy.crop((rx1, ry1, rx2, ry2)) im_crop.load(), save_im_copy_crop.load() r,g,b = varyb(vary(choice(colors))) rc, bc, bc, ralpha = rim.split() blob = ImageOps.colorize(ImageOps.grayscale(rim.convert('RGB')),(r,g,b,0), (255,255,255,0)) #blob = rim.convert('RGB') blob.filter(ImageFilter.BLUR) ralpha.filter(ImageFilter.BLUR) blob.putalpha(ralpha) whistler.save_im.paste(blob, (rx1, ry1), mask=ralpha) painted_crop = whistler.save_im.crop((rx1, ry1, rx2, ry2)) painted_crop.load() old_diff = whistler.abs_diff(save_im_copy_crop,im_crop) new_diff = whistler.abs_diff(painted_crop,im_crop) if new_diff < old_diff: whistler.remaining -= old_diff-new_diff #print ':\timproved\t' + str(old_diff-new_diff)\ # + '\tremaining:\t' + str(remaining) whistler.last_saved_count = 0 whistler.fail_count=0 else: whistler.save_im = save_im_copy whistler.fail_count +=1
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
dt = t[int(i*len(t)/O)] - t0 t0 = t[int(i*len(t)/O)] #current star color color = cols[int(i*len(t)/O)] #take next gif image image = im[i % N] #get image size isize = image.size bsize = tuple((isize[0]*2,isize[1])) size = tuple([int(z * R[int(i*len(t)/O)]) for z in isize]) #apply color transform to image image.load() r, g, b, alpha = image.split() gray = ImageOps.grayscale(image) img = ImageOps.colorize(gray, (0,0,0,0), color) img.putalpha(alpha) #resize transform to image img = img.resize(size) #apply filter to image #omage = omage.filter(ImageFilter.SMOOTH_MORE) #generate HR plot sub.plot(np.log10(Teff)[:int(i*len(t)/O)+1], logL[:int(i*len(t)/O)+1], 'b.', ms=4) sub.title.set_color('white') sub.yaxis.label.set_color('white') sub.xaxis.label.set_color('white') sub.tick_params(axis='x', colors='white') sub.tick_params(axis='y', colors='white')
def plot_ld_heatmap(mat_file, bin_file, outfile, window_size=500000, summary_stat="unlinked_pct", cmap=DEFAULT_CMAP, missing_color=(255, 255, 255), bg_color=(255, 255, 255), chrm_color=(0, 0, 0), tics=False, font_file="/Library/Fonts/Microsoft/Arial.ttf", font_size=80): """ Create a triangle heatmap plot from a numpy matrix of pairwise-bin values. Each cel of the matrix is a summary statistic (e.g. mean or 95th percentile) of the LD between the two bins. The matrix can either be square or upper-right-hand. bins is a three-column matrix: chrmosome, start position, summary value. TODO: support creating diamond heatmaps from a square matrix. """ import csv def load_matrix(x, first): with open(abspath(x), "rU") as i: r = csv.reader(i, delimiter=",") h = r.next()[first:] m = np.array(list( map(lambda x: float("nan" if x == "NA" else x), row[first:]) for row in r), dtype=np.float64) return (h, m) mat = load_matrix(mat_file, 1)[1] #mat = mat[0:5063,0:5063] bin_cols, bins = load_matrix(bin_file, 0) #bins = bins[0:5063,] chrm_col = which("chrm", bin_cols) stat_col = which(summary_stat, bin_cols) chrms = bins[:, chrm_col] chrm_idxs = np.unique(chrms, return_index=True)[1] chrms = [int(chrms[index]) for index in sorted(chrm_idxs)] # TODO: this is a hack. Fix the process_ld_file function to write blank lines for missing windows row = 0 nan = float("nan") blank = [nan] * (bins.shape[1] - 3) for chrm in chrms: pos = 0 while row < bins.shape[0] and int(bins[row, chrm_col]) == chrm: if int(bins[row, 1]) != pos: bins = np.insert(bins, row, [chrm, pos, 0] + blank, axis=0) mat = np.insert(mat, row, nan, axis=0) mat = np.insert(mat, row, nan, axis=1) row += 1 pos += window_size mat_size = mat.shape[0] assert mat_size == mat.shape[1], "Matrix is not square" assert mat_size == len(bins), "Matrix and bins are of different size" def convert_chrm(c): c = int(c) return "X" if c == 23 else str(c) chrms = map(convert_chrm, bins[..., chrm_col]) im = Image.new("RGB", (mat_size + X_OFFSETS[4], mat_size + Y_OFFSETS[0]), bg_color) pixels = im.load() draw = ImageDraw.Draw(im) font = ImageFont.truetype(font_file, font_size) chrm_id = None chrm_end = 0 tic_interval = 10000000 / window_size for row, summary in enumerate(bins[..., stat_col]): chrm = chrms[row] def get_line_coords(start, end): x1 = row + X_OFFSETS[start] y1 = row + Y_OFFSETS[start] x2 = row + X_OFFSETS[end] y2 = row + Y_OFFSETS[end] return ((x1, y1), (x2, y2)) # draw summary line color = heatmap(summary, cmap) if not np.isnan(summary) and summary > 0 else 0 draw.line(get_line_coords(2, 3), fill=color) for col in xrange(row, mat_size): x = col + X_OFFSETS[4] val = mat[row, col] if np.isnan(val) or val < 0: pixels[x, row] = missing_color else: pixels[x, row] = heatmap(val, cmap) # Label chromosome boundaries if chrm != chrm_id or row == (mat_size - 1): draw.line(get_line_coords(0, 2), fill=chrm_color, width=5) if chrm_id is not None: # first draw text in a blank image, then rotate and paste into the main image txt = str(chrm_id) txt_size = draw.textsize(txt, font=font) txt_img = Image.new("L", txt_size) txt_draw = ImageDraw.Draw(txt_img) txt_draw.text((0, 0), txt, font=font, fill=255) txt_img = txt_img.rotate(-45, expand=1) offset = max(txt_size[0], txt_size[1]) lft_indent = int(math.floor((txt_img.size[0] - offset) / 2)) top_indent = int(math.floor((txt_img.size[1] - offset) / 2)) txt_img = txt_img.crop( (lft_indent, top_indent, txt_img.size[0] - lft_indent, txt_img.size[1] - top_indent)) text_row = int(chrm_end + ((row - chrm_end) / 2)) text_x = int(text_row + X_OFFSETS[0] + ((X_OFFSETS[2] - X_OFFSETS[0]) / 2) - (txt_img.size[0] / 2)) text_y = int(text_row + Y_OFFSETS[0] + ((Y_OFFSETS[2] - Y_OFFSETS[0]) / 2) - (txt_img.size[1] / 2)) im.paste(ImageOps.colorize(txt_img, bg_color, chrm_color), (text_x, text_y)) chrm_id = chrm chrm_end = row # add tics if tics and ((row - chrm_end) % tic_interval) == 0: draw.line(get_line_coords(1, 2), fill=chrm_color, width=3) # convert to RGBA (required for background recoloring) im2 = im.convert("RGBA") # rotate im2 = im2.rotate(45, expand=True) # recolor background bg = Image.new("RGBA", im2.size, (255, ) * 4) im2 = Image.composite(im2, bg, im2) # convert back to RGB im = im2.convert(im.mode) # crop final_height = int(math.ceil( math.sqrt(2 * math.pow(mat_size, 2)) / 2)) + OFFSETS[-1] im = im.crop((0, 0, im.size[0], final_height)) # save im.save(outfile)
def add_text_image(self, text_image, offset = (242,60)): self.base.paste(ImageOps.colorize(text_image, (0,0,0), self.colour), offset, text_image) return self.base
def counting(c_std, a_std, imageFile): image_list = [imageFile] c_std = float(c_std) if image_list[0][-3:] == "tif": for f, filename in enumerate(image_list): subprocess.call(["convert", filename, filename + ".png"]) image_list[f] = filename + ".png" output_filename_hash = datetime.datetime.now().minute * 60 + datetime.datetime.now().second images = [scipy.misc.imread(filename).astype(np.uint16) for filename in image_list] # correlation_matrix = np.array([[-1, -1, -1, -1, -1], # [-1, -1, -1, -1, -1], # [-1, -1, 24, -1, -1], # [-1, -1, -1, -1, -1], # [-1, -1, -1, -1, -1]]) correlation_matrix = np.array( [ [-5935, -5935, -5935, -5935, -5935], [-5935, 8027, 8027, 8027, -5935], [-5935, 8027, 30742, 8027, -5935], [-5935, 8027, 8027, 8027, -5935], [-5935, -5935, -5935, -5935, -5935], ] ) median_diameter = 5 local_max = 3 # c_std = 1 processed_images = [np.copy(image).astype(np.int64) for image in images] processed_images = [ np.subtract(image, np.minimum(spf.median_filter(image, median_diameter), image)) for image in images ] processed_images = [ np.maximum(scipy.signal.correlate(image, correlation_matrix, mode="same"), np.zeros_like(image)).astype( np.int64 ) for image in processed_images ] thresholded_images = [ image > np.mean(image) + c_std * np.std(image) # images[i] > np.mean(images[i]) + a_std * np.std(images[i]) # images[i] > a_std for i, image in enumerate(processed_images) ] for i, mask in enumerate(thresholded_images): for (h, w), valid in np.ndenumerate(mask): if valid: local_slice = np.copy( processed_images[i][h - local_max : h + local_max + 1, w - local_max : w + local_max + 1] ) if ( h + local_max >= mask.shape[0] or w + local_max >= mask.shape[1] or h - local_max < 0 or w - local_max < 0 ): mask[h, w] = False continue local_slice[local_max, local_max] = 0 if np.amax(local_slice) >= processed_images[i][h, w]: mask[h, w] = False size = 4 for i, image in enumerate(images): i_std = np.std(image) i_median = np.median(image) - i_std i_max = np.amax(image) for (h, w), value in np.ndenumerate(image): if image[h, w] > i_median: image[h, w] = int( np.around(math.sqrt(image[h, w] - i_median) / math.sqrt(i_max - i_median) * float(2 ** 8 - 1)) ) else: image[h, w] = 0 output_images = [ ImageOps.colorize(Image.fromstring("L", image.shape, image.astype(np.uint8)), (0, 0, 0), (255, 255, 255)) for image in images ] for i, image in enumerate(images): for (h, w), value in np.ndenumerate(image): if thresholded_images[i][h, w]: box = ((w - size, h - size), (w + size, h + size)) draw = ImageDraw.Draw(output_images[i]) draw.rectangle(box, fill=None, outline="blue") # Editing the output file name; Will have the same as the filename + png [ image.save( str(i).zfill(int(np.ceil(math.log(len(output_images), 10)))) + " SIMPLE " + str(output_filename_hash) + ".png" ) for i, image in enumerate(output_images) ] for i, image in enumerate(thresholded_images): print(str(i).zfill(int(np.ceil(math.log(len(thresholded_images), 10)))) + " " + str(np.sum(np.sum(image))))
def cf_image(cfs, coords, width=None, height=None, pos=(0, 0), size=26, border=5, bg=(0, 0, 0), colmap=None): """ Returns a PIL image showing the selected connection fields (CFS) as supplied by extract_CFs. Does not support non-square CF shapes. 'cfs' is an ndarray of N dstacked cfs, each of shape (X,X): (X,X,N) 'coords' is an ndarray of N coordinates: (N,2) 'width' and 'height' are either None (full) of integer grid sizes 'pos' is the starting position of the block, (x,y) 'size' and 'border' are the cf image size and the border size in pixels. 'colmap' is an RGB array shape (N,M,3) with values between 0.0 and 1.0. """ normalize = lambda arr: (arr - arr.min()) / (arr.max() - arr.min()) cf_im = lambda cf, size: greyscale(normalize(cf)).resize( (size, size), Image.NEAREST) (posx, posy) = pos (d1, d2) = zip(*coords) density = len(set(d1)) assert density == len(set(d2)), "Not implemented for non-square sets" height = density if height is None else height width = density if width is None else width assert height > 0 and width > 0, "Height and width must be None or greater than zero" assert posx + width <= density, "X position and width greater than density" assert posy + height <= density, "Y position and width greater than density" # Functions mapping original coordinates onto consecutive grid indices fst_map = dict(((ind, i) for (i, ind) in enumerate(sorted(set(d1))))) snd_map = dict(((ind, i) for (i, ind) in enumerate(sorted(set(d2))))) # Generating a dictionary from the grid coordinates to the CF index mapped_coords = [(fst_map[fst], snd_map[snd]) for [fst, snd] in coords] indexed_coords = dict( (coord, i) for (i, coord) in enumerate(mapped_coords)) # Initialising the image imwidth = width * size + (width - 1) * border imheight = height * size + (height - 1) * border cf_block = Image.new('RGB', (imwidth, imheight), bg) # Building image row by row, top to bottom. for yind in range(height): for xind in range(width): # Swapped coordinate system cf_ind = indexed_coords[(yind + posy, xind + posx)] # Get color from the color map if available if colmap is not None: crd1, crd2 = coords[cf_ind] r, g, b = colmap[crd1, crd2, :] color = (r * 255, g * 255, b * 255) else: color = (255, 255, 255) cf = cfs[:, :, cf_ind] (cf_dim1, cf_dim2) = cf.shape assert cf_dim1 == cf_dim2, "Only supports square CFs." cf_image = ImageOps.colorize(cf_im(cf, size), (0, 0, 0, 0), color) xoffset = xind * border yoffset = yind * border paste_coord = (xoffset + xind * size, yoffset + yind * size) cf_block.paste(cf_image, paste_coord) return cf_block
dpf = ImageFont.truetype ("datapro.ttf", fs) def getrow(i): return 5 + ulpaste[1] + im.size[1] - slotwidth * (i + 1) for i in xrange(slots): draw.text ((ulpaste[0] - 6 * slotwidth, getrow(i) ), "0x%08x" % (i * 0x02000000), fill="#444444", font=dpf) for row in xrange(32): txt=Image.new("L", (600,60)) d = ImageDraw.Draw(txt) d.text ((0,0), "0x%08x" % (row * 0x00100000), fill=255, font=dpf) del d rtxt = txt.rotate (17.5, expand=1) fim.paste (ImageOps.colorize(rtxt, "#ffffff", "#444444"), (ulpaste[0] + (row*(p_per_col/32)*pheight), ulpaste[1] - 4*slotwidth), rtxt) del txt del rtxt #draw.text ((ulpaste[0] + 0x00011000 * p_per_col*pheight / (32*1024*1024), ulpaste[1] + 65*slotwidth), # "Code/Data", fill="#000000", font=dpf) #draw.text ((ulpaste[0] + 0x018C0000 * p_per_col*pheight / (32*1024*1024), ulpaste[1] + 65*slotwidth), # "Stack/Heap", fill="#000000", font=dpf) def writerow(i, str): draw.text ((10 * slotwidth, getrow(i) ), str, fill="#000000", font=dpf) writerow (0, "Slot 0: Active Process") writerow (1, "Slot 1: ROM Image")
def plot_ld_heatmap(mat_file, bin_file, outfile, window_size=500000, summary_stat="unlinked_pct", cmap=DEFAULT_CMAP, missing_color=(255, 255, 255), bg_color=(255, 255, 255), chrm_color=(0, 0, 0), tics=False, font_file="/Library/Fonts/Microsoft/Arial.ttf", font_size=80): """ Create a triangle heatmap plot from a numpy matrix of pairwise-bin values. Each cel of the matrix is a summary statistic (e.g. mean or 95th percentile) of the LD between the two bins. The matrix can either be square or upper-right-hand. bins is a three-column matrix: chrmosome, start position, summary value. TODO: support creating diamond heatmaps from a square matrix. """ import csv def load_matrix(x, first): with open(abspath(x), "rU") as i: r = csv.reader(i, delimiter=",") h = r.next()[first:] m = np.array(list(map(lambda x: float("nan" if x == "NA" else x), row[first:]) for row in r), dtype=np.float64) return (h, m) mat = load_matrix(mat_file, 1)[1] #mat = mat[0:5063,0:5063] bin_cols, bins = load_matrix(bin_file, 0) #bins = bins[0:5063,] chrm_col = which("chrm", bin_cols) stat_col = which(summary_stat, bin_cols) chrms = bins[:,chrm_col] chrm_idxs = np.unique(chrms, return_index=True)[1] chrms = [int(chrms[index]) for index in sorted(chrm_idxs)] # TODO: this is a hack. Fix the process_ld_file function to write blank lines for missing windows row = 0 nan = float("nan") blank = [nan] * (bins.shape[1]-3) for chrm in chrms: pos = 0 while row < bins.shape[0] and int(bins[row, chrm_col]) == chrm: if int(bins[row, 1]) != pos: bins = np.insert(bins, row, [chrm, pos, 0] + blank, axis=0) mat = np.insert(mat, row, nan, axis=0) mat = np.insert(mat, row, nan, axis=1) row += 1 pos += window_size mat_size = mat.shape[0] assert mat_size == mat.shape[1], "Matrix is not square" assert mat_size == len(bins), "Matrix and bins are of different size" def convert_chrm(c): c = int(c) return "X" if c == 23 else str(c) chrms = map(convert_chrm, bins[...,chrm_col]) im = Image.new("RGB", (mat_size + X_OFFSETS[4], mat_size + Y_OFFSETS[0]), bg_color) pixels = im.load() draw = ImageDraw.Draw(im) font = ImageFont.truetype(font_file, font_size) chrm_id = None chrm_end = 0 tic_interval = 10000000 / window_size for row, summary in enumerate(bins[...,stat_col]): chrm = chrms[row] def get_line_coords(start, end): x1 = row + X_OFFSETS[start] y1 = row + Y_OFFSETS[start] x2 = row + X_OFFSETS[end] y2 = row + Y_OFFSETS[end] return ((x1, y1), (x2, y2)) # draw summary line color = heatmap(summary, cmap) if not np.isnan(summary) and summary > 0 else 0 draw.line(get_line_coords(2, 3), fill=color) for col in xrange(row, mat_size): x = col + X_OFFSETS[4] val = mat[row,col] if np.isnan(val) or val < 0: pixels[x, row] = missing_color else: pixels[x, row] = heatmap(val, cmap) # Label chromosome boundaries if chrm != chrm_id or row == (mat_size - 1): draw.line(get_line_coords(0, 2), fill=chrm_color, width=5) if chrm_id is not None: # first draw text in a blank image, then rotate and paste into the main image txt = str(chrm_id) txt_size = draw.textsize(txt, font=font) txt_img = Image.new("L", txt_size) txt_draw = ImageDraw.Draw(txt_img) txt_draw.text((0, 0), txt, font=font, fill=255) txt_img = txt_img.rotate(-45, expand=1) offset = max(txt_size[0], txt_size[1]) lft_indent = int(math.floor((txt_img.size[0] - offset) / 2)) top_indent = int(math.floor((txt_img.size[1] - offset) / 2)) txt_img = txt_img.crop((lft_indent, top_indent, txt_img.size[0] - lft_indent, txt_img.size[1] - top_indent)) text_row = int(chrm_end + ((row - chrm_end) / 2)) text_x = int(text_row + X_OFFSETS[0] + ((X_OFFSETS[2] - X_OFFSETS[0]) / 2) - (txt_img.size[0] / 2)) text_y = int(text_row + Y_OFFSETS[0] + ((Y_OFFSETS[2] - Y_OFFSETS[0]) / 2) - (txt_img.size[1] / 2)) im.paste(ImageOps.colorize(txt_img, bg_color, chrm_color), (text_x, text_y)) chrm_id = chrm chrm_end = row # add tics if tics and ((row - chrm_end) % tic_interval) == 0: draw.line(get_line_coords(1, 2), fill=chrm_color, width=3) # convert to RGBA (required for background recoloring) im2 = im.convert("RGBA") # rotate im2 = im2.rotate(45, expand=True) # recolor background bg = Image.new("RGBA", im2.size, (255,)*4) im2 = Image.composite(im2, bg, im2) # convert back to RGB im = im2.convert(im.mode) # crop final_height = int(math.ceil(math.sqrt(2 * math.pow(mat_size, 2)) / 2)) + OFFSETS[-1] im = im.crop((0, 0, im.size[0], final_height)) # save im.save(outfile)
def sphereToPicture(sphere): picture = normalize(sphere) picture = ImageOps.colorize(picture, (10,0,100), (0,256,0)) picture = imageToPygame(picture) return picture
def WeatherScreenshot(): global filename debug("\n ### WeatherScreenshot [%s] ### " % time.ctime()) debug("Threading image acquisition") th = threading.Thread(target=GetPhoto) th.start() twd = threading.Thread(target=TheWalkingDead, args=(th, )) twd.walker = "Testing" twd.start() if not twd.is_alive(): sys.exit(1) ReadConfig() debug("Autenticating in Twitter") # App python-tweeter # https://dev.twitter.com/apps/815176 tw = twitter.Api(consumer_key=cons_key, consumer_secret=cons_sec, access_token_key=acc_key, access_token_secret=acc_sec) debug("Retrieving info...") msg = get_content() th.join() twd.join() if FAILCOUNTER < 0: print("Failed to acquire image. Quitting...") sys.exit(1) if not msg: msg = "Just another shot at %s" % \ time.strftime("%H:%M", time.localtime()) if msg: im = Image.open(filename) # just get truetype fonts on package ttf-mscorefonts-installer try: f_top = ImageFont.truetype(font="Impact", size=60) except TypeError: # older versions hasn't font and require full path arialpath = "/usr/share/fonts/truetype/msttcorefonts/Impact.ttf" f_top = ImageFont.truetype(arialpath, size=60) try: f_body = ImageFont.truetype(font="Arial", size=20) except TypeError: # older versions hasn't font and require full path arialpath = "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf" f_body = ImageFont.truetype(arialpath, size=20) """ # SHADOW step = 1 for c in [ WHITE, BLACK ]: txt = Image.new('L', IMGSIZE) d = ImageDraw.Draw(txt) d.text( (10 + step, 10 + step), msg[0], font=f_top, fill=255) position = 80 for m in msg[1:]: d.text( (10 + step, position + step), m, font=f_body, fill=255) position += 20 w = txt.rotate(0, expand=1) step = 0 im.paste(ImageOps.colorize(w, c, c), (0,0), w) im.save(filename) """ step = 0 debug("Writting in WHITE") txt = Image.new('L', IMGSIZE) d = ImageDraw.Draw(txt) ## Title ## # border first d.text((10 + step + 1, 10 + step), msg[0], font=f_top, fill=255) d.text((10 + step - 1, 10 + step), msg[0], font=f_top, fill=255) d.text((10 + step, 10 + step + 1), msg[0], font=f_top, fill=255) d.text((10 + step, 10 + step - 1), msg[0], font=f_top, fill=255) ## Body ## position = 80 for m in msg[1:]: # border first d.text((10 + step + 1, position + step), m, font=f_body, fill=255) d.text((10 + step - 1, position + step), m, font=f_body, fill=255) d.text((10 + step, position + step + 1), m, font=f_body, fill=255) d.text((10 + step, position + step - 1), m, font=f_body, fill=255) # content d.text((10 + step, position + step), m, font=f_body, fill=255) position += 20 # final touch w = txt.rotate(0, expand=1) im.paste(ImageOps.colorize(w, WHITE, WHITE), (0, 0), w) im.save(filename) debug("Writting in BLACK") txt = Image.new('L', IMGSIZE) d = ImageDraw.Draw(txt) # content d.text((10 + step, 10 + step), msg[0], font=f_top, fill=255) position = 80 for m in msg[1:]: # content d.text((10 + step, position + step), m, font=f_body, fill=255) position += 20 # final touch w = txt.rotate(0, expand=1) im.paste(ImageOps.colorize(w, BLACK, BLACK), (0, 0), w) im.save(filename) # adding the credit to the right guys (awesome guys btw) msg = u"%s \nvia http://forecast.io/#/f/59.4029,17.9436" % "\n".join( msg) try: print(u"%s" % msg) except UnicodeEncodeError: # I just hate this... pass if sys.argv[-1] == "dry-run": debug("Just dry-run mode. Done!") return try: tw.PostUpdate(status=msg, media=filename) debug("done!") except Exception as e: print("Failed for some reason:", e) # it failed so... deal w/ it. pass else: print("no message available")