Ejemplo n.º 1
0
def circulos(foto,actual,centro,cont,color):
    print "------------------------------"
    x1,y1=actual # inicio
    x2,y2=centro #centro
    print x1
    print x2
    
    print "punto de inicio:"+str(actual)
    print "Centro:"+str(centro)
    area=cont
    print "Area de figura en revision:"+str(area)
    radio=math.sqrt((x2-x1)**2+(y2-y1)**2)
    print radio
    final = radio*2 #diametro
    print "Radio de posible circulo:"+str(radio)
    comprobar_area=(pi*(radio**2))
    print "Area de posible circulo:"+str(comprobar_area)
    if(comprobar_area-500)<area<(comprobar_area+500):
        print "La figura es un circulo"
        return color, actual,centro, diametro 
    else:
        print "Esta figura no es un circulo"
    draw= ImageDraw(image)
    draw.ellipse((actual-1,final+1),outline = "black")
    foto.save("putitos.jpg")
Ejemplo n.º 2
0
    def filterUnreachable(self, reachable):
        # we'll use the flood fill in Image
        img = Image.fromarray(N.uint8(self._raster) * 64).copy()
        ImageDraw.floodfill(img,map(int,reachable[:2]), 128)
        n = N.array(img.getdata()).reshape(img.size[0], img.size[1])

        self._raster =  N.piecewise(n, [n==128,n!=128], [0,1])
Ejemplo n.º 3
0
def make_brasil_map(data, finalsize=None):
  brasil_png = os.path.join(os.path.split(__file__)[0], 'brasil.png')
  raw = Image.open(brasil_png).copy()
  mapa = Image.new('RGBA', raw.size, 'white')
  mapa.paste(raw, (0, 0))

  for k in data:
    if k in places:
      if type(data[k]) == str:
        color = ImageColor.getcolor('#'+data[k], 'RGBA')
      else:
        color = data[k]
      ImageDraw.floodfill(mapa, places[k], color)

  if finalsize:
    mapa = mapa.resize(finalsize)

  dump = StringIO.StringIO()
  mapa.save(dump, 'PNG')
  return dump.getvalue()
Ejemplo n.º 4
0
def drawterritory(t, shaded):
    """Draw an entire territory (possibly shaded)"""
    risknetwork.draw_territory(t, shaded)
    terr = territories[t.name]
    
    #Create colored version of the image
    canvas.delete(terr.name) 
    #print 'Drawing territory: ', t.name
    if hasattr(t.player, 'backcolor'):
        for fp in terr.floodpoints:
            #print 'Flood-filling', terr.name, ' territory'
            ImageDraw.floodfill(terr.photo, fp, hex_to_rgb(t.player.backcolor))

        #print 'Saving images'
        terr.shadedimage = ImageTk.PhotoImage(terr.photo.point(lambda x:x * 0))
        terr.currentimage = ImageTk.PhotoImage(terr.photo)
    if shaded:
        canvas.create_image(terr.x, terr.y, anchor=Tkinter.NW, 
                            image=terr.shadedimage, tags=(terr.name,))
    else:
        canvas.create_image(terr.x, terr.y, anchor=Tkinter.NW, 
                            image=terr.currentimage, tags=(terr.name,))  
    drawarmy(riskengine.territories[terr.name], 1)
Ejemplo n.º 5
0
	def run(self, callback):
		self.callback = callback
		#try:
		import ImageDraw, Image, os
		s = self.job.project.menutemplate.settings
		s_top = s.margin_top.getValue()
		s_bottom = s.margin_bottom.getValue()
		s_left = s.margin_left.getValue()
		s_right = s.margin_right.getValue()
		s_rows = s.space_rows.getValue()
		s_cols = s.space_cols.getValue()
		nr_cols = s.cols.getValue()
		nr_rows = s.rows.getValue()
		thumb_size = s.thumb_size.getValue()
		if thumb_size[0]:
			from Image import open as Image_open
		(s_width, s_height) = s.dimensions.getValue()
		fonts = self.Menus.fonts
		im_bg = self.Menus.im_bg_orig.copy()
		im_high = Image.new("P", (s_width, s_height), 0)
		im_high.putpalette(self.Menus.spu_palette)
		draw_bg = ImageDraw.Draw(im_bg)
		draw_high = ImageDraw.Draw(im_high)
		if self.menu_count == 1:
			headlineText = self.job.project.settings.name.getValue().decode("utf-8")
			headlinePos = self.getPosition(s.offset_headline.getValue(), 0, 0, s_width, s_top, draw_bg.textsize(headlineText, font=fonts[0]))
			draw_bg.text(headlinePos, headlineText, fill=self.Menus.color_headline, font=fonts[0])
		spuxml = """<?xml version="1.0" encoding="utf-8"?>
	<subpictures>
	<stream>
	<spu
	highlight="%s"
	transparent="%02x%02x%02x"
	start="00:00:00.00"
	force="yes" >""" % (self.highlightpngfilename, self.Menus.spu_palette[0], self.Menus.spu_palette[1], self.Menus.spu_palette[2])
		#rowheight = (self.Menus.fontsizes[1]+self.Menus.fontsizes[2]+thumb_size[1]+s_rows)
		menu_start_title = (self.menu_count-1)*self.job.titles_per_menu + 1
		menu_end_title = (self.menu_count)*self.job.titles_per_menu + 1
		nr_titles = len(self.job.project.titles)
		if menu_end_title > nr_titles:
			menu_end_title = nr_titles+1
		col = 1
		row = 1
		for title_no in range( menu_start_title , menu_end_title ):
			title = self.job.project.titles[title_no-1]
			col_width  = ( s_width  - s_left - s_right  ) / nr_cols
			row_height = ( s_height - s_top  - s_bottom ) / nr_rows
			left =   s_left + ( (col-1) * col_width ) + s_cols/2
			right =    left + col_width - s_cols
			top =     s_top + ( (row-1) * row_height) + s_rows/2
			bottom =    top + row_height - s_rows
			width = right - left
			height = bottom - top

			if bottom > s_height:
				bottom = s_height
			#draw_bg.rectangle((left, top, right, bottom), outline=(255,0,0))
			im_cell_bg = Image.new("RGBA", (width, height),(0,0,0,0))
			draw_cell_bg = ImageDraw.Draw(im_cell_bg)
			im_cell_high = Image.new("P", (width, height), 0)
			im_cell_high.putpalette(self.Menus.spu_palette)
			draw_cell_high = ImageDraw.Draw(im_cell_high)

			if thumb_size[0]:
				thumbPos = self.getPosition(s.offset_thumb.getValue(), 0, 0, width, height, thumb_size)
				box = (thumbPos[0], thumbPos[1], thumbPos[0]+thumb_size[0], thumbPos[1]+thumb_size[1])
				try:
					thumbIm = Image_open(title.inputfile.rsplit('.',1)[0] + ".png")
					im_cell_bg.paste(thumbIm,thumbPos)
				except:
					draw_cell_bg.rectangle(box, fill=(64,127,127,127))
				border = s.thumb_border.getValue()
				if border:
					draw_cell_high.rectangle(box, fill=1)
					draw_cell_high.rectangle((box[0]+border, box[1]+border, box[2]-border, box[3]-border), fill=0)

			titleText = title.formatDVDmenuText(s.titleformat.getValue(), title_no).decode("utf-8")
			titlePos = self.getPosition(s.offset_title.getValue(), 0, 0, width, height, draw_bg.textsize(titleText, font=fonts[1]))

			draw_cell_bg.text(titlePos, titleText, fill=self.Menus.color_button, font=fonts[1])
			draw_cell_high.text(titlePos, titleText, fill=1, font=self.Menus.fonts[1])

			subtitleText = title.formatDVDmenuText(s.subtitleformat.getValue(), title_no).decode("utf-8")
			subtitlePos = self.getPosition(s.offset_subtitle.getValue(), 0, 0, width, height, draw_cell_bg.textsize(subtitleText, font=fonts[2]))
			draw_cell_bg.text(subtitlePos, subtitleText, fill=self.Menus.color_button, font=fonts[2])

			del draw_cell_bg
			del draw_cell_high
			im_bg.paste(im_cell_bg,(left, top, right, bottom), mask=im_cell_bg)
			im_high.paste(im_cell_high,(left, top, right, bottom))

			spuxml += """
	<button name="button%s" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (str(title_no).zfill(2),left,right,top,bottom )
			if col < nr_cols:
				col += 1
			else:
				col = 1
				row += 1

		top = s_height - s_bottom - s_rows/2
		if self.menu_count < self.job.nr_menus:
			next_page_text = s.next_page_text.getValue().decode("utf-8")
			textsize = draw_bg.textsize(next_page_text, font=fonts[1])
			pos = ( s_width-textsize[0]-s_right, top )
			draw_bg.text(pos, next_page_text, fill=self.Menus.color_button, font=fonts[1])
			draw_high.text(pos, next_page_text, fill=1, font=fonts[1])
			spuxml += """
	<button name="button_next" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (pos[0],pos[0]+textsize[0],pos[1],pos[1]+textsize[1])
		if self.menu_count > 1:
			prev_page_text = s.prev_page_text.getValue().decode("utf-8")
			textsize = draw_bg.textsize(prev_page_text, font=fonts[1])
			pos = ( (s_left+s_cols/2), top )
			draw_bg.text(pos, prev_page_text, fill=self.Menus.color_button, font=fonts[1])
			draw_high.text(pos, prev_page_text, fill=1, font=fonts[1])
			spuxml += """
	<button name="button_prev" x0="%d" x1="%d" y0="%d" y1="%d"/>""" % (pos[0],pos[0]+textsize[0],pos[1],pos[1]+textsize[1])
		del draw_bg
		del draw_high
		fd=open(self.menubgpngfilename,"w")
		im_bg.save(fd,"PNG")
		fd.close()
		fd=open(self.highlightpngfilename,"w")
		im_high.save(fd,"PNG")
		fd.close()
		spuxml += """
	</spu>
	</stream>
	</subpictures>"""

		f = open(self.spuxmlfilename, "w")
		f.write(spuxml)
		f.close()
		Task.processFinished(self, 0)
Ejemplo n.º 6
0
def callback(msg_1):
    global i
    global j
    #global ini
    global xcgg
    global lcg, lhg
    global vel_res, wvel_res  #linear velocity, and angular velocity
    global img_nn_c
    global out_gonet
    global vres, wres
    global xc, yc, xyoffset
    j = j + 1

    if j == 1:
        xkg = xcgg  #previous image
        xd = np.zeros((3, 3, 128, 128), dtype=np.float32)
        # resize and crop image for msg_1
        cv2_msg_img = bridge.imgmsg_to_cv2(msg_1)
        cv_imgc = bridge.cv2_to_imgmsg(cv2_msg_img, 'rgb8')
        pil_img = encode(cv_imgc)
        fg_img = PILImage.new('RGBA', pil_img.size, (0, 0, 0, 255))
        draw = ImageDraw.Draw(fg_img)
        draw.ellipse(XYc, fill=(0, 0, 0, 0))
        pil_img.paste(fg_img, (0, 0), fg_img.split()[3])
        img_msg = decode(pil_img)
        cv2_imgd = bridge.imgmsg_to_cv2(img_msg, 'rgb8')

        #crop the image
        cv_cutimg = cv2_imgd[yc - xyoffset:yc + xyoffset,
                             xc - xyoffset:xc + xyoffset]
        cv_cutimg = cv2.transpose(cv_cutimg)
        cv_cutimg = cv2.flip(cv_cutimg, 1)

        #resize the image 3x128x128
        cv_resize1 = cv2.resize(cv_cutimg, (rsizex, rsizey))
        cv_resizex = cv_resize1.transpose(2, 0, 1)
        in_imgcc1 = np.array([cv_resizex], dtype=np.float32)

        #normalization
        in_img1 = (in_imgcc1 - 128) / 128

        for i in range(batchsize):  #usually batchsize=1
            img_nn_c[i] = in_img1
            vresc[i][0][0][0] = vel_res
            wresc[i][0][0][0] = wvel_res

        xcg = Variable(cuda.to_gpu(img_nn_c))
        vrescg = Variable(cuda.to_gpu(vresc))
        wrescg = Variable(cuda.to_gpu(wresc))

        #designing the virtual velocity from joypad input vel_ref(linear velocity) and wvel_ref(angular velocity)
        vres[0][0][0] = 0.5
        if wvel_ref == 0.0:
            wres[0][0][0] = 0.0
        elif wvel_ref != 0.0 and vel_ref == 0.0:
            if wvel_ref > 0.0:
                wres[0][0][0] = 1.0
            else:
                wres[0][0][0] = -1.0
        elif vel_ref < 0.0:
            wres[0][0][0] = 0.0
        else:
            rd = 2.5 * vel_ref / wvel_ref
            wres[0][0][0] = 0.5 / rd
            if wres[0][0][0] > 1.0:
                wres[0][0][0] = 1.0
            elif wres[0][0][0] < -1.0:
                wres[0][0][0] = -1.0

        vresg = Variable(cuda.to_gpu(vres))  #virtual linear velocity
        wresg = Variable(cuda.to_gpu(wres))  #virtual angular velocity

        fl.l_LSTM.h = Variable(lhg)  #internal value of LSTM
        fl.l_LSTM.c = Variable(lcg)  #internal value of LSTM

        with chainer.using_config('train', False), chainer.no_backprop_mode():
            img_gen = gen(invg(xcg))
            dis_real = dis(xcg)
            dis_gen = dis(img_gen)
            output = fl(xcg - img_gen, dis_real - dis_gen, dis_real)

        out_gonet[0] = np.reshape(cuda.to_cpu(output.data), (batchsize))
        lhg = fl.l_LSTM.h.data
        lcg = fl.l_LSTM.c.data
        xcgg = xcg  #keep current image for the next step

        font = ImageFont.truetype(
            "/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf", 25)
        stext = 35
        for k in range(4):  # 4steps prediction
            if k == 0:
                xkg = xkg
                xcg = xcg
            else:
                xkg = xcg
                xcg = xap

            #future prediction:start
            with chainer.using_config('train',
                                      False), chainer.no_backprop_mode():
                if k == 0:
                    x = dec(enc(xkg), vrescg, wrescg)
                else:
                    x = dec(enc(xkg), vresg, wresg)

            genk = F.spatial_transformer_sampler(xkg, x)
            xkp = genk

            with chainer.using_config('train',
                                      False), chainer.no_backprop_mode():
                xcf = dec(enc(xcg), vresg, wresg)
                xkf = dec(enc(xkp), vresg, wresg)

            gencf = F.spatial_transformer_sampler(xcg, xcf)
            genkf = F.spatial_transformer_sampler(xkp, xkf)

            indata = F.concat((genkf, gencf), axis=1)
            maskg = Variable(cuda.to_gpu(mask_batch))

            with chainer.using_config('train',
                                      False), chainer.no_backprop_mode():
                zL = encD(indata)
                xfLs = decD(zL)

            xfL = F.separate(xfLs, axis=1)

            apf0 = F.reshape(xfL[0], (batchsize, 1, 128, 128))
            apf1 = F.reshape(xfL[1], (batchsize, 1, 128, 128))
            apf2 = F.reshape(xfL[2], (batchsize, 1, 128, 128))
            apf3 = F.reshape(xfL[3], (batchsize, 1, 128, 128))
            mask_kL = F.reshape(xfL[4], (batchsize, 1, 128, 128))
            mask_cL = F.reshape(xfL[5], (batchsize, 1, 128, 128))

            apfLc = F.concat((apf0, apf1), axis=1)
            apfLk = F.concat((apf2, apf3), axis=1)
            genLcx = F.spatial_transformer_sampler(gencf, apfLc + maskg)
            genLkx = F.spatial_transformer_sampler(genkf, apfLk + maskg)

            maskL = F.concat((mask_kL, mask_cL), axis=1)
            mask_softL = F.softmax(maskL, axis=1)
            mask_sepL = F.separate(mask_softL, axis=1)

            mask_knL = F.reshape(mask_sepL[0], (batchsize, 1, 128, 128))
            mask_cnL = F.reshape(mask_sepL[1], (batchsize, 1, 128, 128))

            xap = F.scale(genLcx, mask_cnL, axis=0) + F.scale(
                genLkx, mask_knL, axis=0)  #predicted image

            #GONet
            with chainer.using_config('train',
                                      False), chainer.no_backprop_mode():
                img_gen = gen(invg(xap))
                dis_real = dis(xap)
                dis_gen = dis(img_gen)
                output = fl(xap - img_gen, dis_real - dis_gen, dis_real)

            out_gonet[k + 1] = np.reshape(cuda.to_cpu(output.data),
                                          (batchsize))

            #showing predicted image and traversable probability by GONet
            out_imgc = img_nn_c
            imgb = np.fmin(255.0, np.fmax(0.0, out_imgc * 128 + 128))
            imgc = np.reshape(imgb, (3, 128, 128))
            imgd = imgc.transpose(1, 2, 0)
            imge = imgd.astype(np.uint8)
            imgm = bridge.cv2_to_imgmsg(imge)

            imgg = PILImage.new('RGB', (128, 30))
            d = ImageDraw.Draw(imgg)
            d.text((stext, 0),
                   str(np.round(out_gonet[0][0], 2)),
                   fill=(int(255 * (1.0 - out_gonet[0][0])),
                         int(255 * out_gonet[0][0]), 0),
                   font=font)
            imgtext = decode(imgg)
            imgtextcv = bridge.imgmsg_to_cv2(imgtext, 'bgr8')
            imgtextcvx = imgtextcv.transpose(2, 0, 1)
            imgc = np.concatenate((imgc, imgtextcvx), axis=1)
            #
            imgcc0 = imgc

            for im in range(1):
                out_imgc = cuda.to_cpu(xap.data[im])
                imgb = np.fmin(255.0, np.fmax(0.0, out_imgc * 128 + 128))
                imgc = np.reshape(imgb, (3, 128, 128))
                if k == 0:
                    if im == 0:
                        imgg = PILImage.new('RGB', (128, 30))
                        d = ImageDraw.Draw(imgg)
                        d.text((stext, 0),
                               str(np.round(out_gonet[k + 1][im], 2)),
                               fill=(int(255 * (1.0 - out_gonet[k + 1][im])),
                                     int(255 * out_gonet[k + 1][im]), 0),
                               font=font)
                        imgtext = decode(imgg)
                        imgtextcv = bridge.imgmsg_to_cv2(imgtext, 'bgr8')
                        imgtextcvx = imgtextcv.transpose(2, 0, 1)
                        imgc = np.concatenate((imgc, imgtextcvx), axis=1)
                        #
                        imgcc1 = imgc
                elif k == 1:
                    if im == 0:
                        imgg = PILImage.new('RGB', (128, 30))
                        d = ImageDraw.Draw(imgg)
                        d.text((stext, 0),
                               str(np.round(out_gonet[k + 1][im], 2)),
                               fill=(int(255 * (1.0 - out_gonet[k + 1][im])),
                                     int(255 * out_gonet[k + 1][im]), 0),
                               font=font)
                        imgtext = decode(imgg)
                        imgtextcv = bridge.imgmsg_to_cv2(imgtext, 'bgr8')
                        imgtextcvx = imgtextcv.transpose(2, 0, 1)
                        imgc = np.concatenate((imgc, imgtextcvx), axis=1)
                        #
                        imgcc2 = imgc
                elif k == 2:
                    if im == 0:
                        imgg = PILImage.new('RGB', (128, 30))
                        d = ImageDraw.Draw(imgg)
                        d.text((stext, 0),
                               str(np.round(out_gonet[k + 1][im], 2)),
                               fill=(int(255 * (1.0 - out_gonet[k + 1][im])),
                                     int(255 * out_gonet[k + 1][im]), 0),
                               font=font)
                        imgtext = decode(imgg)
                        imgtextcv = bridge.imgmsg_to_cv2(imgtext, 'bgr8')
                        imgtextcvx = imgtextcv.transpose(2, 0, 1)
                        imgc = np.concatenate((imgc, imgtextcvx), axis=1)
                        #
                        imgcc3 = imgc
                elif k == 3:
                    if im == 0:
                        imgg = PILImage.new('RGB', (128, 30))
                        d = ImageDraw.Draw(imgg)
                        d.text((stext, 0),
                               str(np.round(out_gonet[k + 1][im], 2)),
                               fill=(int(255 * (1.0 - out_gonet[k + 1][im])),
                                     int(255 * out_gonet[k + 1][im]), 0),
                               font=font)
                        imgtext = decode(imgg)
                        imgtextcv = bridge.imgmsg_to_cv2(imgtext, 'bgr8')
                        imgtextcvx = imgtextcv.transpose(2, 0, 1)
                        imgc = np.concatenate((imgc, imgtextcvx), axis=1)
                        #
                        imgcc4 = imgc

        imgcc = np.concatenate((imgcc0, imgcc1, imgcc2, imgcc3, imgcc4),
                               axis=2)
        imgdd = imgcc.transpose(1, 2, 0)
        imgee = imgdd.astype(np.uint8)
        imgmm = bridge.cv2_to_imgmsg(imgee)
        image_all.publish(imgmm)
        j = 0
Ejemplo n.º 7
0
def view_2dmol(option,
               maps=None,
               out_put=None,
               target_id=None,
               legends=None,
               extra=None):
    """Function to render a mol image from a smiles.
    The input (option) could be 1) a list of smiles 2) a smiles 3) pdb_code
    Returns a molecule image as data"""
    option = str(option)
    print option
    try:
        option = ast.literal_eval(option)
    except:
        pass
    if type(option) is list:
        mols = [Chem.MolFromSmiles(str(x)) for x in option]
        p = Chem.MolFromSmarts(MCS.FindMCS(mols).smarts)
        AllChem.Compute2DCoords(p)
        [AllChem.GenerateDepictionMatching2DStructure(x, p) for x in mols]
        image = Draw.MolsToGridImage(mols, 2, legends=legends)
    # If it's a PDB code
    elif Chem.MolFromSmiles(str(option)) is None and type(option) is str:
        mol = Chem.MolFromSmiles(
            str(
                Molecule.objects.filter(
                    prot_id__code=option)[0].cmpd_id.smiles))
        AllChem.GenerateDepictionMatching3DStructure(
            mol,
            Chem.MolFromMolBlock(
                str(Molecule.objects.filter(
                    prot_id__code=option)[0].sdf_info)))
        image = Draw.MolToImage(mol)
    # If it's a
    elif type(option) is str:
        mol = Chem.MolFromSmiles(str(option))
        if extra == "SIMPLE":
            image = Draw.MolToImage(mol)
        elif extra is None:
            h_map = None
            image = Draw.MolToImage(mol,
                                    size=(100, 100),
                                    fitImage=True,
                                    highlightMap=h_map)
        else:
            sub = Chem.MolFromSmiles(str(extra))
            h_map = get_h_map(mol, sub)
            image = Draw.MolToImage(mol, highlightMap=h_map)
        if maps is None:
            pass
        else:
            maps = float(maps)
            draw = ImageDraw.Draw(image)
            dim = (20, 0) + (20, image.size[1])
            draw.line(dim,
                      fill=(255 - int(255 * maps), int(255 * maps), 0),
                      width=10)
    else:
        print "NOT VALID TYPE"
        return "NOT VALID TYPE"
    output = StringIO.StringIO()
    image.save(output, format="PNG")
    contents = output.getvalue()
    return contents
Ejemplo n.º 8
0
import Image
import ImageDraw
import ImagePalette
spritesheet = Image.open('test_input.png')

block_size = 30
palette_key = Image.new('P', (16 * block_size, 16 * block_size))
draw = ImageDraw.Draw(palette_key)

print spritesheet.mode

palette_key.putpalette(spritesheet.palette)
x = 0
y = 0
for i in range(256):
    draw.rectangle([(x, y), (x + block_size, y + block_size)], fill=i)
    bg_size = draw.textsize(str(i))
    text_pos = (x + (block_size / 4), y + (block_size / 3))
    draw.rectangle([(text_pos[0] - 1, text_pos[1] + 1),
                    (text_pos[0] + bg_size[0], text_pos[1] + bg_size[1] - 2)],
                   fill=255)
    draw.text((x + (block_size / 4), y + (block_size / 3)), str(i), fill=1)
    x = x + block_size
    if x == 16 * block_size:
        x = 0
        y = y + block_size

palette_key.save('palette_key.png')
Ejemplo n.º 9
0
    def create_legend(self, **kwargs):
        """self.legend is replaced from None to PIL image

        PIL image includes colorbar, caption, and titleString.

        **Modifies:** self.legend (PIL image)

        Parameters
        -----------
        **kwargs : dict
            Any of Figure parameters

        """
        # modify default parameters
        self._set_defaults(kwargs)

        # set fonts size for colorbar
        font = ImageFont.truetype(self.fontFileName, self.fontSize)

        # create a pilImage for the legend
        self.pilImgLegend = Image.new(
            'P', (self.width, int(self.height * self.LEGEND_HEIGHT)), 255)
        draw = ImageDraw.Draw(self.pilImgLegend)

        # set black color
        if self.array.shape[0] == 1:
            black = 254
        else:
            black = (0, 0, 0)

        # if 1 band, draw the color bar
        if self.array.shape[0] == 1:
            # make an array for color bar
            bar = np.outer(
                np.ones(
                    max(int(self.pilImgLegend.size[1] * self.CBAR_HEIGHT),
                        self.CBAR_HEIGHTMIN)),
                np.linspace(0, self.numOfColor,
                            int(self.pilImgLegend.size[0] * self.CBAR_WIDTH)))
            # create a colorbar pil Image
            pilImgCbar = Image.fromarray(np.uint8(bar))
            # paste the colorbar pilImage on Legend pilImage
            self.pilImgLegend.paste(
                pilImgCbar,
                (int(self.pilImgLegend.size[0] * self.CBAR_LOCATION_X),
                 int(self.pilImgLegend.size[1] * self.CBAR_LOCATION_Y)))
            # create a scale for the colorbar
            scaleLocation = np.linspace(0, 1, self.numOfTicks)
            scaleArray = scaleLocation
            if self.logarithm:
                scaleArray = (np.power(scaleArray, (1.0 / self.gamma)))
            scaleArray = (scaleArray * (self.cmax[0] - self.cmin[0]) +
                          self.cmin[0])
            scaleArray = list(map(self._round_number, scaleArray))
            # draw scales and lines on the legend pilImage
            for iTick in range(self.numOfTicks):
                coordX = int(scaleLocation[iTick] * self.pilImgLegend.size[0] *
                             self.CBAR_WIDTH + int(self.pilImgLegend.size[0] *
                                                   self.CBAR_LOCATION_X))

                box = (coordX,
                       int(self.pilImgLegend.size[1] * self.CBAR_LOCATION_Y),
                       coordX,
                       int(self.pilImgLegend.size[1] *
                           (self.CBAR_LOCATION_Y + self.CBAR_HEIGHT)) - 1)
                draw.line(box, fill=black)
                box = (coordX + self.CBTICK_LOC_ADJUST_X,
                       int(self.pilImgLegend.size[1] *
                           (self.CBAR_LOCATION_Y + self.CBAR_HEIGHT)) +
                       self.CBTICK_LOC_ADJUST_Y)
                draw.text(box, scaleArray[iTick], fill=black, font=font)

        # draw longname and units
        box = (int(self.pilImgLegend.size[0] * self.CAPTION_LOCATION_X),
               int(self.pilImgLegend.size[1] * self.CAPTION_LOCATION_Y))
        draw.text(box, str(self.caption), fill=black, font=font)

        # if titleString is given, draw it
        if self.titleString != '':
            # write text each line onto pilImgCanvas
            textHeight = int(self.pilImgLegend.size[1] * self.TITLE_LOCATION_Y)
            for line in self.titleString.splitlines():
                draw.text(
                    (int(self.pilImgLegend.size[0] * self.TITLE_LOCATION_X),
                     textHeight),
                    line,
                    fill=black,
                    font=font)
                text = draw.textsize(line, font=font)
                textHeight += text[1]
Ejemplo n.º 10
0
import Image
import ImageDraw
import ImageFont

width = 1280
height = 1280

if __name__ == "__main__":
    
    background = (255, 255, 255)
    rect = (40, 40, 40)
    
    im = Image.new("RGB", (width, height), background)
    d = ImageDraw.Draw(im)
    
    #f = ImageFont.truetype('/System/Library/Fonts/Keyboard.ttf', 80)
    
    #d.text([80, 80], 'Comparison of rectangles to one of a million pixels', font = f, fill = (230, 230, 230))
    
    
    d.rectangle([80, 1183, 97, 1200], fill = rect)
    

    d.rectangle([80, 980, 100, 1000], fill = rect)
    d.rectangle([80, 776, 104, 800],  fill = rect)
    d.rectangle([80, 570, 110, 600], fill = rect)
    
    d.rectangle([200, 200, 1200, 1200], fill = rect)
    
    im.save("image.png", "PNG")
    
Ejemplo n.º 11
0
 def hasStdDrawObject(self, xSize, ySize):
     self.img = Image.new(modeRGB, (xSize, ySize), self.colors.background)
     self.hasDrawObject(ImageDraw.Draw(self.img))
     return self
Ejemplo n.º 12
0
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 frame(self, imarray):

        # No calibration params yet.
        if not self.vo:
            return

        if self.seq > 10000:
            sys.exit()
        if DEBUG:
            print ""
            print ""
            print "Frame ", self.seq
            print ""
            print ""

        im = imarray.images[1]
        im_r = imarray.images[0]
        if im.colorspace == "mono8":
            im_py = Image.fromstring("L", (im.width, im.height), im.data)
            im_r_py = Image.fromstring("L", (im_r.width, im_r.height),
                                       im_r.data)
        elif im.colorspace == "rgb24":
            use_color = True
            im_col_py = Image.fromstring("RGB", (im.width, im.height), im.data)
            im_py = im_col_py.convert("L")
            im_r_py = Image.fromstring("RGB", (im_r.width, im_r.height),
                                       im_r.data)
            im_r_py = im_r_py.convert("L")
        else:
            print "Unknown colorspace"
            return

        # Detect faces on the first frame
        if not self.current_keyframes:
            self.faces = self.p.detectAllFaces(im_py.tostring(), im.width,
                                               im.height, self.cascade_file,
                                               1.0, None, None, True)
            if DEBUG:
                print "Faces ", self.faces

        sparse_pred_list = []
        sparse_pred_list_2d = []
        old_rect = [0, 0, 0, 0]
        ia = SparseStereoFrame(im_py, im_r_py)
        ia.matches = []
        ia.desc_diffs = []
        ia.good_matches = []

        # Track each face
        iface = -1
        for face in self.faces:

            iface += 1

            (x, y, w, h) = copy.copy(self.faces[iface])
            if DEBUG:
                print "A face ", (x, y, w, h)

            (old_center, old_diff) = self.rect_to_center_diff((x, y, w, h))

            if self.face_centers_3d and iface < len(self.face_centers_3d):
                censize3d = list(copy.copy(self.face_centers_3d[iface]))
                censize3d.append(2.0 *
                                 self.real_face_sizes_3d[iface])  ###ZMULT
                self.get_features(ia, self.num_feats, (x, y, w, h), censize3d)
            else:
                self.get_features(ia, self.num_feats, (x, y, w, h),
                                  (0.0, 0.0, 0.0, 1000000.0))
            if not ia.kp2d:
                continue

            # First frame:
            if len(self.current_keyframes) < iface + 1:

                (cen, diff) = self.rect_to_center_diff((x, y, w, h))
                cen3d = self.cam.pix2cam(cen[0], cen[1], ia.avgd)
                cen3d = list(cen3d)
                ltf = self.cam.pix2cam(x, y, ia.avgd)
                rbf = self.cam.pix2cam(x + w, y + h, ia.avgd)
                fs3d = ((rbf[0] - ltf[0]) + (rbf[1] - ltf[1])) / 4.0
                # This assumes that we're tracking the face plane center, not the center of the head sphere.
                # If you want to track the center of the sphere instead, do: cen3d[2] += fs3d

                # Check that the face is a reasonable size. If not, skip this face.
                if 2 * fs3d < self.min_real_face_size or 2 * fs3d > self.max_real_face_size or iface > 1:  #HACK: ONLY ALLOW ONE FACE
                    self.faces.pop(iface)
                    iface -= 1
                    continue

                if DESCRIPTOR == 'CALONDER':
                    self.vo.collect_descriptors(ia)
                elif DESCRIPTOR == 'SAD':
                    self.vo.collect_descriptors_sad(ia)
                else:
                    pass

                self.current_keyframes.append(0)
                self.keyframes.append(copy.copy(ia))

                self.feats_to_centers.append(
                    self.make_face_model(cen, diff, ia.kp2d))

                self.real_face_sizes_3d.append(copy.deepcopy(fs3d))
                self.feats_to_centers_3d.append(
                    self.make_face_model(cen3d, (fs3d, fs3d, fs3d), ia.kp3d))
                self.face_centers_3d.append(copy.deepcopy(cen3d))

                self.recent_good_frames.append(copy.copy(ia))
                self.recent_good_rects.append(copy.deepcopy([x, y, w, h]))
                self.recent_good_centers_3d.append(copy.deepcopy(cen3d))
                self.recent_good_motion.append([0.0] * 3)  #dx,dy,dimfacesize
                self.recent_good_motion_3d.append([0.0] * 3)

                self.same_key_rgfs.append(True)

                if DEBUG:
                    print "cen2d", cen
                    print "cen3d", self.face_centers_3d[iface]

                # End first frame

            # Later frames
            else:
                if DESCRIPTOR == 'CALONDER':
                    self.vo.collect_descriptors(ia)
                elif DESCRIPTOR == 'SAD':
                    self.vo.collect_descriptors_sad(ia)
                else:
                    pass

                done_matching = False
                bad_frame = False
                while not done_matching:

                    # Try matching to the keyframe
                    keyframe = self.keyframes[self.current_keyframes[iface]]
                    temp_match = self.vo.temporal_match(ia,
                                                        keyframe,
                                                        want_distances=True)
                    ia.matches = [(m2, m1) for (m1, m2, m3) in temp_match]
                    ia.desc_diffs = [m3 for (m1, m2, m3) in temp_match]
                    print "temp matches", temp_match
                    ia.good_matches = [
                        s < self.desc_diff_thresh for s in ia.desc_diffs
                    ]

                    n_good_matches = len([
                        m for m in ia.desc_diffs if m < self.desc_diff_thresh
                    ])

                    if DEBUG:
                        if len(keyframe.kp) < 2:
                            print "Keyframe has less than 2 kps"
                        if n_good_matches < len(keyframe.kp) / 2.0:
                            print "ngoodmatches, len key.kp, len key.kp/2", n_good_matches, len(
                                keyframe.kp), len(keyframe.kp) / 2.0

                    # Not enough matches, get a new keyframe
                    if len(keyframe.kp) < 2 or n_good_matches < len(
                            keyframe.kp) / 2.0:

                        if DEBUG:
                            print "New keyframe"

                        # Make a new face model, either from a recent good frame, or from the current image
                        if not self.same_key_rgfs[iface]:

                            if DEBUG:
                                print "centers at beginning of new keyframe"
                                print "cen2d", [
                                    self.faces[iface][0] +
                                    self.faces[iface][2] / 2.0,
                                    self.faces[iface][1] +
                                    self.faces[iface][3] / 2.0
                                ]
                                print "cen3d", self.face_centers_3d[iface]

                            matched_z_list = [
                                kp3d[2] for (kp3d, is_good) in zip(
                                    self.recent_good_frames[iface].kp3d, self.
                                    recent_good_frames[iface].good_matches)
                                if is_good
                            ]
                            if len(matched_z_list) == 0:
                                matched_z_list = [
                                    kp3d[2] for kp3d in
                                    self.recent_good_frames[iface].kp3d
                                ]
                            avgz_goodmatches = sum(matched_z_list) / len(
                                matched_z_list)
                            tokeep = [
                                math.fabs(
                                    self.recent_good_frames[iface].kp3d[i][2] -
                                    avgz_goodmatches) <
                                2.0 * self.real_face_sizes_3d[iface]
                                for i in range(
                                    len(self.recent_good_frames[iface].kp3d))
                            ]
                            kp3d_for_model = [
                                kp3d for (kp3d, tk) in zip(
                                    self.recent_good_frames[iface].kp3d,
                                    tokeep) if tk
                            ]
                            kp_for_model = [
                                kp for (kp, tk) in zip(
                                    self.recent_good_frames[iface].kp, tokeep)
                                if tk
                            ]
                            # If you're not left with enough points, just take all of them and don't worry about the depth constraints.
                            if len(kp3d_for_model) < 2:
                                kp3d_for_model = copy.deepcopy(
                                    self.recent_good_frames[iface].kp3d)
                                kp_for_model = copy.deepcopy(
                                    self.recent_good_frames[iface].kp)

                            (cen, diff) = self.rect_to_center_diff(
                                self.recent_good_rects[iface])
                            self.feats_to_centers[
                                iface] = self.make_face_model(
                                    cen, diff,
                                    [(kp0, kp1)
                                     for (kp0, kp1, kp2) in kp_for_model])

                            cen3d = self.recent_good_centers_3d[iface]
                            self.feats_to_centers_3d[
                                iface] = self.make_face_model(
                                    cen3d,
                                    [self.real_face_sizes_3d[iface]] * 3,
                                    kp3d_for_model)

                            self.keyframes[
                                self.current_keyframes[iface]] = copy.copy(
                                    self.recent_good_frames[iface])
                            self.keyframes[self.current_keyframes[
                                iface]].kp = kp_for_model
                            self.keyframes[
                                self.current_keyframes[iface]].kp2d = [
                                    (k0, k1) for (k0, k1, k2) in kp_for_model
                                ]
                            self.keyframes[self.current_keyframes[
                                iface]].kp3d = kp3d_for_model
                            self.keyframes[
                                self.current_keyframes[iface]].matches = [
                                    (i, i) for i in range(len(kp_for_model))
                                ]
                            self.keyframes[
                                self.current_keyframes[iface]].good_matches = [
                                    True
                                ] * len(kp_for_model)
                            self.keyframes[self.current_keyframes[
                                iface]].desc_diffs = [0] * len(kp_for_model)

                            if DESCRIPTOR == 'CALONDER':
                                self.vo.collect_descriptors(self.keyframes[
                                    self.current_keyframes[iface]])
                            elif DESCRIPTOR == 'SAD':
                                self.vo.collect_descriptors_sad(self.keyframes[
                                    self.current_keyframes[iface]])
                            else:
                                pass

                            self.face_centers_3d[iface] = copy.deepcopy(cen3d)
                            # Not changing the face size

                            self.current_keyframes[
                                iface] = 0  #### HACK: ONLY ONE KEYFRAME!!!

                            self.same_key_rgfs[iface] = True
                            # Don't need to change the recent good frame yet.

                            if DEBUG:
                                print "centers at end of new keyframe"
                                print "cen2d", [
                                    self.faces[iface][0] +
                                    self.faces[iface][2] / 2.0,
                                    self.faces[iface][1] +
                                    self.faces[iface][3] / 2.0
                                ]
                                print "cen3d", self.face_centers_3d[iface]

                        else:

                            # Making a new model off of the current frame but with the predicted new position.
                            # HACK: The displacement computation assumes that the robot/head is still, fix this.
                            bad_frame = True
                            #done_matching = True
                            if DEBUG:
                                print "Bad frame ", self.seq, " for face ", iface

                            (cen, diff) = self.rect_to_center_diff(
                                self.faces[iface])
                            if DEBUG:
                                print "Motion for bad frame ", self.recent_good_motion[
                                    iface], self.recent_good_motion_3d[iface]
                            new_cen = [
                                cen[0] + self.recent_good_motion[iface][0],
                                cen[1] + self.recent_good_motion[iface][1]
                            ]
                            diff = [
                                diff[0] + self.recent_good_motion[iface][2],
                                diff[1] + self.recent_good_motion[iface][2]
                            ]

                            self.faces[iface] = (new_cen[0] - diff[0],
                                                 new_cen[1] - diff[1],
                                                 2.0 * diff[0], 2.0 * diff[1])
                            (x, y, w, h) = copy.deepcopy(self.faces[iface])

                            pred_cen_3d = [
                                o + n for (o, n) in zip(
                                    self.face_centers_3d[iface],
                                    self.recent_good_motion_3d[iface])
                            ]
                            pred_cen_3d.append(
                                2.0 *
                                self.real_face_sizes_3d[iface])  #### ZMULT
                            self.get_features(ia, self.num_feats, (x, y, w, h),
                                              pred_cen_3d)
                            if not ia.kp2d:
                                break

                            if DESCRIPTOR == 'CALONDER':
                                self.vo.collect_descriptors(ia)
                            elif DESCRIPTOR == 'SAD':
                                self.vo.collect_descriptors_sad(ia)
                            else:
                                pass

                            self.keyframes[
                                self.current_keyframes[iface]] = copy.copy(ia)
                            self.current_keyframes[iface] = 0
                            (cen, diff) = self.rect_to_center_diff(
                                self.faces[iface])
                            self.feats_to_centers[
                                iface] = self.make_face_model(
                                    cen, diff, ia.kp2d)
                            self.feats_to_centers_3d[
                                iface] = self.make_face_model([
                                    pred_cen_3d[0], pred_cen_3d[1],
                                    pred_cen_3d[2]
                                ], [self.real_face_sizes_3d[iface]] * 3,
                                                              ia.kp3d)
                            self.face_centers_3d[iface] = copy.deepcopy(
                                pred_cen_3d)
                            self.same_key_rgfs[iface] = True

                    # Good matches, mark this frame as good
                    else:
                        done_matching = True

                    # END MATCHING

                # If we got enough matches for this frame, track.
                if ia.kp and ia.kp2d:

                    # Track
                    sparse_pred_list = []
                    sparse_pred_list_2d = []
                    probs = []
                    bandwidths = []
                    size_mult = 0.05  #1.0

                    for ((match1, match2),
                         score) in zip(ia.matches, ia.desc_diffs):
                        if score < self.desc_diff_thresh:
                            sparse_pred_list.append([
                                ia.kp3d[match2][i] +
                                self.feats_to_centers_3d[iface][match1][i]
                                for i in range(3)
                            ])
                            sparse_pred_list_2d.append([
                                ia.kp2d[match2][i] +
                                self.feats_to_centers[iface][match1][i]
                                for i in range(2)
                            ])
                            #probs.append(score)
                    probs = [1.0] * len(
                        sparse_pred_list_2d
                    )  # Ignore actual match scores. Uncomment line above to use the match scores.
                    bandwidths = [size_mult * self.real_face_sizes_3d[iface]
                                  ] * len(sparse_pred_list_2d)

                    (old_center,
                     old_diff) = self.rect_to_center_diff(self.faces[iface])

                    if DEBUG:
                        print "Old center 3d ", self.face_centers_3d[iface]
                        print "Old center 2d ", old_center

                    old_rect = self.faces[iface]  # For display only

                    new_center = self.mean_shift_sparse(
                        self.face_centers_3d[iface][0:3], sparse_pred_list,
                        probs, bandwidths, 10, 1.0)
                    new_center_2d = self.cam.cam2pix(new_center[0],
                                                     new_center[1],
                                                     new_center[2])
                    # The above line assumes that we're tracking the face plane center, not the center of the head sphere.
                    # If you want to track the center of the sphere instead, subtract self.real_face_sizes[iface] from the z-coord.
                    ltf = self.cam.cam2pix(
                        new_center[0] - self.real_face_sizes_3d[iface],
                        new_center[1] - self.real_face_sizes_3d[iface],
                        new_center[2])
                    rbf = self.cam.cam2pix(
                        new_center[0] + self.real_face_sizes_3d[iface],
                        new_center[1] + self.real_face_sizes_3d[iface],
                        new_center[2])
                    w = rbf[0] - ltf[0]
                    h = rbf[1] - ltf[1]

                    if DEBUG:
                        print "new center 3d ", new_center
                        print "new_center 2d ", new_center_2d

                    (nx, ny, nw, nh) = (new_center_2d[0] - (w - 1) / 2.0,
                                        new_center_2d[1] - (h - 1) / 2.0, w, h)

                    # Force the window back into the image.
                    nx += max(0, 0 - nx) + min(0, im.width - nx + nw)
                    ny += max(0, 0 - ny) + min(0, im.height - ny + nh)

                    self.faces[iface] = [nx, ny, nw, nh]
                    self.recent_good_rects[iface] = [nx, ny, nw, nh]
                    self.recent_good_centers_3d[iface] = copy.deepcopy(
                        new_center)
                    if bad_frame:
                        self.recent_good_motion[
                            iface] = self.recent_good_motion[iface]
                        self.recent_good_motion_3d[
                            iface] = self.recent_good_motion_3d[iface]
                    else:
                        self.recent_good_motion[iface] = [
                            new_center_2d[0] - old_center[0],
                            new_center_2d[1] - old_center[1],
                            ((nw - 1.0) / 2.0) - old_diff[0]
                        ]
                        self.recent_good_motion_3d[iface] = [
                            new_center[i] - self.face_centers_3d[iface][i]
                            for i in range(len(new_center))
                        ]
                    self.face_centers_3d[iface] = copy.deepcopy(new_center)
                    self.recent_good_frames[iface] = copy.copy(ia)
                    self.same_key_rgfs[iface] = False

                    if DEBUG:
                        print "motion ", self.recent_good_motion[
                            iface], self.recent_good_motion_3d[iface]
                        print "face 2d ", self.faces[iface]
                        print "face center 3d ", self.face_centers_3d[iface]

                    # Output the location of this face center in the 3D camera frame (of the left camera), and rotate
                    # the coordinates to match the robot's idea of the 3D camera frame.
                    center_uvd = (nx + (nw - 1) / 2.0, ny + (nh - 1) / 2.0,
                                  (numpy.average(ia.kp, 0))[2])
                    center_camXYZ = self.cam.pix2cam(center_uvd[0],
                                                     center_uvd[1],
                                                     center_uvd[2])
                    center_robXYZ = (center_camXYZ[2], -center_camXYZ[0],
                                     -center_camXYZ[1])

                    ########### PUBLISH the face center for the head controller to track. ########
                    if not self.usebag:
                        #stamped_point = PointStamped()
                        #(stamped_point.point.x, stamped_point.point.y, stamped_point.point.z) = center_robXYZ
                        #stamped_point.header.frame_id = "stereo"
                        #stamped_point.header.stamp = imarray.header.stamp
                        #self.pub.publish(stamped_point)
                        pm = PositionMeasurement()
                        pm.header.stamp = imarray.header.stamp
                        pm.name = "stereo_face_feature_tracker"
                        pm.object_id = -1
                        (pm.pos.x, pm.pos.y, pm.pos.z) = center_robXYZ
                        pm.header.frame_id = "stereo_link"
                        pm.reliability = 0.5
                        pm.initialization = 0
                        #pm.covariance
                        self.pub.publish(pm)

                # End later frames

            ############ DRAWING ################
            if SAVE_PICS:

                if not self.keyframes or len(self.keyframes) <= iface:
                    bigim_py = im_py
                    draw = ImageDraw.Draw(bigim_py)
                else:
                    key_im = self.keyframes[self.current_keyframes[iface]]
                    keyim_py = Image.fromstring("L", key_im.size,
                                                key_im.rawdata)
                    bigim_py = Image.new(
                        "RGB", (im_py.size[0] + key_im.size[0], im_py.size[1]))
                    bigim_py.paste(keyim_py.convert("RGB"), (0, 0))
                    bigim_py.paste(im_py, (key_im.size[0] + 1, 0))
                    draw = ImageDraw.Draw(bigim_py)

                    (x, y, w, h) = self.faces[iface]
                    draw.rectangle((x, y, x + w, y + h), outline=(0, 255, 0))
                    draw.rectangle(
                        (x + key_im.size[0], y, x + w + key_im.size[0], y + h),
                        outline=(0, 255, 0))
                    (x, y, w, h) = old_rect
                    draw.rectangle((x, y, x + w, y + h),
                                   outline=(255, 255, 255))
                    draw.rectangle(
                        (x + key_im.size[0], y, x + w + key_im.size[0], y + h),
                        outline=(255, 255, 255))

                    mstart = old_center
                    mend = (old_center[0] + self.recent_good_motion[iface][0],
                            old_center[1] + self.recent_good_motion[iface][1])
                    draw.rectangle((mstart[0] - 1, mstart[1] - 1,
                                    mstart[0] + 1, mstart[1] + 1),
                                   outline=(255, 255, 255))
                    draw.rectangle(
                        (mend[0] - 1, mend[1] - 1, mend[0] + 1, mend[1] + 1),
                        outline=(0, 255, 0))
                    draw.line(mstart + mend, fill=(255, 255, 255))

                    for (x, y) in key_im.kp2d:
                        draw_x(draw, (x, y), (1, 1), (255, 0, 0))
                    for (x, y) in ia.kp2d:
                        draw_x(draw, (x + key_im.size[0], y), (1, 1),
                               (255, 0, 0))

                    if self.seq > 0:

                        if ia.matches:
                            for ((m1, m2),
                                 score) in zip(ia.matches, ia.desc_diffs):
                                if score > self.desc_diff_thresh:
                                    color = (255, 0, 0)
                                else:
                                    color = (0, 255, 0)
                                draw.line(
                                    (key_im.kp2d[m1][0], key_im.kp2d[m1][1],
                                     ia.kp2d[m2][0] + key_im.size[0],
                                     ia.kp2d[m2][1]),
                                    fill=color)

                        for (i, (u, v)) in enumerate(sparse_pred_list_2d):
                            bscale = min(1, probs[i] / 0.01)
                            draw_x(draw, (u, v), (1, 1),
                                   (128.0 + 128.0 * bscale,
                                    128.0 + 128.0 * bscale,
                                    (1.0 - bscale) * 255.0))
                            draw_x(draw, (u + key_im.size[0], v), (1, 1),
                                   (128.0 + 128.0 * bscale,
                                    128.0 + 128.0 * bscale,
                                    (1.0 - bscale) * 255.0))

                    ####### PUBLISH 3d visualization point cloud ###################
                    if self.usebag and self.visualize:
                        cloud = PointCloud()
                        cloud.header.frame_id = "stereo"
                        cloud.header.stamp = imarray.header.stamp
                        cloud.pts = []
                        cloud.pts.append(Point())
                        (cloud.pts[0].x, cloud.pts[0].y,
                         cloud.pts[0].z) = self.face_centers_3d[iface][:3]
                        for (i, kp3d) in enumerate(ia.kp3d):
                            cloud.pts.append(Point())
                            (cloud.pts[i].x, cloud.pts[i].y,
                             cloud.pts[i].z) = kp3d

                        lp = len(cloud.pts)
                        if self.seq > 0:
                            for (i, (u, v)) in enumerate(sparse_pred_list):
                                cloud.pts[lp + i].append(Point())
                                (cloud.pts[lp + i].x, cloud.pts[lp + i].y,
                                 cloud.pts[lp + i].z) = sparse_pred_list[i][:3]

                        self.pub.publish(cloud)

                bigim_py.save("/tmp/tiff/feats%06d_%03d.tiff" %
                              (self.seq, iface))
                #END DRAWING

            # END FACE LOOP

        self.seq += 1
Ejemplo n.º 14
0
    def assembleBanner(self, name, medals, insignia):
        width, height = self.sizeBanner(name, medals, insignia)
        oheight = height

        bwidth = 4

        height = max(insignia.size[1] + 2 * bwidth, height)
        xpos = 2 * bwidth
        ypos = 2 * bwidth
        linesize = 16
        image = Image.new("RGBA", (width, height), (0, 0, 0, 0))
        draw = ImageDraw.Draw(image)
        # Draw Border

        draw.rectangle([(0, bwidth), (width, height - (bwidth + 1))],
                       fill=ImageColor.getrgb(TRIM_COLOR))
        draw.rectangle([(bwidth, 0), (width - (bwidth + 1), height)],
                       fill=ImageColor.getrgb(TRIM_COLOR))
        draw.rectangle([(bwidth, 2 * bwidth),
                        (width - (bwidth + 1), height - 2 * (bwidth + 1))],
                       fill=ImageColor.getrgb(BG_COLOR))
        draw.rectangle([(2 * bwidth, bwidth),
                        (width - 2 * (bwidth + 1), height - (bwidth + 1))],
                       fill=ImageColor.getrgb(BG_COLOR))
        # Draw Name, Rank, Kills, Deaths, KD, Favorite Weapon, Rank
        image.paste(insignia, (width - (insignia.size[0] + 2 * bwidth),
                               height / 2 - insignia.size[1] / 2), insignia)
        namewidth, nameheight = self.yoster24.getsize(name)
        maxwidth = 525 - (2 * bwidth + insignia.size[0])
        fw, fh = self.yoster12.getsize(WATERMARK)
        if oheight == 50:
            #if it's just one line
            for medalset in medals:
                image.paste(medalset, (xpos, ypos), medalset)
                xpos += medalset.size[0] + 4

            if self.gold:
                draw.text((xpos, ypos),
                          name,
                          font=self.yoster24,
                          fill=GOLD_SHADOW)
                draw.text((xpos - 1, ypos - 1),
                          name,
                          font=self.yoster24,
                          fill=GOLD_COLOR)

            else:
                draw.text((xpos, ypos),
                          name,
                          font=self.yoster24,
                          fill=(155, 155, 155))
                draw.text((xpos - 1, ypos - 1),
                          name,
                          font=self.yoster24,
                          fill=(0xFF, 0xFF, 0xFF))

            draw.text((xpos + 2, height - 16),
                      WATERMARK,
                      font=self.yoster12,
                      fill=WATERMARK_COLOR)

        else:
            #if it's multiline
            ypos += linesize
            medalwidth = reduce(lambda x, y: x + y.size[0], medals, 0)

            if self.gold:
                draw.text((((width / 2) - (namewidth / 2)) + 1, 4 + 1),
                          name,
                          font=self.yoster24,
                          fill=GOLD_SHADOW)
                draw.text(((width / 2) - (namewidth / 2), 4),
                          name,
                          font=self.yoster24,
                          fill=GOLD_COLOR)

            else:
                draw.text((((width / 2) - (namewidth / 2)) + 1, 4 + 1),
                          name,
                          font=self.yoster24,
                          fill=(155, 155, 155))
                draw.text(((width / 2) - (namewidth / 2), 4),
                          name,
                          font=self.yoster24,
                          fill=(0xFF, 0xFF, 0xFF))

            #draw.text(,name,font=self.yoster24,fill=(155,155,155)) # text shadow
            #draw.text(,4),name,font=self.yoster24)
            ypos += 4
            spacing = 8
            xpos = bwidth + spacing
            for medalset in medals:
                if xpos + medalset.size[0] > maxwidth:
                    ypos += linesize + 2
                    xpos = bwidth
                image.paste(medalset, (xpos, ypos), medalset)

                xpos += medalset.size[0] + spacing
            draw.text(((width / 2) - (fw / 2), height - 16),
                      WATERMARK,
                      font=self.yoster12,
                      fill=WATERMARK_COLOR)

        #draw.text((14,height-16),"Dr. Frink's FUNHOUSE",font=yoster12,fill=(136,0,0))
        #draw.text((width-(fw+14),height-16),WATERMARK,font=yoster12,fill=(136,0,0))

        return image
Ejemplo n.º 15
0
import ariturtle
import math
import copy
import Image, ImageDraw
import sys
usrS = int(raw_input('Enter Image Size: '))
depth = int(raw_input('Enter Recursion Depth: '))

img = Image.new('RGB', (usrS, usrS))
imageSize = img.size
draw = ImageDraw.Draw(img)

sys.setrecursionlimit(1000)

global size


def drawBasic(turtle, level, angle=90):

    global size

    if level == 0:
        return

    ariturtle.turn(turtle, angle)
    drawBasic(turtle, level - 1, -angle)

    ariturtle.move(turtle, size)
    ariturtle.turn(turtle, -angle)
    drawBasic(turtle, level - 1, angle)
Ejemplo n.º 16
0
def coordToMask(polygon, dims):
    img = Image.new('L', (dims[0], dims[1]), 0)
    ImageDraw.Draw(img).polygon(polygon, outline=1, fill=1)
    return img
Ejemplo n.º 17
0
    def run_calibration(self,
                        calibration_points,
                        move_duration=1.5,
                        shuffle=True,
                        start_key='space',
                        decision_key='space',
                        text_color='white',
                        enable_mouse=False):
        """
        Run calibration.
        
        :param calibration_points: List of position of calibration points.
        :param float move_duration: Duration of animation of calibration target.
            Unit is second.  Default value is 1.5.
        :param bool shuffle: If True, order of calibration points is shuffled.
            Otherwise, calibration target moves in the order of calibration_points.
            Default value is True.
        :param str start_key: Name of key to start calibration procedure.
            If None, calibration starts immediately afte this method is called.
            Default value is 'space'.
        :param str decision_key: Name of key to accept/retry calibration.
            Default value is 'space'.
        :param text_color: Color of message text. Default value is 'white'
        :param bool enable_mouse: If True, mouse operation is enabled.
            Default value is False.
        """

        if self.eyetracker is None:
            raise RuntimeError('Eyetracker is not found.')

        if not (2 <= len(calibration_points) <= 9):
            raise ValueError('Calibration points must be 2~9')

        if enable_mouse:
            mouse = psychopy.event.Mouse(visible=False, win=self.win)

        img = Image.new('RGBA', tuple(self.win.size))
        img_draw = ImageDraw.Draw(img)

        result_img = psychopy.visual.SimpleImageStim(self.win,
                                                     img,
                                                     autoLog=False)
        result_msg = psychopy.visual.TextStim(self.win,
                                              pos=(0, -self.win.size[1] / 4),
                                              color=text_color,
                                              units='pix',
                                              autoLog=False)
        remove_marker = psychopy.visual.Circle(
            self.win,
            radius=self.calibration_target_dot.radius * 5,
            fillColor='black',
            lineColor='white',
            lineWidth=1,
            autoLog=False)
        if self.win.units == 'norm':  # fix oval
            remove_marker.setSize(
                [float(self.win.size[1]) / self.win.size[0], 1.0])
            remove_marker.setSize(
                [float(self.win.size[1]) / self.win.size[0], 1.0])

        self.calibration.enter_calibration_mode()

        self.move_duration = move_duration
        self.original_calibration_points = calibration_points[:]
        self.retry_points = list(range(len(
            self.original_calibration_points)))  # set all points

        in_calibration_loop = True
        while in_calibration_loop:
            self.calibration_points = []
            for i in range(len(self.original_calibration_points)):
                if i in self.retry_points:
                    self.calibration_points.append(
                        self.original_calibration_points[i])

            if shuffle:
                np.random.shuffle(self.calibration_points)

            if start_key is not None or enable_mouse:
                waitkey = True
                if start_key is not None:
                    if enable_mouse:
                        result_msg.setText(
                            'Press {} or click left button to start calibration'
                            .format(start_key))
                    else:
                        result_msg.setText(
                            'Press {} to start calibration'.format(start_key))
                else:  # enable_mouse==True
                    result_msg.setText(
                        'Click left button to start calibration')
                while waitkey:
                    for key in psychopy.event.getKeys():
                        if key == start_key:
                            waitkey = False

                    if enable_mouse and mouse.getPressed()[0]:
                        waitkey = False

                    result_msg.draw()
                    self.win.flip()
            else:
                self.win.flip()

            self.update_calibration()

            calibration_result = self.calibration.compute_and_apply()

            self.win.flip()

            img_draw.rectangle(((0, 0), tuple(self.win.size)),
                               fill=(0, 0, 0, 0))
            if calibration_result.status == tobii_research.CALIBRATION_STATUS_FAILURE:
                #computeCalibration failed.
                pass
            else:
                if len(calibration_result.calibration_points) == 0:
                    pass
                else:
                    for calibration_point in calibration_result.calibration_points:
                        p = calibration_point.position_on_display_area
                        for calibration_sample in calibration_point.calibration_samples:
                            lp = calibration_sample.left_eye.position_on_display_area
                            rp = calibration_sample.right_eye.position_on_display_area
                            if calibration_sample.left_eye.validity == tobii_research.VALIDITY_VALID_AND_USED:
                                img_draw.line(((p[0] * self.win.size[0],
                                                p[1] * self.win.size[1]),
                                               (lp[0] * self.win.size[0],
                                                lp[1] * self.win.size[1])),
                                              fill=(0, 255, 0, 255))
                            if calibration_sample.right_eye.validity == tobii_research.VALIDITY_VALID_AND_USED:
                                img_draw.line(((p[0] * self.win.size[0],
                                                p[1] * self.win.size[1]),
                                               (rp[0] * self.win.size[0],
                                                rp[1] * self.win.size[1])),
                                              fill=(255, 0, 0, 255))
                        img_draw.ellipse(((p[0] * self.win.size[0] - 3,
                                           p[1] * self.win.size[1] - 3),
                                          (p[0] * self.win.size[0] + 3,
                                           p[1] * self.win.size[1] + 3)),
                                         outline=(0, 0, 0, 255))

            if enable_mouse:
                result_msg.setText(
                    'Accept/Retry: {} or right-click\nSelect recalibration points: 0-9 key or left-click\nAbort: esc'
                    .format(decision_key))
            else:
                result_msg.setText(
                    'Accept/Retry: {}\nSelect recalibration points: 0-9 key\nAbort: esc'
                    .format(decision_key))
            result_img.setImage(img)

            waitkey = True
            self.retry_points = []
            if enable_mouse:
                mouse.setVisible(True)
            while waitkey:
                for key in psychopy.event.getKeys():
                    if key in [decision_key, 'escape']:
                        waitkey = False
                    elif key in ['0', 'num_0']:
                        if len(self.retry_points) == 0:
                            self.retry_points = list(
                                range(len(self.original_calibration_points)))
                        else:
                            self.retry_points = []
                    elif key in self.key_index_dict:
                        key_index = self.key_index_dict[key]
                        if key_index < len(self.original_calibration_points):
                            if key_index in self.retry_points:
                                self.retry_points.remove(key_index)
                            else:
                                self.retry_points.append(key_index)
                if enable_mouse:
                    pressed = mouse.getPressed()
                    if pressed[2]:  # right click
                        key = decision_key
                        waitkey = False
                    elif pressed[0]:  # left click
                        mouse_pos = mouse.getPos()
                        for key_index in range(
                                len(self.original_calibration_points)):
                            p = self.original_calibration_points[key_index]
                            if np.linalg.norm([
                                    mouse_pos[0] - p[0], mouse_pos[1] - p[1]
                            ]) < self.calibration_target_dot.radius * 5:
                                if key_index in self.retry_points:
                                    self.retry_points.remove(key_index)
                                else:
                                    self.retry_points.append(key_index)
                                time.sleep(0.2)
                                break
                result_img.draw()
                if len(self.retry_points) > 0:
                    for index in self.retry_points:
                        if index > len(self.original_calibration_points):
                            self.retry_points.remove(index)
                        remove_marker.setPos(
                            self.original_calibration_points[index])
                        remove_marker.draw()
                result_msg.draw()
                self.win.flip()

            if key == decision_key:
                if len(self.retry_points) == 0:
                    retval = 'accept'
                    in_calibration_loop = False
                else:  #retry
                    for point_index in self.retry_points:
                        x, y = self.get_tobii_pos(
                            self.original_calibration_points[point_index])
                        self.calibration.discard_data(x, y)
            elif key == 'escape':
                retval = 'abort'
                in_calibration_loop = False
            else:
                raise RuntimeError('Calibration: Invalid key')

            if enable_mouse:
                mouse.setVisible(False)

        self.calibration.leave_calibration_mode()

        if enable_mouse:
            mouse.setVisible(False)

        return retval
Ejemplo n.º 18
0
def plot_rgb_histogram(img):
    # RGB Hitogram
    # This script will create a histogram image based on the RGB content of
    # an image. It uses PIL to do most of the donkey work but then we just
    # draw a pretty graph out of it.
    #
    # May 2009,  Scott McDonough, www.scottmcdonough.co.uk
    #

    import Image, ImageDraw

    imagepath = "mZXN_1979"  # The image to build the histogram of

    histHeight = 120  # Height of the histogram
    histWidth = 256  # Width of the histogram
    multiplerValue = 1  # The multiplier value basically increases
    # the histogram height so that love values
    # are easier to see, this in effect chops off
    # the top of the histogram.
    showFstopLines = True  # True/False to hide outline
    fStopLines = 5

    # Colours to be used
    backgroundColor = (51, 51, 51)  # Background color
    lineColor = (102, 102, 102)  # Line color of fStop Markers
    red = (255, 60, 60)  # Color for the red lines
    green = (51, 204, 51)  # Color for the green lines
    blue = (0, 102, 255)  # Color for the blue lines

    ##################################################################################

    #img = Image.open(imagepath)
    hist = img.histogram()
    histMax = max(hist)  # comon color
    xScale = float((histWidth)) / len(hist)  # xScaling
    yScale = float((histHeight)) / histMax  # yScaling

    im = Image.new("RGBA", ((histWidth * multiplerValue),
                            (histHeight * multiplerValue)), backgroundColor)
    draw = ImageDraw.Draw(im)

    # Draw Outline is required
    if showFstopLines:
        xmarker = histWidth / fStopLines
        x = 0
        for i in range(1, fStopLines + 1):
            draw.line((x, 0, x, histHeight), fill=lineColor)
            x += xmarker
        draw.line((histWidth - 1, 0, histWidth - 1, 200), fill=lineColor)
        draw.line((0, 0, 0, histHeight), fill=lineColor)

    # Draw the RGB histogram lines
    x = 0
    c = 0
    for i in hist:
        if int(i) == 0: pass
        else:
            color = red
            if c > 255: color = green
            if c > 511: color = blue
            draw.line((x, histHeight, x, histHeight - (i * yScale)),
                      fill=color)
        if x > 255: x = 0
        else: x += 1
        c += 1

    # Now save and show the histogram
    im.save('histogram.png', 'PNG')
    #im.show()
    return im
Ejemplo n.º 19
0
            + gif)
        #print gifDirectory

        gifSpeed = os.listdir(
            "/home/pi/Documents/LEDMatrix/rpi-rgb-led-matrix-master/gifSpeed"
        )[0]

        hexa = os.listdir(
            "/home/pi/Documents/LEDMatrix/rpi-rgb-led-matrix-master/Color")[0]

        curDate = datetime.datetime.now().strftime("%H:%M")

        image = Image.new("1",
                          (30, 12))  # Can be larger than matrix if wanted!!
        image = image.convert("RGBA")
        draw = ImageDraw.Draw(image)  # Declare Draw instance before prims

        draw.text((0, 0), curDate, fill=hex_to_rgb(hexa))

        #       draw.text((0, 0), curDate, fill=(int(float(r)), int(float(g)), int(float(b))))
        #  matrix.Clear()

        matrix.SetImage(image.im.id, 0, 0)

        for n in range(1, len(gifDirectory) + 1):
            pict = Image.open(
                "/home/pi/Documents/LEDMatrix/rpi-rgb-led-matrix-master/gifDirectory/"
                + gif + "/" + str(n) + ".jpg")
            pict.load()  # Must do this before SetImage() calls
            matrix.SetImage(pict.im.id, 31, 0)
            time.sleep(gifSpeed * 0.01)
Ejemplo n.º 20
0
    def add_latlon_labels(self, **kwargs):
        """Add lat/lon labels along upper and left side

        Compute step of lables.
        Get lat/lon for these labels from latGrid, lonGrid
        Print lables to PIL in white.

        **Modifies:** self.pilImg (PIL image), added lat/lon labels

        Parameters
        ----------
        latGrid : numpy array
            array with values of latitudes
        lonGrid : numpy array
            array with values of longitudes
        lonTicks : int or list
            number of lines to draw
            or locations of gridlines
        latTicks : int or list
            number of lines to draw
            or locations of gridlines
        **kwargs : dict
            Any of Figure parameters

        """
        # modify default values
        self._set_defaults(kwargs)

        # test availability of grids
        if (self.latGrid is None or self.lonGrid is None):
            return

        draw = ImageDraw.Draw(self.pilImg)
        font = ImageFont.truetype(self.fontFileName, self.fontSize)

        # get vectors with ticks based on input
        latTicks = self._get_auto_ticks(self.latTicks, self.latGrid)
        lonTicks = self._get_auto_ticks(self.lonTicks, self.lonGrid)

        # get corresponding lons from upper edge and lats from left edge
        lonTicksIdx = self._get_tick_index_from_grid(lonTicks, self.lonGrid, 1,
                                                     self.lonGrid.shape[1])
        latTicksIdx = self._get_tick_index_from_grid(latTicks, self.latGrid,
                                                     self.lonGrid.shape[0], 1)

        # draw lons
        lonsOffset = self.lonGrid.shape[1] / len(lonTicksIdx) / 8.
        for lonTickIdx in lonTicksIdx:
            lon = self.lonGrid[0, lonTickIdx]
            draw.text((lonTickIdx + lonsOffset, 0),
                      '%4.2f' % lon,
                      fill=255,
                      font=font)

        # draw lats
        latsOffset = self.latGrid.shape[0] / len(latTicksIdx) / 8.
        for latTickIdx in latTicksIdx:
            lat = self.latGrid[latTickIdx, 0]
            draw.text((0, latTickIdx + latsOffset),
                      '%4.2f' % lat,
                      fill=255,
                      font=font)
Ejemplo n.º 21
0
def fill_bbs(im, bbs, color=255):
	draw = ImageDraw.Draw(im)
	for bb in bbs:
		draw.rectangle(bb, fill=color)
Ejemplo n.º 22
0
def drawOval(oval, orig, action):
    img = Image.new('L', (mapSize * 2, mapSize))
    draw = ImageDraw.Draw(img)
    draw.ellipse(oval, fill=action[1])
    del draw
    return action[0](orig, img)
Ejemplo n.º 23
0
#-*- coding: utf-8 -*-
from __future__ import unicode_literals
import Image
import ImageDraw
import time
import ImageFont
from rgbmatrix import Adafruit_RGBmatrix

# Rows and chain length are both required parameters:
matrix = Adafruit_RGBmatrix(32, 4)
font = ImageFont.load_default()
font = ImageFont.truetype("DejaVuSerif.ttf", size=14)

text1 = "Reading status"
img = Image.new('RGB', (128, 32))
d = ImageDraw.Draw(img)
d.text((0, 0), text1, fill=(0, 200, 200), font=font)
matrix.SetImage(img.im.id, 0, 0)

time.sleep(0.2)
text2 = "."
img = Image.new('RGB', (128, 32))
d = ImageDraw.Draw(img)
d.text((0, 0), text2, fill=(0, 200, 200), font=font)

for m in range(1, 6, 1):
    for n in range(106, 120, 3):
        matrix.SetImage(img.im.id, n, 0)
        time.sleep(0.3)

time.sleep(2)
Ejemplo n.º 24
0
def update(epd):

    # EPD 2 inch 13 b HAT is rotated 90 clockwize and does not support partial update
    # But has amazing 2 colors
    print "drawing status"
    width = epd2in13b.EPD_HEIGHT
    height = epd2in13b.EPD_WIDTH
    top = 2
    fill_color = 0
    xt = 70
    xc = 120
    xc2 = 164

    while True:
        frame_black = Image.new('1', (width, height), 255)
        frame_red = Image.new('1', (width, height), 255)

        pihole_logo_top = Image.open('pihole-bw-80-top.bmp')
        pihole_logo_bottom = Image.open('pihole-bw-80-bottom.bmp')
        # pihole_logo = Image.open('monocolo    r.bmp')

        font = ImageFont.truetype(
            '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf', 10)
        font_bold = ImageFont.truetype(
            '/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf', 11)
        font_title = ImageFont.truetype(
            '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf', 11)
        font_title_bold = ImageFont.truetype(
            '/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf', 11)
        font_debug = ImageFont.truetype(
            '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf', 8)

        # font = ImageFont.truetype('slkscr.ttf', 15)
        draw_black = ImageDraw.Draw(frame_black)

        draw_black.rectangle((0, 0, width, height), outline=0, fill=None)

        ip = subprocess.check_output("hostname -I | cut -d' ' -f1",
                                     shell=True).strip()
        print "ip:", ip
        host = subprocess.check_output("hostname",
                                       shell=True).strip() + ".local"
        print "host:", host
        mem_usage = subprocess.check_output(dedent("""
            free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'
            """).strip(),
                                            shell=True).replace("Mem: ", "")
        print "memory usage:", mem_usage
        disk = subprocess.check_output(dedent("""
            df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'
            """).strip(),
                                       shell=True).replace("Disk: ", "")
        print "disk:", disk

        try:
            r = requests.get(api_url)
            data = json.loads(r.text)
            dnsqueries = data['dns_queries_today']
            adsblocked = data['ads_blocked_today']
            clients = data['unique_clients']
        except KeyError:
            time.sleep(1)
            continue

        frame_black.paste(pihole_logo_top, (-8, 2))
        frame_red.paste(pihole_logo_bottom, (-8, 2))
        draw_red = ImageDraw.Draw(frame_red)
        draw_red.text((10, height - 21),
                      "Pi",
                      font=font_title,
                      fill=fill_color)
        draw_red.text((23, height - 21),
                      "-hole",
                      font=font_title_bold,
                      fill=fill_color)

        draw_black.text((xt, top + 0),
                        "HOST: ",
                        font=font_bold,
                        fill=fill_color)
        draw_black.text((xc, top + 0), host, font=font, fill=fill_color)
        draw_black.text((xt, top + 15),
                        "IP: ",
                        font=font_bold,
                        fill=fill_color)
        draw_black.text((xc, top + 15), str(ip), font=font, fill=fill_color)
        draw_black.text((xt, top + 30),
                        "Mem:",
                        font=font_bold,
                        fill=fill_color)
        draw_black.text((xc, top + 30),
                        str(mem_usage),
                        font=font,
                        fill=fill_color)
        draw_black.text((xt, top + 45),
                        "Disk:",
                        font=font_bold,
                        fill=fill_color)
        draw_black.text((xc, top + 45), str(disk), font=font, fill=fill_color)
        draw_black.text((xt, top + 60),
                        "Ads Blocked: ",
                        font=font_bold,
                        fill=fill_color)
        draw_black.text((xc2, top + 60),
                        str(adsblocked),
                        font=font,
                        fill=fill_color)
        draw_black.text((xt, top + 75),
                        "Clients:",
                        font=font_bold,
                        fill=fill_color)
        draw_black.text((xc2, top + 75),
                        str(clients),
                        font=font,
                        fill=fill_color)
        draw_black.text((xt, top + 90),
                        "DNS Queries: ",
                        font=font_bold,
                        fill=fill_color)
        draw_black.text((xc2, top + 90),
                        str(dnsqueries),
                        font=font,
                        fill=fill_color)

        draw_black.text((14, height - 10), u"↻: ", font=font, fill=fill_color)
        draw_black.text((24, height - 8),
                        strftime("%H:%M", gmtime()),
                        font=font_debug,
                        fill=fill_color)

        epd.display_frame(
            epd.get_frame_buffer(frame_black.transpose(PIL.Image.ROTATE_90)),
            epd.get_frame_buffer(frame_red.transpose(PIL.Image.ROTATE_90)))
        sleep_sec = 10 * 60
        print "sleeping {0} sec ({1} min) at {1}".format(
            sleep_sec, sleep_sec / 60, strftime("%H:%M", gmtime()))
        epd.sleep()
        epd.delay_ms(sleep_sec * 1000)
        # awakening the display
        epd.init()
Ejemplo n.º 25
0
    def makeGeometry(self):
        # parse input file and plot enrichments and gad percents
        print 'parsing casmo input...'
        logfile = open(self.input_file, 'r').readlines()
        self.pin_type = numpy.zeros(shape=(10, 10))
        self.pin_num = numpy.zeros(shape=(10, 10))
        counter = 0
        for line in logfile:
            if 'LFU' in line:
                line_num = 0
                for i in range(counter + 1, counter + 11):
                    char_num = 0
                    for j in range(0, line_num + 1):
                        if logfile[i][char_num + 1] == ' ':
                            self.pin_type[line_num,
                                          j] = float(logfile[i][char_num])
                            char_num += 2
                        else:
                            self.pin_type[line_num,
                                          j] = float(logfile[i][char_num] +
                                                     logfile[i][char_num + 1])
                            char_num += 3
                    line_num += 1

            if 'LPI' in line:
                line_num = 0
                for i in range(counter + 1, counter + 11):
                    char_num = 0
                    for j in range(0, line_num + 1):
                        self.pin_num[line_num, j] = float(logfile[i][char_num])
                        char_num += 2
                    line_num += 1

            counter += 1

        # fill in empty pin_types nad pin_nums
        for row in range(0, 10):
            for col in range(row, 10):
                self.pin_type[row, col] = self.pin_type[col, row]
                self.pin_num[row, col] = self.pin_num[col, row]
        '''
            This portion of the code parses the 'bwr.inp' input file for casmo to find the number of each pin type,
            the enrichment for each pin type. It uses this information to compute the total cost for the BWR fuel
            bundle represented by the casmo input file using current fuel costs from the UxC website.
            '''

        # parse bwr.inp and find the ids Gd and non-Gd pins
        logfile = open(self.input_file, "r").readlines()
        start_pins = 'FUE'
        end_pins = 'LFU'
        Gd_pin = '64016='

        # Dictionaries of pin IDs (keys) to uranium enrichments (values)
        self.non_Gd_pin_IDs_to_enr = {}
        self.Gd_pin_IDs_to_enr = {}

        # Dictionaries of pin IDs (keys) to pin quantities (values)
        self.non_Gd_pin_IDs_to_qty = {}
        self.Gd_pin_IDs_to_qty = {}
        self.pin_IDs_to_gad = {}

        line_counter = 0

        for line in logfile:
            if start_pins in line:

                while start_pins in line:
                    if Gd_pin in line:
                        # First set the number of this given pin to zero - count pins on next loop in script
                        self.Gd_pin_IDs_to_qty[(int(
                            logfile[line_counter].split()[1]))] = 0
                        # Next set the enrichment for this pin type
                        self.Gd_pin_IDs_to_enr[(int(
                            logfile[line_counter].split()[1]))] = float(
                                logfile[line_counter].split()[2]
                                [5:len(logfile[line_counter].split()[2])])
                        # Next set the gad concentration for this pin type
                        self.pin_IDs_to_gad[(int(
                            logfile[line_counter].split()[1]))] = float(
                                logfile[line_counter].split()[3][6:8])
                    else:
                        # First set number of this given pin to zero - count pins on next loop in script
                        self.non_Gd_pin_IDs_to_qty[(int(
                            logfile[line_counter].split()[1]))] = 0
                        # Next set the enrichment for this pin type
                        self.non_Gd_pin_IDs_to_enr[(int(
                            logfile[line_counter].split()[1]))] = float(
                                logfile[line_counter].split()[2]
                                [5:len(logfile[line_counter].split()[2])])
                        # Next set the gad concentration for this pin type
                        self.pin_IDs_to_gad[(int(
                            logfile[line_counter].split()[1]))] = 0.0

                    line_counter += 1
                    line = logfile[line_counter]

                break

            line_counter += 1

        # parse bwr.inp and find the quantity of each pin type in the geometry
        logfile = open(self.input_file, "r").readlines()
        start_geometry = 'LFU'
        end_geometry = 'DEP'
        num_non_Gd_pins = 0
        num_Gd_pins = 0
        line_counter = 0

        for line in logfile:
            if start_geometry in line:

                line_counter += 1
                line = logfile[line_counter]

                while end_geometry not in line:
                    pin_IDs = logfile[line_counter].split()

                    for id in pin_IDs:
                        if int(id) in self.Gd_pin_IDs_to_qty.iterkeys():
                            self.Gd_pin_IDs_to_qty[int(id)] += 1
                            num_Gd_pins += 1
                        else:
                            self.non_Gd_pin_IDs_to_qty[int(id)] += 1
                            num_non_Gd_pins += 1

                    line_counter += 1
                    line = logfile[line_counter]

                break

            line_counter += 1

        # plot enrichments and gad conc.
        self.pin_enr = numpy.zeros(shape=(10, 10))
        self.pin_gad = numpy.zeros(shape=(10, 10))
        for row in range(0, 10):
            for col in range(0, 10):
                self.pin_gad[row, col] = self.pin_IDs_to_gad[int(
                    self.pin_type[row, col])]
                if self.pin_gad[row, col] == 0:
                    self.pin_enr[row, col] = self.non_Gd_pin_IDs_to_enr[int(
                        self.pin_type[row, col])]
                else:
                    self.pin_enr[row, col] = self.Gd_pin_IDs_to_enr[int(
                        self.pin_type[row, col])]

        # create array of normalized pin powers to plot
        gad_max = 10
        enr_max = 4.9

        self.pin_enr[3, 5] = 0.0
        self.pin_enr[4, 5] = 0.0
        self.pin_enr[3, 6] = 0.0
        self.pin_enr[4, 6] = 0.0
        self.pin_enr[5, 3] = 0.0
        self.pin_enr[5, 4] = 0.0
        self.pin_enr[6, 3] = 0.0
        self.pin_enr[6, 4] = 0.0

        pin_enr_draw = self.pin_enr / enr_max
        pin_gad_draw = self.pin_gad / gad_max

        # create image
        img_enr = Image.new('RGB', (1000, 1000), 'white')
        img_gad = Image.new('RGB', (1000, 1000), 'white')
        draw_enr = ImageDraw.Draw(img_enr)
        draw_gad = ImageDraw.Draw(img_gad)

        for i in range(0, 10):
            for j in range(0, 10):

                # get color for enr pins
                if (pin_enr_draw[i, j] <= 1.0 / 3.0):
                    red_enr = 0.0
                    green_enr = 3.0 * pin_gad_draw[i, j]
                    blue_enr = 1.0
                elif (pin_enr_draw[i, j] <= 2.0 / 3.0):
                    red_enr = 3.0 * pin_enr_draw[i, j] - 1.0
                    green_enr = 1.0
                    blue_enr = -3.0 * pin_enr_draw[i, j] + 2.0
                else:
                    red_enr = 1.0
                    green_enr = -3.0 * pin_enr_draw[i, j] + 3.0
                    blue_enr = 0.0

                # get color for gad pins
                if (pin_gad_draw[i, j] <= 1.0 / 3.0):
                    red_gad = 0.0
                    green_gad = 3.0 * pin_gad_draw[i, j]
                    blue_gad = 1.0
                elif (pin_gad_draw[i, j] <= 2.0 / 3.0):
                    red_gad = 3.0 * pin_gad_draw[i, j] - 1.0
                    green_gad = 1.0
                    blue_gad = -3.0 * pin_gad_draw[i, j] + 2.0
                else:
                    red_gad = 1.0
                    green_gad = -3.0 * pin_gad_draw[i, j] + 3.0
                    blue_gad = 0.0

                # convert color to RGB triplet
                red_enr = int(255 * red_enr)
                green_enr = int(255 * green_enr)
                blue_enr = int(255 * blue_enr)

                # convert color to RGB triplet
                red_gad = int(255 * red_gad)
                green_gad = int(255 * green_gad)
                blue_gad = int(255 * blue_gad)

                # draw pin and pin power
                draw_enr.rectangle(
                    [i * 100, j * 100, (i + 1) * 100,
                     (j + 1) * 100], (red_enr, green_enr, blue_enr))
                draw_gad.rectangle(
                    [i * 100, j * 100, (i + 1) * 100,
                     (j + 1) * 100], (red_gad, green_gad, blue_gad))
                draw_enr.text([i * 100 + 35, j * 100 + 40],
                              str(self.pin_enr[i, j]), (0, 0, 0),
                              font=self.font)
                draw_gad.text([i * 100 + 35, j * 100 + 40],
                              str(self.pin_gad[i, j]), (0, 0, 0),
                              font=self.font)

        # save image
        img_enr.save('enr.png')
        img_gad.save('gad.png')
Ejemplo n.º 26
0
 def __init__(self, image, size=None, color=None):
     if not hasattr(image, "im"):
         image = Image.new(image, size, color)
     self.draw = ImageDraw.Draw(image)
     self.image = image
     self.transform = None
Ejemplo n.º 27
0
    def parseOutput(self):

        print 'parsing casmo output...'
        # parse output file and make array of pin powers
        logfile = open("bwr.out", "r").readlines()
        summary = 'C A S M O - 4     S U M M A R Y'
        self.powers = numpy.zeros(shape=(10, 10))
        counter = 0
        for line in logfile:
            if summary in line:
                burnup_str = 'burnup = ' + logfile[counter +
                                                   1].split()[2] + ' MWD / kg'
                keff_str = 'keff = ' + logfile[counter + 1].split()[6]
                peak_power_str = 'peak power = ' + logfile[counter +
                                                           4].split()[6]
                line_num = 0
                for i in range(counter + 5, counter + 15):
                    char_start = 2
                    for j in range(0, line_num + 1):
                        self.powers[line_num,
                                    j] = float(logfile[i][char_start] +
                                               logfile[i][char_start + 1] +
                                               logfile[i][char_start + 2] +
                                               logfile[i][char_start + 3] +
                                               logfile[i][char_start + 4])
                        char_start += 7
                    line_num += 1

                # fill in empty pin powers
                for row in range(0, 10):
                    for col in range(row, 10):
                        self.powers[row, col] = self.powers[col, row]

                # create array of normalized pin powers to plot
                pmax = numpy.max(self.powers)
                powers_draw = self.powers / pmax

                # create image
                img = Image.new('RGB', (1000, 1000), 'white')
                draw = ImageDraw.Draw(img)

                for i in range(0, 10):
                    for j in range(0, 10):

                        # get color
                        if (powers_draw[i, j] <= 1.0 / 3.0):
                            red = 0.0
                            green = 3.0 * powers_draw[i, j]
                            blue = 1.0
                        elif (powers_draw[i, j] <= 2.0 / 3.0):
                            red = 3.0 * powers_draw[i, j] - 1.0
                            green = 1.0
                            blue = -3.0 * powers_draw[i, j] + 2.0
                        else:
                            red = 1.0
                            green = -3.0 * powers_draw[i, j] + 3.0
                            blue = 0.0

                        # convert color to RGB triplet
                        red = int(255 * red)
                        green = int(255 * green)
                        blue = int(255 * blue)

                        # draw pin and pin power
                        draw.rectangle(
                            [i * 100, j * 100, (i + 1) * 100,
                             (j + 1) * 100], (red, green, blue))
                        draw.text([i * 100 + 25, j * 100 + 40],
                                  str(self.powers[i, j]), (0, 0, 0),
                                  font=self.font)

                # save image
                sum_str = burnup_str + '  ' + keff_str + '  ' + peak_power_str
                draw.text([250, 5], sum_str, font=self.font)
                if float(logfile[counter + 1].split()[2]) / 10 < 1.0:
                    img_str = 'pin_powers0' + logfile[counter +
                                                      1].split()[2] + '.png'
                else:
                    img_str = 'pin_powers' + logfile[counter +
                                                     1].split()[2] + '.png'
                img.save(img_str)

            counter += 1
Ejemplo n.º 28
0
 def clear(self):
     self.drawing_area.delete("all")
     self.image=Image.new("RGB",(200,200),(255,255,255))
     self.draw=ImageDraw.Draw(self.image)
Ejemplo n.º 29
0
  def makemap(self):
    sizex=256*(abs(self.bound2.x-self.bound1.x)+1)
    sizey=256*(abs(self.bound2.y-self.bound1.y)+1)
    size=(sizex,sizey)
    back=Image.new("RGB",size)
    draw=ImageDraw.Draw(back)
    for x in range(self.bound1.x,self.bound2.x+1):
      for y in range(self.bound1.y,self.bound2.y+1):
        for layer in self.layers:
          f=open(layer+"/"+str(self.zoom)+"/"+str(x)+"/"+str(y)+".png")
          ol=Image.open(f) 
          posx=x/self.bound1.x*sizex
          posy=x/self.bound1.x*sizex
          #ol.convert("RGBA")
          back.paste(ol,((x-self.bound1.x)*256,(y-self.bound1.y)*256),ol)
          f.close()
    #for label in self.labels:
    for x in self.label:
      posx=x[2][0]
      posy=x[2][1]
      bd=getTile(self.zoom,posx,posy)
      posxx=(bd.x-self.bound1.x)*256+int(bd.xpx)
      posyy=(bd.y-self.bound1.y)*256+int(bd.ypx)
      if x[0]=="city":
        font = ImageFont.truetype("DejaVuSans-Bold.ttf", 7+pow(self.zoom-7,2)*2)
        coef=self.zoom/2
        draw.polygon(((posxx+coef,posyy+coef),(posxx+coef,posyy-coef),(posxx-coef,posyy-coef),(posxx-coef,posyy+coef)),fill=(255,0,0,255))
        w, h = draw.textsize(x[1],font=font)
        draw.text((posxx-w/2,posyy-h-coef),x[1].decode("utf8"),(0,0,0,255),font=font)
      if x[0]=="town":
        font = ImageFont.truetype("DejaVuSans.ttf", 8+pow(self.zoom-8,2))
        coef=self.zoom/4
        draw.polygon(((posxx+coef,posyy+coef),(posxx+coef,posyy-coef),(posxx-coef,posyy-coef),(posxx-coef,posyy+coef)),fill=(255,129,235,255))
        w, h = draw.textsize(x[1],font=font)
        draw.text((posxx-w/2,posyy-h-coef),x[1].decode("utf8"),(0,0,0,255),font=font)
      if x[0]=="village":
        font = ImageFont.truetype("DejaVuSans.ttf", 10+pow(self.zoom-10,2))
        coef=self.zoom/8
        draw.polygon(((posxx+coef,posyy+coef),(posxx+coef,posyy-coef),(posxx-coef,posyy-coef),(posxx-coef,posyy+coef)),fill=(255,129,235,255))
        w, h = draw.textsize(x[1],font=font)
        draw.text((posxx-w/2,posyy-h-coef),x[1].decode("utf8"),(0,0,0,255),font=font)
      if x[0]=="camp":
        font = ImageFont.truetype("DejaVuSans.ttf", 9+pow(self.zoom-9,2))
        coef=self.zoom/4
        #if len(x[1])>10:
        #  towrite=x[1].decode("utf8")[0:15]+"-"
        #else:
        #  towrite=x[1]
        towrite="Primitiv"
        draw.polygon(((posxx+coef,posyy+coef),(posxx-coef,posyy+coef),(posxx,posyy-coef)),fill=(0,130,0,255))
        w, h = draw.textsize(towrite,font=font)
        draw.text((posxx-w/2,posyy-h-coef),towrite,(0,130,0,255),font=font)




        #f1=open(self.layer1+"/"+str(self.zoom)+"/"+str(x)+"/"+str(y)+".png")
        #f2=open(self.layer2+"/"+str(self.zoom)+"/"+str(x)+"/"+str(y)+".png")
        #ol1=Image.open(f1)
        #ol2=Image.open(f2)
        #posx=x/self.bound1.x*sizex
        #posy=x/self.bound1.x*sizex
        #ol1.convert("RGBA")
        #back.paste(ol1,((x-self.bound1.x)*256,(y-self.bound1.y)*256))
        #ol2.convert("RGBA")
        #back.paste(ol2,((x-self.bound1.x)*256,(y-self.bound1.y)*256),ol2)
        #
        #f1.close()
        #f2.close()

    back.show()
    back.save(self.result)
Ejemplo n.º 30
0
 def _init(self, code):
     size = self.calculate_size(len(code[0]), len(code), self.dpi)
     self._image = Image.new('RGB', size, self.background)
     self._draw = ImageDraw.Draw(self._image)
Ejemplo n.º 31
0
    def drawBkg(self):
        if self.bw:
            self.bkgclr = (255, 255, 255)
        else:
            self.bkgclr = self.options.clrbackground

        self.SetBackgroundColour(self.bkgclr)

        tableclr = self.options.clrtable
        if self.bw:
            tableclr = (0, 0, 0)

        img = Image.new('RGB', (self.WIDTH, self.HEIGHT), self.bkgclr)
        draw = ImageDraw.Draw(img)

        BOR = commonwnd.CommonWnd.BORDER

        txtclr = (0, 0, 0)
        if not self.bw:
            txtclr = self.options.clrtexts

        x = BOR
        y = BOR
        draw.line((x + self.SMALL_CELL_WIDTH, y, x + self.TABLE_WIDTH, y),
                  fill=tableclr)

        y += self.LINE_HEIGHT
        for i in range(self.LINE_NUM + 1):
            draw.line((x, y + i * self.LINE_HEIGHT, x + self.TABLE_WIDTH,
                       y + i * self.LINE_HEIGHT),
                      fill=tableclr)

        draw.line((x, y, x, y + self.TABLE_HEIGHT - self.LINE_HEIGHT),
                  fill=tableclr)
        x += self.SMALL_CELL_WIDTH
        y -= self.LINE_HEIGHT
        draw.line((x, y, x, y + self.TABLE_HEIGHT), fill=tableclr)
        for i in range(self.COLUMN_NUM + 2):
            draw.line((x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH, y,
                       x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH,
                       y + self.TABLE_HEIGHT),
                      fill=tableclr)

        for i in range(astrology.SE_SATURN + 1):
            clr = (0, 0, 0)
            if not self.bw:
                if self.options.useplanetcolors:
                    clr = self.options.clrindividual[i]
                else:
                    dign = self.chart.dignity(i)
                    clr = self.clrs[dign]
            txt = common.common.Planets[i]
            w, h = draw.textsize(txt, self.fntMorinus)
            draw.text(
                (x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH +
                 (self.CELL_WIDTH - w) / 2, y + (self.LINE_HEIGHT - h) / 2),
                txt,
                fill=clr,
                font=self.fntMorinus)
            draw.text(
                (x - self.SMALL_CELL_WIDTH + (self.SMALL_CELL_WIDTH - w) / 2,
                 y + (i + 1) * self.LINE_HEIGHT + (self.LINE_HEIGHT - h) / 2),
                txt,
                fill=clr,
                font=self.fntMorinus)

            plon = self.chart.planets.planets[i].data[planets.Planet.LONG]
            self.drawLong(draw, x,
                          y + self.TITLE_HEIGHT + i * self.LINE_HEIGHT, plon,
                          clr)

            for j in range(astrology.SE_SATURN + 1):
                if j == astrology.SE_SUN or j == astrology.SE_MOON:
                    txt = self.chart.almutens.essentials.essentials[i][j][0]
                    w, h = draw.textsize(txt, self.fntText)
                    draw.text(
                        (x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH +
                         (self.CELL_WIDTH - w) / 2, y +
                         (j + 1) * self.LINE_HEIGHT +
                         (self.LINE_HEIGHT - h) / 2),
                        txt,
                        fill=txtclr,
                        font=self.fntText)
                else:
                    txt = self.chart.almutens.essentials.essentials2[i][j -
                                                                        2][0]
                    w, h = draw.textsize(txt, self.fntText)
                    draw.text(
                        (x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH +
                         (self.CELL_WIDTH - w) / 2, y +
                         (j + 1) * self.LINE_HEIGHT +
                         (self.LINE_HEIGHT - h) / 2),
                        txt,
                        fill=txtclr,
                        font=self.fntText)

            txt = self.chart.almutens.essentials.essentials[i][3][0]
            w, h = draw.textsize(txt, self.fntText)
            draw.text((x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH +
                       (self.CELL_WIDTH - w) / 2, y + 8 * self.LINE_HEIGHT +
                       (self.LINE_HEIGHT - h) / 2),
                      txt,
                      fill=txtclr,
                      font=self.fntText)

            txt = self.chart.almutens.essentials.essentials[i][4][0]
            w, h = draw.textsize(txt, self.fntText)
            draw.text((x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH +
                       (self.CELL_WIDTH - w) / 2, y + 9 * self.LINE_HEIGHT +
                       (self.LINE_HEIGHT - h) / 2),
                      txt,
                      fill=txtclr,
                      font=self.fntText)

            txt = self.chart.almutens.essentials.essentials[i][2][0]
            w, h = draw.textsize(txt, self.fntText)
            draw.text((x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH +
                       (self.CELL_WIDTH - w) / 2, y + 10 * self.LINE_HEIGHT +
                       (self.LINE_HEIGHT - h) / 2),
                      txt,
                      fill=txtclr,
                      font=self.fntText)

            txt = self.chart.almutens.essentials.essentialsmc[i][0]
            w, h = draw.textsize(txt, self.fntText)
            draw.text((x + self.LONGITUDE_CELL_WIDTH + i * self.CELL_WIDTH +
                       (self.CELL_WIDTH - w) / 2, y + 11 * self.LINE_HEIGHT +
                       (self.LINE_HEIGHT - h) / 2),
                      txt,
                      fill=txtclr,
                      font=self.fntText)

        #Degree Wins
        txt = mtexts.txts['Almuten']
        w, h = draw.textsize(txt, self.fntText)
        draw.text((x + self.LONGITUDE_CELL_WIDTH + 7 * self.CELL_WIDTH +
                   (self.DEGREEWINS_CELL_WIDTH - w) / 2, y +
                   (self.LINE_HEIGHT - h) / 2),
                  txt,
                  fill=txtclr,
                  font=self.fntText)

        x = BOR + self.SMALL_CELL_WIDTH + 7 * self.CELL_WIDTH
        y = BOR + self.TITLE_HEIGHT
        #		num = len(self.chart.almutens.essentials.degwinner)
        for i in range(2):
            self.drawDegWinner(draw, x + self.LONGITUDE_CELL_WIDTH, y, i,
                               False, self.chart.almutens.essentials.degwinner,
                               txtclr)

        x = BOR + self.SMALL_CELL_WIDTH + 7 * self.CELL_WIDTH
        y = BOR + self.TITLE_HEIGHT + 2 * self.LINE_HEIGHT
        num = len(self.chart.almutens.essentials.degwinner2)
        for i in range(num):
            self.drawDegWinner(draw, x + self.LONGITUDE_CELL_WIDTH, y, i,
                               False,
                               self.chart.almutens.essentials.degwinner2,
                               txtclr)

        x = BOR + self.SMALL_CELL_WIDTH + 7 * self.CELL_WIDTH
        y = BOR + self.TITLE_HEIGHT + 7 * self.LINE_HEIGHT
        self.drawDegWinner(draw, x + self.LONGITUDE_CELL_WIDTH, y, 3, True,
                           self.chart.almutens.essentials.degwinner, txtclr)

        x = BOR + self.SMALL_CELL_WIDTH + 7 * self.CELL_WIDTH
        y = BOR + self.TITLE_HEIGHT + 8 * self.LINE_HEIGHT
        self.drawDegWinner(draw, x + self.LONGITUDE_CELL_WIDTH, y, 4, True,
                           self.chart.almutens.essentials.degwinner, txtclr)

        x = BOR + self.SMALL_CELL_WIDTH + 7 * self.CELL_WIDTH
        y = BOR + self.TITLE_HEIGHT + 9 * self.LINE_HEIGHT
        self.drawDegWinner(draw, x + self.LONGITUDE_CELL_WIDTH, y, 2, True,
                           self.chart.almutens.essentials.degwinner, txtclr)

        x = BOR + self.SMALL_CELL_WIDTH + 7 * self.CELL_WIDTH
        y = BOR + self.TITLE_HEIGHT + 10 * self.LINE_HEIGHT
        self.drawDegWinner2(draw, x + self.LONGITUDE_CELL_WIDTH, y,
                            self.chart.almutens.essentials.degwinnermc, txtclr)

        x = BOR
        y = BOR + self.LINE_HEIGHT
        #LoF
        clr = (0, 0, 0)
        if not self.bw:
            if self.options.useplanetcolors:
                clr = self.options.clrindividual[11]
            else:
                clr = self.options.clrperegrin
        txt = common.common.fortune
        w, h = draw.textsize(txt, self.fntMorinus)
        draw.text(
            (x + (self.SMALL_CELL_WIDTH - w) / 2, y + 7 * self.LINE_HEIGHT +
             (self.LINE_HEIGHT - h) / 2),
            txt,
            fill=clr,
            font=self.fntMorinus)

        flon = self.chart.fortune.fortune[fortune.Fortune.LON]
        self.drawLong(draw, x + self.SMALL_CELL_WIDTH,
                      y + 7 * self.LINE_HEIGHT, flon, clr)

        #Syzygy
        txt = mtexts.txts['Syzygy']
        w, h = draw.textsize(txt, self.fntText)
        draw.text(
            (x + (self.SMALL_CELL_WIDTH - w) / 2, y + 8 * self.LINE_HEIGHT +
             (self.LINE_HEIGHT - h) / 2),
            txt,
            fill=txtclr,
            font=self.fntText)

        slon = self.chart.syzygy.lon
        self.drawLong(draw, x + self.SMALL_CELL_WIDTH,
                      y + 8 * self.LINE_HEIGHT, slon, txtclr)

        #Asc
        txt = mtexts.txts['Asc']
        w, h = draw.textsize(txt, self.fntText)
        draw.text(
            (x + (self.SMALL_CELL_WIDTH - w) / 2, y + 9 * self.LINE_HEIGHT +
             (self.LINE_HEIGHT - h) / 2),
            txt,
            fill=txtclr,
            font=self.fntText)

        alon = self.chart.houses.ascmc[houses.Houses.ASC]
        self.drawLong(draw, x + self.SMALL_CELL_WIDTH,
                      y + 9 * self.LINE_HEIGHT, alon, txtclr)

        #MC
        txt = mtexts.txts['MC']
        w, h = draw.textsize(txt, self.fntText)
        draw.text(
            (x + (self.SMALL_CELL_WIDTH - w) / 2, y + 10 * self.LINE_HEIGHT +
             (self.LINE_HEIGHT - h) / 2),
            txt,
            fill=txtclr,
            font=self.fntText)

        mlon = self.chart.houses.ascmc[houses.Houses.MC]
        self.drawLong(draw, x + self.SMALL_CELL_WIDTH,
                      y + 10 * self.LINE_HEIGHT, mlon, txtclr)

        y = BOR + self.LINE_HEIGHT
        #Housecusps
        hcstxt = [
            mtexts.txts['HC1'], mtexts.txts['HC2'], mtexts.txts['HC3'],
            mtexts.txts['HC4'], mtexts.txts['HC5'], mtexts.txts['HC6'],
            mtexts.txts['HC7'], mtexts.txts['HC8'], mtexts.txts['HC9'],
            mtexts.txts['HC10'], mtexts.txts['HC11'], mtexts.txts['HC12']
        ]
        for i in range(astrology.SE_SATURN + 1):
            for j in range(houses.Houses.HOUSE_NUM):
                if i == 0:
                    txt = hcstxt[j]
                    w, h = draw.textsize(txt, self.fntText)
                    draw.text(
                        (x + (self.SMALL_CELL_WIDTH - w) / 2,
                         y + 11 * self.LINE_HEIGHT + j * self.LINE_HEIGHT +
                         (self.LINE_HEIGHT - h) / 2),
                        txt,
                        fill=txtclr,
                        font=self.fntText)

                txt = self.chart.almutens.essentials.essentialshcs[i][j][0]
                w, h = draw.textsize(txt, self.fntText)
                draw.text(
                    (x + self.SMALL_CELL_WIDTH + self.LONGITUDE_CELL_WIDTH +
                     i * self.CELL_WIDTH + (self.CELL_WIDTH - w) / 2,
                     y + 11 * self.LINE_HEIGHT + j * self.LINE_HEIGHT +
                     (self.LINE_HEIGHT - h) / 2),
                    txt,
                    fill=txtclr,
                    font=self.fntText)

                if i == 0:
                    hlon = self.chart.houses.cusps[j + 1]
                    if self.options.ayanamsha != 0 and self.options.hsys != 'W':
                        hlon -= self.chart.ayanamsha
                        hlon = util.normalize(hlon)
                    self.drawLong(
                        draw, x + self.SMALL_CELL_WIDTH,
                        y + 11 * self.LINE_HEIGHT + j * self.LINE_HEIGHT, hlon,
                        txtclr, False)

        #Housecusps degwinner
        x = BOR + self.SMALL_CELL_WIDTH + 7 * self.CELL_WIDTH
        y = BOR + self.TITLE_HEIGHT + 11 * self.LINE_HEIGHT
        num = len(self.chart.almutens.essentials.degwinnerhcs)
        for i in range(num):
            self.drawDegWinner(draw, x + self.LONGITUDE_CELL_WIDTH, y, i,
                               False,
                               self.chart.almutens.essentials.degwinnerhcs,
                               txtclr)

        wxImg = wx.EmptyImage(img.size[0], img.size[1])
        wxImg.SetData(img.tostring())
        self.buffer = wx.BitmapFromImage(wxImg)
Ejemplo n.º 32
0
def createImageOfAnnotation(sequenceObject, outputFile):
	'''Creates an image of the annotation, with relative positions of features and their size'''
	try:
		import ImageFont, Image, ImageDraw
	except:
		print ''
		print 'Could not import Image or ImageDraw library, no image of result being created.'
		return False

	horizontalSize = 1224
	verticalSize = 250
	red = (255,102,102)
	green = (0,102,51)
	bege = (255,178,102)
	blue = (102,178,255)
	white = (255,255,255)
	size = (horizontalSize,verticalSize)             # size of the image to create
	im = Image.new('RGB', size, white) # create the image
	draw = ImageDraw.Draw(im)   # create a drawing object that is
	                            # used to draw on the new image
	n = 1
	legenda = []

	for gbkFeature in sequenceObject.features:
		if gbkFeature.type == 'tRNA' or gbkFeature.type == 'CDS' or gbkFeature.type == 'rRNA' or gbkFeature.type == 'D-loop':
			featureLen = (gbkFeature.location.end - gbkFeature.location.start) + 1
			featureRelativeSize = horizontalSize * featureLen / len(sequenceObject.seq)
			featureRelativeStart = (horizontalSize * gbkFeature.location.start / len(sequenceObject.seq)) + 1
		
			if gbkFeature.location.strand == 1:
				if n%2 == 0:
					text_pos = (featureRelativeStart - 1,20) # top-left position of our text
				else:
					text_pos = (featureRelativeStart - 1,10) # top-left position of our text
			else:
				if n%2 == 0:
					text_pos = (featureRelativeStart - 1,125) # top-left position of our text
				else:
					text_pos = (featureRelativeStart - 1,115) # top-left position of our text
		
			for qualifier in gbkFeature.qualifiers:
				if qualifier == 'product' or qualifier == 'gene':
					#get feature name
					text = str(n) #gbkFeature.qualifiers[qualifier]

					if gbkFeature.qualifiers[qualifier] not in legenda:
						legenda.append(gbkFeature.qualifiers[qualifier])

					if gbkFeature.type == 'rRNA':
						triangleColor = red
					elif gbkFeature.type == 'tRNA':
						triangleColor = bege
					else:
						triangleColor = blue

			module_dir = os.path.dirname(__file__)
			module_dir = os.path.abspath(module_dir)
			font_full_path = os.path.join(module_dir, 'fonts/FreeSans.ttf')

			font = ImageFont.truetype(font_full_path,12)

			# Now, we'll do the drawing: 
			draw.text(text_pos, text, fill="black", font=font)

			if gbkFeature.location.strand == 1:
				draw.polygon([(featureRelativeStart,40), (featureRelativeStart,70), \
                                            (featureRelativeStart + featureRelativeSize,55)],outline=triangleColor, fill=triangleColor)
			else:
				draw.polygon([(featureRelativeStart,90), (featureRelativeStart + featureRelativeSize,105), \
                                            (featureRelativeStart + featureRelativeSize,75)],outline=triangleColor, fill=triangleColor)

			n += 1

	nlegenda = 0
	legendaString = ''
	linha = 1

	while draw.textsize(legendaString,font=font)[0] < horizontalSize and nlegenda < len(legenda):
		nlegenda += 1
		if draw.textsize(legendaString + str(nlegenda) + '-' + legenda[nlegenda - 1] + ', ',font=font)[0]  > horizontalSize:
			draw.text((0,155 + 20 * (linha - 1)), legendaString, fill="black", font=font)
			linha += 1
			nlegenda -= 1
			legendaString = ''
		elif nlegenda == len(legenda):
			legendaString += str(nlegenda) + '-' + legenda[nlegenda - 1]
			draw.text((0,155 + 20 * (linha - 1)), legendaString, fill="black", font=font)
			break
		else:
			legendaString += str(nlegenda) + '-' + legenda[nlegenda - 1] + ', '

	draw.text((horizontalSize / 2,verticalSize - 15), sequenceObject.name, fill="black", font=font)
	
	del draw # I'm done drawing so I don't need this anymore
	
	# now, we tell the image to save as a PNG to the 
	# provided file-like object
	im.save(outputFile, 'PNG')
Ejemplo n.º 33
0
    def drawFunkyWindGauge(self, gaugeName):
        """Wind direction gauge generator with shaded background to indicate historic wind directions"""

        imageWidth = self.gauge_dict.as_int('image_width')
        imageHeight = self.gauge_dict.as_int('image_height')
        imageOrigin = (imageWidth / 2, imageHeight / 2)

        syslog.syslog(
            syslog.LOG_INFO,
            """reportengine: Generating %s gauge, (%d x %d)""" %
            (gaugeName, imageWidth, imageHeight))

        labelFontSize = self.gauge_dict[gaugeName].as_int('labelfontsize')

        archivedb = self._getArchive(self.skin_dict['archive_database'])
        (data_time, data_value) = archivedb.getSqlVectors(
            'windDir',
            archivedb.lastGoodStamp() -
            self.gauge_dict[gaugeName].as_int('history') * 60,
            archivedb.lastGoodStamp(), 300, 'avg')

        for rec in data_value:
            syslog.syslog(syslog.LOG_INFO, """reportengine: %s""" % rec)

        # Number of bins to count wind history into
        numBins = 16

        # One data point recorded every 5 mins for 'history' number of hours
        numPoints = self.gauge_dict[gaugeName].as_int('history') * 60 / 5

        #
        # Get the wind data
        #
        buckets = [0.0] * numBins

        # 22 July 2013
        #
        # Now looks up historic data using weewx helper functions... Thanks Tom!
        #
        archive_db = self.config_dict['StdArchive']['archive_database']
        archive = weewx.archive.Archive.open(
            self.config_dict['Databases'][archive_db])

        windDirNow = None
        windSpeedNow = None

        for row in archive.genSql(
                "SELECT windDir, windSpeed FROM archive ORDER BY dateTime DESC LIMIT %d"
                % numPoints):
            # This line is occasionally crashing out with error:
            # TypeError: float() argument must be a string or a number
            if row[0] is not None:
                windDir = float(row[0])
                if (windDir < 0) or (windDir > 360):
                    syslog.syslog(
                        syslog.LOG_INFO,
                        "drawFunkyWindGauge: %f should be in the range 0-360 degrees",
                        windDir)
                else:
                    buckets[int(windDir * numBins / 360)] += 1

            if windSpeedNow is None:
                windSpeedNow = float(row[1])

            if windDirNow is None:
                windDirNow = windDir

        max = maxValue(buckets)
        buckets = [i / max for i in buckets]

        #
        # Draw the gauge
        #
        im = Image.new("RGB", (imageWidth, imageHeight), (255, 255, 255))

        draw = ImageDraw.Draw(im)

        if imageWidth < imageHeight:
            radius = imageWidth * 0.45
        else:
            radius = imageHeight * 0.45

        sansFont = ImageFont.truetype(
            "/usr/share/fonts/truetype/freefont/FreeSans.ttf", labelFontSize)
        bigSansFont = ImageFont.truetype(
            "/usr/share/fonts/truetype/freefont/FreeSans.ttf", 20)

        # Background
        angle = 0.0
        angleStep = 360.0 / numBins
        for i in range(0, numBins, 1):
            draw.pieslice(
                (int(imageOrigin[0] - radius), int(imageOrigin[1] - radius),
                 int(imageOrigin[0] + radius), int(imageOrigin[1] + radius)),
                int(angle + 90),
                int(angle + angleStep + 90),
                fill=(255, int(255 * (1 - buckets[i])), 255))
            angle += angleStep

        # Compass points
        labels = ['N', 'E', 'S', 'W']

        for i in range(0, 4, 1):
            angle = i * math.radians(90) + math.radians(180)

            # Major tic
            startPoint = (imageOrigin[0] - radius * math.sin(angle) * 0.93,
                          imageOrigin[1] + radius * math.cos(angle) * 0.93)
            endPoint = (imageOrigin[0] - radius * math.sin(angle),
                        imageOrigin[1] + radius * math.cos(angle))
            draw.line((startPoint, endPoint), fill=(0, 0, 0))

            labelText = labels[i]
            stringSize = sansFont.getsize(labelText)

            labelPoint = (imageOrigin[0] - radius * math.sin(angle) * 0.80,
                          imageOrigin[1] + radius * math.cos(angle) * 0.80)
            labelPoint = (labelPoint[0] - stringSize[0] / 2,
                          labelPoint[1] - stringSize[1] / 2)

            draw.text(labelPoint, labelText, font=sansFont, fill=(0, 0, 0))

            # Minor tic
            angle += math.radians(45)
            startPoint = (imageOrigin[0] - radius * math.sin(angle) * 0.93,
                          imageOrigin[1] + radius * math.cos(angle) * 0.93)
            endPoint = (imageOrigin[0] - radius * math.sin(angle),
                        imageOrigin[1] + radius * math.cos(angle))
            draw.line((startPoint, endPoint), fill=(0, 0, 0))

        # The needle
        angle = math.radians(windDirNow)
        endPoint = (imageOrigin[0] - radius * math.sin(angle) * 0.7,
                    imageOrigin[1] + radius * math.cos(angle) * 0.7)
        leftPoint = (imageOrigin[0] -
                     radius * math.sin(angle - math.pi * 7 / 8) * 0.2,
                     imageOrigin[1] +
                     radius * math.cos(angle - math.pi * 7 / 8) * 0.2)
        rightPoint = (imageOrigin[0] -
                      radius * math.sin(angle + math.pi * 7 / 8) * 0.2,
                      imageOrigin[1] +
                      radius * math.cos(angle + math.pi * 7 / 8) * 0.2)
        midPoint = (imageOrigin[0] - radius * math.sin(angle + math.pi) * 0.1,
                    imageOrigin[1] + radius * math.cos(angle + math.pi) * 0.1)

        draw.line((leftPoint, endPoint), fill=(3, 29, 219))
        draw.line((rightPoint, endPoint), fill=(3, 29, 219))
        draw.line((leftPoint, midPoint), fill=(3, 29, 219))
        draw.line((rightPoint, midPoint), fill=(3, 29, 219))

        # Outline
        draw.ellipse(((imageOrigin[0] - radius, imageOrigin[1] - radius),
                      (imageOrigin[0] + radius, imageOrigin[1] + radius)),
                     outline=(0, 0, 0))

        # Digital value text
        #degreeSign= u'\N{DEGREE SIGN}'
        #digitalText = "%d" % windDirNow + degreeSign
        digitalText = self.formatter.to_ordinal_compass(
            (windDirNow, "degree_compass", "group_direction"))
        stringSize = bigSansFont.getsize(digitalText)
        draw.text((imageOrigin[0] - stringSize[0] / 2,
                   imageOrigin[1] + radius * 0.4 - stringSize[1] / 2),
                  digitalText,
                  font=bigSansFont,
                  fill=(3, 29, 219))

        del draw

        im.save(self.whereToSaveIt + gaugeName + "Gauge.png", "PNG")
Ejemplo n.º 34
0
    def drawGauge(self, gaugeValue, gaugeName):
        imageWidth = self.gauge_dict.as_int('image_width')
        imageHeight = self.gauge_dict.as_int('image_height')
        imageOrigin = (imageWidth / 2, imageHeight / 2)

        # Check gaugeValue is usable
        if gaugeValue is None:
            syslog.syslog(
                syslog.LOG_INFO,
                "reportengine: Generating %s gauge, (%d x %d), value = None" %
                (gaugeName, imageWidth, imageHeight))
            digitalText = "N/A"
        else:
            syslog.syslog(
                syslog.LOG_INFO,
                "reportengine: Generating %s gauge, (%d x %d), value = %.1f" %
                (gaugeName, imageWidth, imageHeight, gaugeValue))

            if gaugeName == "Temperature":
                # Temparature scale
                degreeSign = u'\N{DEGREE SIGN}'
                digitalText = "%.1f" % gaugeValue + degreeSign + "C"
            elif gaugeName == "Pressure":
                digitalText = "%d" % gaugeValue + " mbar"
            elif gaugeName == "Humidity":
                digitalText = "%d" % gaugeValue + "%"
            elif gaugeName == "WindSpeed":
                digitalText = "%.1f" % gaugeValue + " knots"
            elif gaugeName == "WindGust":
                digitalText = "%.1f" % gaugeValue + " knots"

        minValue = self.gauge_dict[gaugeName].as_float('minvalue')
        maxValue = self.gauge_dict[gaugeName].as_float('maxvalue')
        majorStep = self.gauge_dict[gaugeName].as_float('majorstep')
        minorStep = self.gauge_dict[gaugeName].as_float('minorstep')
        labelFontSize = self.gauge_dict[gaugeName].as_int('labelfontsize')
        labelFormat = "%d"

        minAngle = 45  # in degrees
        maxAngle = 315

        im = Image.new("RGB", (imageWidth, imageHeight), (255, 255, 255))

        draw = ImageDraw.Draw(im)

        if imageWidth < imageHeight:
            radius = imageWidth * 0.45
        else:
            radius = imageHeight * 0.45

        # Background
        if gaugeName == "Temperature":
            if self.gauge_dict[gaugeName].as_int('history') > 0:

                numBins = self.gauge_dict[gaugeName].as_int('bins')
                buckets = self.histogram(gaugeName, "outTemp")

                angle = float(minAngle)
                angleStep = (maxAngle - minAngle) / float(numBins)
                for i in range(0, numBins, 1):
                    draw.pieslice((int(imageOrigin[0] - radius),
                                   int(imageOrigin[1] - radius),
                                   int(imageOrigin[0] + radius),
                                   int(imageOrigin[1] + radius)),
                                  int(angle + 90),
                                  int(angle + angleStep + 90),
                                  fill=(255, int(255 * (1 - buckets[i])), 255))
                    angle += angleStep

        draw.ellipse(((imageOrigin[0] - radius, imageOrigin[1] - radius),
                      (imageOrigin[0] + radius, imageOrigin[1] + radius)),
                     outline=(0, 0, 0))

        sansFont = ImageFont.truetype(
            "/usr/share/fonts/truetype/freefont/FreeSans.ttf", labelFontSize)
        bigSansFont = ImageFont.truetype(
            "/usr/share/fonts/truetype/freefont/FreeSans.ttf", 20)

        labelValue = minValue

        # Major tic marks and scale labels
        for angle in frange(math.radians(minAngle), math.radians(maxAngle),
                            int(1 + (maxValue - minValue) / majorStep)):
            startPoint = (imageOrigin[0] - radius * math.sin(angle) * 0.93,
                          imageOrigin[1] + radius * math.cos(angle) * 0.93)
            endPoint = (imageOrigin[0] - radius * math.sin(angle),
                        imageOrigin[1] + radius * math.cos(angle))
            draw.line((startPoint, endPoint), fill=(0, 0, 0))

            labelText = str(labelFormat % labelValue)
            stringSize = sansFont.getsize(labelText)

            labelPoint = (imageOrigin[0] - radius * math.sin(angle) * 0.80,
                          imageOrigin[1] + radius * math.cos(angle) * 0.80)
            labelPoint = (labelPoint[0] - stringSize[0] / 2,
                          labelPoint[1] - stringSize[1] / 2)

            draw.text(labelPoint, labelText, font=sansFont, fill=(0, 0, 0))
            #draw.point(labelPoint)
            labelValue += majorStep

        # Minor tic marks
        for angle in frange(math.radians(minAngle), math.radians(maxAngle),
                            int(1 + (maxValue - minValue) / minorStep)):
            startPoint = (imageOrigin[0] - radius * math.sin(angle) * 0.97,
                          imageOrigin[1] + radius * math.cos(angle) * 0.97)
            endPoint = (imageOrigin[0] - radius * math.sin(angle),
                        imageOrigin[1] + radius * math.cos(angle))
            draw.line((startPoint, endPoint), fill=(0, 0, 0))

        # The needle
        if gaugeValue is not None:
            angle = math.radians(minAngle + (gaugeValue - minValue) *
                                 (maxAngle - minAngle) / (maxValue - minValue))
            endPoint = (imageOrigin[0] - radius * math.sin(angle) * 0.7,
                        imageOrigin[1] + radius * math.cos(angle) * 0.7)
            leftPoint = (imageOrigin[0] -
                         radius * math.sin(angle - math.pi * 7 / 8) * 0.2,
                         imageOrigin[1] +
                         radius * math.cos(angle - math.pi * 7 / 8) * 0.2)
            rightPoint = (imageOrigin[0] -
                          radius * math.sin(angle + math.pi * 7 / 8) * 0.2,
                          imageOrigin[1] +
                          radius * math.cos(angle + math.pi * 7 / 8) * 0.2)
            midPoint = (imageOrigin[0] -
                        radius * math.sin(angle + math.pi) * 0.1,
                        imageOrigin[1] +
                        radius * math.cos(angle + math.pi) * 0.1)

            draw.line((leftPoint, endPoint), fill=(3, 29, 219))
            draw.line((rightPoint, endPoint), fill=(3, 29, 219))
            draw.line((leftPoint, midPoint), fill=(3, 29, 219))
            draw.line((rightPoint, midPoint), fill=(3, 29, 219))

        # Digital value text
        stringSize = bigSansFont.getsize(digitalText)
        draw.text((imageOrigin[0] - stringSize[0] / 2,
                   imageOrigin[1] + radius * 0.4 - stringSize[1] / 2),
                  digitalText,
                  font=bigSansFont,
                  fill=(3, 29, 219))

        del draw

        im.save(self.whereToSaveIt + gaugeName + "Gauge.png", "PNG")
Ejemplo n.º 35
0
def load_data():
  data = pd.read_csv('bac2012.csv', sep='|', header=0,
      names = ['name', 'county', 'pos', 'unit', 'retry', 'type', 'special',
        'ro1', 'ro2', 'oblig', 'oblig1', 'oblig2',
        'choice', 'choice1', 'choice2', 'avg', 'admitted'])
  admit = data[data['admitted'] >0]
  print len(admit)
  admit_county = data[['county', 'admitted']]
  grouped = admit_county.groupby('county')
  county_percents = grouped.aggregate(np.average)
  county_percents = county_percents.sort('admitted')
  print county_percents
  harta_jud = Image.open('img/harta_bw3.png')
  #transform_bw(harta_jud)
  #harta_jud = harta_jud.convert('1')
  county_pos = {
    'ab' : (140, 130),
    'ag' : (210, 210),
    'ar' : (100, 130),
    'b' : (273, 243), # + if
    'bc' : (300, 140),
    'bh' : (100, 100),
    'bn' : (200, 60),
    'br' : (340, 200),
    'bt' : (300, 20),
    'bv' : (230, 160),
    'bz' : (300, 220),
    'cj' : (170, 100),
    'cl' : (330, 270),
    'cs' : (90, 200),
    'ct' : (380, 260),
    'cv' : (270, 170),
    'db' : (240, 220),
    'dj' : (160, 260),
    'gj' : (150, 210),
    'gl' : (350, 160),
    'gr' : (260, 270),
    'hd' : (120, 160),
    'hr' : (240, 100),
    'il' : (340, 240),
    'is' : (300, 70),
    'mh' : (110, 230),
    'mm' : (200, 40),
    'ms' : (220, 100),
    'nt' : (280, 80),
    'ot' : (200, 260),
    'ph' : (260, 200),
    'sb' : (190, 150),
    'sj' : (150, 70),
    'sm' : (140, 30),
    'sv' : (250, 40),
    'tl' : (410, 220),
    'tm' : (70, 170),
    'tr' : (230, 270),
    'vl' : (180, 200),
    'vn' : (300, 160),
    'vs' : (340, 110)
  }
  print float(county_percents.loc['ab'])
  percent_min =  float(county_percents.iloc[0])
  percent_max = float(county_percents.iloc[-1])
  percent_delta = percent_max-percent_min
  draw = ImageDraw.Draw(harta_jud)
  font = ImageFont.truetype("/Library/Fonts/Georgia.ttf",12)
  for k,v in county_pos.items():
    (x,y) = v
    alpha = county_percents.loc[k]
    ImageDraw.floodfill(harta_jud, (x,y), (int((1-alpha)*255), int(alpha*255), 0))
    draw.text((x,y), k, (0, 0, 0), font=font)
  harta_jud.save("img/a_test.png")