Ejemplo n.º 1
0
class SokoLock(Object):
    img = Img.img2("SokoLok")
    img2 = Img.img2("SokoLokOpen")
    destructible = False
    lockopen = False
    updtick = 0

    def get_img(self):
        return self.img2 if self.lockopen else self.img

    def update(self, world):
        if not self.lockopen:
            if self.updtick != 60:
                self.updtick += 1
            else:
                self.updtick = 0
                breaking = False
                for row in world.t:
                    for t in row:
                        if t == 4 or t == 6 or t == 10:
                            breaking = True
                            break
                    if breaking:
                        break
                else:
                    self.lockopen = True
                    self.destructible = True
Ejemplo n.º 2
0
 def update(self, events):
     """Update Everything"""
     if not pygame.mixer.music.get_busy():
         Img.musply(choice(self.music), 1)
     for n in range(self.tran[0]):
         if not randint(0, self.tran[1]):
             rx = randint(0, self.size[0] - 1)
             ry = randint(0, self.size[1] - 1)
             terrlist[self.terr[rx][ry]].ranupdate(self, rx, ry)
     for ent in self.ents:
         ent.update(self, events)
         ent.mupdate(self, events)
     self.anitick += 1
     if self.anitick == 56:
         self.anitick = 0
         self.map = self.make_map()
     for row in self.objs:
         for obj in row:
             if obj and obj.updatable:
                 obj.update(self)
     if self.player.psupply > 0:
         for pst in self.player.pstorage:
             self.player.psupply -= pst.give_power(self, self.player.psupply)
             if self.player.psupply == 0:
                 break
Ejemplo n.º 3
0
def f1():
  import pgm
  #imgarray,w,h = pgm.pgmread('histo_inp_image.pgm')
  #imgarray,w,h = pgm.pgmread('histo_ref_image.pgm')
  #imgarray,w,h = pgm.pgmread('histo_inp_image2.pgm')
  #imgarray,w,h = pgm.pgmread('histo_ref_image2.pgm')
  imgarray,w,h = pgm.pgmread('lena.pgm')
  #imgarray,w,h = pgm.pgmread('fourier_transform.pgm')
  imgs = Img.Img(imgarray)
  imgt = imgs.add_salt_pepper(0.65)
  imgt1 = imgt.median_filter(np.ones((3,3)))
  imgt1 = imgt1.median_filter(np.ones((5,5)))
  #imgt1 = imgt.median_filter(np.ones((7,7)))
  #imgt1 = imgt.median_filter(np.array([[2,2,2],[2,1,2],[2,2,2]]))
  k = Img.create_gauss_kernel(Img.find_gauss_support(0.75), 0.75)
  imgt2 = imgt.conv(k)
  plot_fig(imgs.pix, 'Original image')
  plot_fig(imgt.pix, 'Added salt and pepper noise')
  plot_fig(imgt1.pix, 'Median filtered image')
  plot_fig(imgt2.pix, 'Gaussian LP filtered image')
  #plot_hist(imgs, 'Original image')
  #plot_hist(imgt, 'Added salt and pepper noise')
  #plot_hist(imgt1, 'Median filtered image')
  #plot_hist(imgt2, 'Gaussian LP filtered image')
  print np.sum((imgs.pix - imgt1.pix)**2)
Ejemplo n.º 4
0
def die(screen):
    pygame.display.flip()
    pygame.time.wait(1000)
    screen.fill((0, 0, 0))
    Img.bcentre(Img.bfont, "FOOL", screen, col=(255, 255, 255))
    pygame.display.flip()
    pygame.time.wait(1000)
Ejemplo n.º 5
0
 def run(self,screen,player):
     screen.fill((255,255,255))
     Img.bcentre(Img.bfont,"WIN",screen)
     pygame.display.flip()
     pygame.time.wait(1000)
     if not self.p:
         sys.exit()
Ejemplo n.º 6
0
def f2():
  import pgm
  #
  # imgs is the image to be modified
  # imgt is the reference image
  #
  imgarray,w,h = pgm.pgmread('histo_inp_image.pgm')
  #imgarray,w,h = pgm.pgmread('histo_ref_image.pgm')
  #imgarray,w,h = pgm.pgmread('histo_inp_image2.pgm')
  #imgarray,w,h = pgm.pgmread('histo_ref_image2.pgm')
  #imgarray,w,h = pgm.pgmread('lena.pgm')
  #imgarray,w,h = pgm.pgmread('fourier_transform.pgm')
  #imgarray,w,h = pgm.pgmread('Fourier.pgm')
  imgs = Img.Img(imgarray)
  #
  #imgarray,w,h = pgm.pgmread('histo_inp_image.pgm')
  imgarray,w,h = pgm.pgmread('histo_ref_image.pgm')
  #imgarray,w,h = pgm.pgmread('histo_inp_image2.pgm')
  #imgarray,w,h = pgm.pgmread('histo_ref_image2.pgm')
  #imgarray,w,h = pgm.pgmread('lena.pgm')
  #imgarray,w,h = pgm.pgmread('fourier_transform.pgm')
  #imgarray,w,h = pgm.pgmread('Fourier.pgm')
  imgt = Img.Img(imgarray)
  #
  imgt1 = imgs.modify_hist(imgt)
  plot_fig(imgs.pix, 'Original image')
  plot_fig(imgt.pix, 'Reference image')
  plot_fig(imgt1.pix, 'Modified original image')
  stem_hist(imgs, 'Original image')
  stem_hist(imgt, 'Reference image')
  stem_hist(imgt1, 'Modified original image')
  print np.sum((imgs.pix - imgt1.pix)**2)
Ejemplo n.º 7
0
 def __init__(self, edit, level=None):
     self.edit = edit
     self.playerdead = False
     self.done = False
     self.level = level
     self.exitcode="NORMAL"
     if edit:
         self.t = []
         self.o = []
         for _ in range(20):
             self.t.append([0] * 20)
             self.o.append([0] * 20)
         self.e = []
     else:
         self.e = []
         self.ps=[]
         if level=="sav":
             savfile = open(Img.np("lvls//save.sav"), "r")
         elif len(level)==2:
             savfile = open(Img.np("lvls//%s-%s.sav" % tuple(level)), "r")
         else:
             savfile = open(Img.np("lvls//%s-%s-%s.sav" % tuple(level)), "r")
         self.t = []
         self.o = []
         self.fx = []
         self.bfx = []
         if level[0]==3 and level[1]!=8:
             for _ in range(randint(50,60)):
                 self.bfx.append(FX.Star(randint(0,638),randint(0,638)))
         savr = savfile.readlines()
         self.fltext = savr[0][:-1]
         del savr[0]
         for row in savr[:20]:
             self.t.append([int(s) for s in row.split()])
         for x, row in enumerate(savr[20:]):
             self.o.append([None] * 20)
             crow = [int(s) for s in row.split()]
             for y, n in enumerate(crow):
                 if n:
                     eo = self.eoconvert(n)
                     if eo[1] == "obj":
                         self.o[x][y] = eo[0](x, y)
                     elif eo[1] == "ent":
                         self.e.append(eo[0](x, y))
                     elif eo[1] == "spawn":
                         self.ps.append(eo[0](x, y))
                         self.e.append(self.ps[-1])
                         self.akey=self.ps[-1].akey
                     elif eo[1] == "gravblock":
                         self.e.append(Entities.SokoBlokGrav(x,y,eo[0]))
         if level[1]==8:
             try:
                 self.boss=Bosses.bosses[level[0]-1](9,9)
                 if level[0]==6:
                     self.o[9][9]=self.boss
                 else:
                     self.e.append(self.boss)
             except IndexError:
                 pass
         savfile.close()
Ejemplo n.º 8
0
def parse_data(path, shape, size, batch_size, time_step):
    DataSet = []
    i_Buffers = []
    Labels = []
    l_Buffers = []
    cnt = 0
    
    for i in range(time_step):
        i_Buffers.append(None)
        l_Buffers.append(None)
        
    images = Img.Video_Read(path, shape, size)
    labels = Img.Label_Read(path)
    
    for image, label in zip(images, labels):
        cnt += 1
        for i in range(time_step):
            i_Buffers[time_step -i - 1] = i_Buffers[time_step - i - 2]            
            l_Buffers[time_step -i - 1] = l_Buffers[time_step - i - 2]
        i_Buffers[0] = image        
        l_Buffers[0] = label     
        
        if(cnt >= time_step):
            DataSet.append(i_Buffers.copy()) 
            Labels.append(l_Buffers.copy())
    
    train = tf.data.Dataset.from_tensor_slices((DataSet, Labels))
    train = train.batch(batch_size)
    
    return train
Ejemplo n.º 9
0
class Pan(Item):
    img = Img.img4("Pan")
    burnt = False
    bimg = Img.img4("BurntPan")

    def combine(self, food):
        if food.can_change_state(
                "cooked") and not self.contents and not self.burnt:
            self.contents = food
            self.re_img()
            return True

    def re_img(self):
        if self.burnt:
            self.img = self.bimg
        elif self.contents:
            self.img = self.__class__.img.copy()
            self.img.blit(self.contents.get_img(), (0, 0))
        else:
            self.img = self.__class__.img

    def heat(self):
        if self.contents:
            if self.contents.heat():
                if self.contents.burnprog:
                    self.contents = None
                    self.burnt = True
                    self.re_img()
                else:
                    self.re_img()

    def maketag(self):
        return "Pan:" + self.contents.maketag() if self.contents else "empty"
Ejemplo n.º 10
0
class Block(Pipe):
    img=Img.img32("Block")
    cimg=Img.img32("EBlock")
    symb = "B"
    def get_img(self):
        return self.img
    def get_cimg(self):
        return self.cimg
Ejemplo n.º 11
0
class SaladCream(Food):
    name = "SaladCream"
    img = Img.img4("SaladCream")
    raw_img = Img.imgsz("SaladBottle", (32, 32))
    removable = False

    def get_img(self):
        return self.img
Ejemplo n.º 12
0
class Ketchup(Food):
    name = "Ketchup"
    img = Img.img4("Ketchup")
    raw_img = Img.imgsz("KetchupBottle", (32, 32))
    soupcolour = (255, 0, 0)
    removable = False

    def get_img(self):
        return self.img
Ejemplo n.º 13
0
class Mustard(Food):
    name = "Mustard"
    img = Img.img4("Mustard")
    raw_img = Img.imgsz("MustardBottle", (32, 32))
    soupcolour = (255, 216, 0)
    removable = False

    def get_img(self):
        return self.img
Ejemplo n.º 14
0
    def __init__(self, manager):
        OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)

        inImage_arg = [None] * ((len(Img._d_TimedCameraImage) - 4) / 2)
        self._d_inImage = Img.TimedCameraImage(*inImage_arg)
        """
		"""
        self._inImageIn = OpenRTM_aist.InPort("inImage", self._d_inImage)
        self._d_inString = OpenRTM_aist.instantiateDataType(RTC.TimedString)
        """
		"""
        self._inStringIn = OpenRTM_aist.InPort("inString", self._d_inString)
        outImage_arg = [None] * ((len(Img._d_TimedCameraImage) - 4) / 2)
        self._d_outImage = Img.TimedCameraImage(
            RTC.Time(0, 0),
            Img.CameraImage(RTC.Time(0, 0), Img.ImageData(0, 0, 0, []),
                            Img.CameraIntrinsicParameter([], []), []), 0)
        """
		"""
        self._outImageOut = OpenRTM_aist.OutPort("outImage", self._d_outImage)
        self._d_outObjectParam = OpenRTM_aist.instantiateDataType(
            ObjectRecognition.TimedObjectParamSeq)
        """
		"""
        self._outObjectParamOut = OpenRTM_aist.OutPort("outObjectParam",
                                                       self._d_outObjectParam)
        self._d_outFlag = OpenRTM_aist.instantiateDataType(RTC.TimedLong)
        """
		"""
        self._outFlagOut = OpenRTM_aist.OutPort("outFlag", self._d_outFlag)

        # initialize of configuration-data.
        # <rtc-template block="init_conf_param">
        """
		
		 - Name:  dataset
		 - DefaultValue: karuta
		"""
        self._dataset = ['karuta']
        """
		
		 - Name:  mode
		 - DefaultValue: gpu
		"""
        self._mode = ['gpu']
        """
		
		 - Name:  net
		 - DefaultValue: vgg16
		"""
        self._net = ['vgg16']
        """
		
		 - Name:  recognitionRate
		 - DefaultValue: 0.8
		"""
        self._recognitionRate = [0.8]
Ejemplo n.º 15
0
 def re_img(self):
     if self.contents:
         self.img = self.imgs[self.contents.q - 1].copy()
         Img.colswap(self.img, (255, 0, 255), self.contents.colour)
         if self.contents.chunks:
             self.img.blit(self.contents.chunks,
                           (0, self.contents.q * -4 + 4))
     else:
         self.img = self.__class__.img
Ejemplo n.º 16
0
class Burger(Food):
    topped = False
    simg = None
    state = "normal"
    ordermultiplier = 1.5
    name = "Burger"
    img = Img.img4("BunBase")
    raw_img = Img.imgsz("BunBase", (32, 32))

    def __init__(self):
        self.contents = []

    def combine(self, food):
        if not any([self.topped, food.utensil]):
            if food.state != "normal" and food.name in burgeritems and food.name not in self.get_names(
            ):
                self.contents.append(food)
                self.re_img()
                return True
            elif food.name == "BunTop":
                self.topped = True
                self.re_img()
                return True
        elif not self.topped and food.name == "Pan" and food.contents and "cooked" in food.contents.state:
            self.contents.append(food.contents)
            food.contents = None
            food.re_img()
            self.re_img()
            return False

    def re_img(self):
        totoffset = (len(self.contents) + self.topped) * 4
        self.simg = pygame.Surface((64, 64 + totoffset), pygame.SRCALPHA,
                                   32).convert_alpha()
        self.simg.blit(self.img, (0, totoffset))
        yb = 0
        for s in burgeritems:
            for c in self.contents:
                if c.name == s:
                    self.simg.blit(c.get_img(), (0, yb + totoffset))
                    yb -= 4
        if self.topped:
            self.simg.blit(BunTop.img, (0, 0))
        self.o3d = totoffset // 4

    def get_img(self):
        return self.simg if self.contents else self.img

    def get_names(self):
        names = [c.name for c in self.contents]
        return [s for s in burgeritems if s in names]

    def maketag(self):
        return "Burger:" + ",".join(
            [c.maketag()
             for c in sorted(self.contents)]) + ("T" if self.topped else "uT")
Ejemplo n.º 17
0
def create_train_csv():
    """生成训练集"""

    file_list = listdir('train_image/')
    for each in file_list:
        img = Image.open('train_image/%s' % each)
        x = Img.two_Value(img, 'list')
        y = each[0]
        x.insert(0, y)
        Img.write_csv(fileName='train_csv.csv', values=x)
Ejemplo n.º 18
0
    def format(self):
        """将self.all_chunks里的图片进行二值、去边框、环切、重定义尺寸,
        并保存至self.all_format_chunks当中"""

        for i, each in enumerate(self.all_chunks):
            two_value_image = Img.twoValueImage(each, 200)
            remove_frame = Img.clear_frame(two_value_image, 1)
            cut_around = Img.cut_around(remove_frame)
            new_img = Img.format_size(cut_around, (20, 30))
            self.all_format_chunks.append(new_img)
Ejemplo n.º 19
0
def test():
    download_image("http://jwxt.bupt.edu.cn/validateCodeAction.do?random=",name="hello")
    image=Img(fname="hello.jpg")
    image.binary()
    images=image.divide()

    vcodes=[]
    for temp in images:
        vcodes.append(temp.recognise())
    vcode_result=''.join(vcodes)
    print(vcode_result)
Ejemplo n.º 20
0
def Instruct(instructions, time):
    words = instructions.split()
    text = ""
    for i in range(len(words)):
        pygame.event.pump()
        if i:
            text += " "
        text += words[i]
        screen.fill((255, 255, 255))
        Img.bcentre(Img.dfont, text, screen, col=(0, 0, 0))
        pygame.display.flip()
        pygame.time.wait(time)
Ejemplo n.º 21
0
 def run(self,screen,player):
     """The pause GUI should use minimal system resources"""
     pygame.mixer.music.pause()
     screen.fill((255,255,255))
     Img.bcentre(Img.bfont,"Paused",screen)
     pygame.display.flip()
     while True:
         for e in pygame.event.get():
             if e.type==pygame.QUIT:
                 sys.exit()
             if e.type==pygame.KEYDOWN and e.key==pygame.K_p:
                 pygame.mixer.music.unpause()
                 return None
         pygame.time.wait(200)
Ejemplo n.º 22
0
 def add(self, food):
     self.contents.append(food)
     self.colours.append(food.soupcolour)
     if not self.chunks and food.scimg and food.state == "chopped":
         self.chunks = food.scimg
     self.colour = tuple([
         sum([c[n] for c in self.colours]) // len(self.colours)
         for n in range(3)
     ])
     self.q += 1
     if self.q == 3:
         self.img = Img.img4("Soup")
         if self.chunks:
             self.img.blit(self.chunks, (0, 0))
         Img.colswap(self.img, (255, 0, 255), self.colour)
Ejemplo n.º 23
0
class SokoPlate(Tile):
    img = Img.img2("SokoPlate")

    def update(self, world, x, y):
        gent = world.get_ent(x, y)
        if gent and gent.name == "Sokoblock":
            world.t[x][y] = 7
Ejemplo n.º 24
0
 def __init__(self, level, players,controllers):
     self.done = False
     self.level = level
     self.exitcode="NORMAL"
     self.e = []
     self.ps=[]
     savfile = open(Img.np("lvls//battle//"+level), "r")
     self.t = []
     self.o = []
     self.fx = []
     self.bfx = []
     pn=0
     savr = savfile.readlines()
     for row in savr[:20]:
         self.t.append([int(s) for s in row.split()])
     for x, row in enumerate(savr[20:]):
         self.o.append([None] * 20)
         crow = [int(s) for s in row.split()]
         for y, n in enumerate(crow):
             if n:
                 eo = self.eoconvert(n)
                 if eo[1] == "obj":
                     self.o[x][y] = eo[0](x, y)
                 elif eo[1] == "ent":
                     self.e.append(eo[0](x, y))
                 elif eo[1] == "spawn":
                     self.ps.append(self.pconv[players[pn]](x, y, controllers[pn]))
                     self.e.append(self.ps[-1])
                     pn+=1
     savfile.close()
Ejemplo n.º 25
0
 def __init__(self, level, players, controllers):
     self.done = False
     self.level = level
     self.exitcode = "NORMAL"
     self.e = []
     self.ps = []
     savfile = open(Img.np("lvls//battle//" + level), "r")
     self.t = []
     self.o = []
     self.fx = []
     self.bfx = []
     pn = 0
     savr = savfile.readlines()
     for row in savr[:20]:
         self.t.append([int(s) for s in row.split()])
     for x, row in enumerate(savr[20:]):
         self.o.append([None] * 20)
         crow = [int(s) for s in row.split()]
         for y, n in enumerate(crow):
             if n:
                 eo = self.eoconvert(n)
                 if eo[1] == "obj":
                     self.o[x][y] = eo[0](x, y)
                 elif eo[1] == "ent":
                     self.e.append(eo[0](x, y))
                 elif eo[1] == "spawn":
                     self.ps.append(self.pconv[players[pn]](
                         x, y, controllers[pn]))
                     self.e.append(self.ps[-1])
                     pn += 1
     savfile.close()
Ejemplo n.º 26
0
 def __init__(self,level,hs):
     self.electric=not level[0]%2
     if self.electric:
         self.ttgo=5460
     self.objects=[[None]*self.size[1] for _ in range(self.size[0])]
     lfile=open(Img.np("levels//%s-%s.sav" % tuple(level)))
     llines=lfile.readlines()
     del llines[0]
     for x,row in enumerate(llines):
         for y,n in enumerate(row.split()):
             if n!="0":
                 obj=n.split(":")
                 for c in editorclasses:
                     if c.symb==obj[0]:
                         newobj=c(int(obj[1]))
                         newobj.fixed=True
                         self.objects[x][y]=newobj
                         if obj[0]=="S":
                             self.fx=x
                             self.fy=y
                             self.nd=D.get_dir(int(obj[1]))
     self.hs=hs
     self.new_pipe()
     self.level=level
     self.nhs=False
Ejemplo n.º 27
0
class ManPlateAct(Tile):
    img = Img.img2("ManPlateAct")

    def update(self, world, x, y):
        gent = world.get_ent(x, y)
        if not gent or gent not in world.ps:
            world.t[x][y] = 10
Ejemplo n.º 28
0
class ManPlate(Tile):
    img = Img.img2("ManPlate")

    def update(self, world, x, y):
        gent = world.get_ent(x, y)
        if gent and gent in world.ps:
            world.t[x][y] = 11
Ejemplo n.º 29
0
class SokoPlateAct(Tile):
    img = Img.img2("SokoPlateAct")

    def update(self, world, x, y):
        gent = world.get_ent(x, y)
        if not gent or gent.name != "Sokoblock":
            world.t[x][y] = 6
Ejemplo n.º 30
0
class Basket(Item):
    img = Img.img4("Basket")
    o3d = 4
    name = "Basket"

    def combine(self, food):
        if food.can_change_state("fried") and not self.contents:
            self.contents = food
            self.re_img()
            return True

    def re_img(self):
        if self.contents:
            self.img = self.__class__.img.copy()
            self.img.blit(self.contents.get_img(), (0, 0))
        else:
            self.img = self.__class__.img

    def heat(self):
        if self.contents:
            if self.contents.fry():
                if self.contents.burnprog:
                    self.contents = None
                    self.re_img()
                else:
                    self.re_img()

    def maketag(self):
        return "Basket:" + self.contents.maketag(
        ) if self.contents else "empty"
Ejemplo n.º 31
0
def SendPic(command):
    global commands
    messagelist = []
    if command.user in log:
        userhist = log[command.user]
        messagelist.append(userhist[-2][1])
        messagelist.append(userhist[-1][0])
        messagelist.append(userhist[-1][1])
    else:
        messagelist.append("Play the game first!!!")

    image = Img.gen(messagelist)

    try:
        image.save("123.png")
    except IOError:
        print("cannot convert")

    try:
        api.update_with_media(filename = "123.png", status = "Here is a highlight from @" + command.user)
        del commands[0] #remove command from queue. happens after posting, so if there is an error it stays in
        print('POSTED pic to ' + command.user)
        f = open("last.txt", "w")
        f.write(str(command.id))
        f.close()

        #do not update the log when posting a highlight. only keeps track of actual game commands.

    except tweepy.TweepError as e:
        print "Error trying to post status: " + str(e.reason)
Ejemplo n.º 32
0
def move_to_second_label():
    # Take image form user class
    z = img.upload_image()
    if z is not None:
        main_label.pack_forget()
        second_label.pack()
        second_window(z)
Ejemplo n.º 33
0
class Pot(Item):
    imgs = [Img.img4("PotSoup" + str(n)) for n in range(3)]

    def combine(self, food):
        if not food.utensil and food.state != "normal" and food.soupcolour:
            if not self.contents:
                self.contents = Soup(food)
                self.re_img()
                return True
            elif self.contents.q < 3:
                self.contents.add(food)
                self.re_img()
                return True

    def re_img(self):
        if self.contents:
            self.img = self.imgs[self.contents.q - 1].copy()
            Img.colswap(self.img, (255, 0, 255), self.contents.colour)
            if self.contents.chunks:
                self.img.blit(self.contents.chunks,
                              (0, self.contents.q * -4 + 4))
        else:
            self.img = self.__class__.img

    def heat(self):
        if self.contents:
            self.contents.heat()
            if self.contents.burnt == 360:
                self.re_img()

    def maketag(self):
        if self.contents:
            return "Pot:" + self.contents.maketag()
        return "Pot"
Ejemplo n.º 34
0
class Snow(FX):
    img = Img.img2("SnowFX")

    def update(self, world):
        self.y += randint(1, 3)
        self.x += randint(-1, 1)
        if self.y > 640:
            self.dead = True
Ejemplo n.º 35
0
 def __init__(self, x, y,owner, fent):
     self.x = x
     self.y = y
     self.owner=owner
     self.ent=fent
     simg=pygame.transform.scale(self.ent.img,(16,16))
     self.img.blit(simg,(4,8))
     self.img.blit(Img.imgret("Tutorial\Psign.png"),(16,8))
Ejemplo n.º 36
0
def two_value():
    """将训练集所有原始图进行二值化"""

    file_list = listdir('source_image/')
    for each in file_list:
        image = Image.open('source_image/%s' % each)
        image = Img.twoValueImage(image, 200)
        image.save('two_value_image/%s' % each)
Ejemplo n.º 37
0
class Drain(Pipe):
    symb = "D"
    img=Img.img32("Drain")
    cimgs=rloadf("CableDrain")
    name="Drain"
    ends=D.directions
    def get_img(self):
        return self.img
Ejemplo n.º 38
0
 def __init__(self, x, y, rgb):
     self.x = x
     self.y = y
     self.ileft = 10
     self.rgb = rgb
     self.img = Img.imgret("GoldBlock.png")
     pygame.draw.rect(self.img, rgb, pygame.Rect(4, 4, 8, 8))
     self.img = pygame.transform.scale2x(self.img)
Ejemplo n.º 39
0
def f1():
    """ Convolves image and kernel """
    (imgarr, w, h) = pgm.pgmread('cameraman.pgm')
    imgs = Img.Img(imgarr)
    k1 = Img.create_gauss_kernel(Img.find_gauss_support(0.8))
    k2 = Img.create_gauss_kernel(Img.find_gauss_support(1.2))
    k3 = Img.create_gauss_kernel(Img.find_gauss_support(1.6))
    imgt1 = imgs.conv(k1)
    imgt2 = imgs.conv(k2)
    imgt3 = imgs.conv(k3)
    #  print imgt1.col, imgt1.row
    #  print imgt2.col, imgt2.row
    #  print imgt3.col, imgt3.row
    plt.figure(1)
    plt.imshow(imgs.pix, cmap=cm.gray)
    plt.title('Original image')
    plt.figure(2)
    plt.imshow(imgt1.pix, cmap=cm.gray)
    plt.title('Img convolved with Gaussian kernel' + str(shape(k1)))
    plt.figure(3)
    plt.imshow(imgt2.pix, cmap=cm.gray)
    plt.title('Img convolved with Gaussian kernel' + str(shape(k2)))
    plt.figure(4)
    plt.imshow(imgt3.pix, cmap=cm.gray)
    plt.title('Img convolved with Gaussian kernel' + str(shape(k3)))
    plt.show()
Ejemplo n.º 40
0
 def __init__(self, x, y, rgb):
     self.x = x
     self.y = y
     self.rgb = rgb
     self.mcol = rgb
     self.img = Img.imgret("MachBlock.png")
     pygame.draw.rect(self.img, rgb, pygame.Rect(4, 4, 8, 8))
     self.img = pygame.transform.scale2x(self.img)
     self.output = []
Ejemplo n.º 41
0
 def init(cls):
     cls.name = cls.__name__
     cls.validstates = []
     name = cls.name
     cls.img = Img.img4(name)
     cls.stateimgs = {"normal": cls.img}
     cls.raw_img = Img.imgsz(name, (32, 32))
     for s in [
             "chopped", "grated", "cooked", "hammered", "grilled", "rolled",
             "hammered+cooked", "cooked+chopped", "grated+fried"
     ]:
         try:
             cls.stateimgs[s] = Img.img4(
                 "".join([ss.capitalize() for ss in s.split("+")]) + name)
             cls.validstates.append(s)
         except pygame.error:
             pass
     cls.einit()
    def __init__(self, manager):
        OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)

        camera_arg = [None] * ((len(Img._d_TimedCameraImage) - 4) / 2)
        self._d_camera = Img.TimedCameraImage(*camera_arg)
        """
        """
        self._cameraIn = OpenRTM_aist.InPort("camera", self._d_camera)
        """
        """
        self._manipCommonPort = OpenRTM_aist.CorbaPort("manipCommon")
        """
        """
        self._manipMiddlePort = OpenRTM_aist.CorbaPort("manipMiddle")
        """
        """
        self._manipCommon = OpenRTM_aist.CorbaConsumer(
            interfaceType=JARA_ARM.ManipulatorCommonInterface_Common)
        """
        """
        self._manipMiddle = OpenRTM_aist.CorbaConsumer(
            interfaceType=JARA_ARM.ManipulatorCommonInterface_Middle)

        # initialize of configuration-data.
        # <rtc-template block="init_conf_param">
        """
        
         - Name:  debug
         - DefaultValue: 1
        """
        self._debug = [1]

        self._model = None
        """
        
         - Name:  gripper_close_ratio
         - DefaultValue: 0.1
        """
        self._gripper_close_ratio = [0.1]

        #self._model = None

        # the position for taking a picture
        self._camera_jointPos0 = [1.57076]
        self._camera_jointPos1 = [0]
        self._camera_jointPos2 = [1.57076]
        self._camera_jointPos3 = [0]
        self._camera_jointPos4 = [1.57076]
        self._camera_jointPos5 = [0]

        #the initial position
        self._initial_jointPos0 = [1.57076]
        self._initial_jointPos1 = [0]
        self._initial_jointPos2 = [1.57076]
        self._initial_jointPos3 = [0]
        self._initial_jointPos4 = [1.57076]
        self._initial_jointPos5 = [0]
Ejemplo n.º 43
0
 def win(self,screen):
     success.play()
     screen.fill((255,255,255))
     Img.bcentre(bfont,"YAY",screen)
     if self.score>self.hs:
         self.nhs=True
         Img.bcentre(tfont,"NEW HIGH SCORE: "+str(self.score),screen,100,(0,255,0))
     else:
         Img.bcentre(tfont,"SCORE: "+str(self.score),screen,100)
         Img.bcentre(tfont,"HIGH SCORE: "+str(self.hs),screen,200)
     pygame.display.flip()
     pygame.time.wait(2000)
     self.done="success"
Ejemplo n.º 44
0
def f1():
  """ Convolves image and kernel """
  (imgarr,w,h) = pgm.pgmread('cameraman.pgm')
  imgs = Img.Img(imgarr)
  k1 = Img.create_gauss_kernel(Img.find_gauss_support(0.8))
  k2 = Img.create_gauss_kernel(Img.find_gauss_support(1.2))
  k3 = Img.create_gauss_kernel(Img.find_gauss_support(1.6))
  imgt1 = imgs.conv(k1)
  imgt2 = imgs.conv(k2)
  imgt3 = imgs.conv(k3)
#  print imgt1.col, imgt1.row
#  print imgt2.col, imgt2.row
#  print imgt3.col, imgt3.row
  plt.figure(1)
  plt.imshow(imgs.pix, cmap=cm.gray)
  plt.title('Original image')
  plt.figure(2)
  plt.imshow(imgt1.pix, cmap=cm.gray)
  plt.title('Img convolved with Gaussian kernel' + str(shape(k1)))
  plt.figure(3)
  plt.imshow(imgt2.pix, cmap=cm.gray)
  plt.title('Img convolved with Gaussian kernel' + str(shape(k2)))
  plt.figure(4)
  plt.imshow(imgt3.pix, cmap=cm.gray)
  plt.title('Img convolved with Gaussian kernel' + str(shape(k3)))
  plt.show()
Ejemplo n.º 45
0
 def run(self, screen, player):
     recrects = []
     while True:
         for e in pygame.event.get():
             if e.type==pygame.QUIT:
                 sys.exit()
             if e.type == pygame.MOUSEBUTTONDOWN:
                 mpos = pygame.mouse.get_pos()
                 for rr in recrects:
                     if rr[1].collidepoint(mpos):
                         self.cr.recipe = rr[0]
                         self.cr.recipeprogress = GameRegistry.craftrecipes[rr[0]][0][:]
             elif e.type==pygame.KEYDOWN and e.key==pygame.K_LSHIFT:
                 return None
         screen.fill((200, 200, 200))
         recrects = []
         Img.fblit(screen, Img.dfont, "CRAFTING: ", (0, 0, 0), (0, 0))
         Img.fblit(screen,Img.sfont,", ".join(self.cr.recipeprogress),(0, 0, 0), (0, 32))
         if self.cr.recipeprogress == GameRegistry.craftrecipes[self.cr.recipe][0]:
             for n, r in enumerate(GameRegistry.craftrecipes):
                 recrects.append([n, screen.blit(r[2], (n * 32, 64))])
         pygame.display.flip()
Ejemplo n.º 46
0
 def render(self,p,screen):
     screenrect=screen.get_rect()
     sh,sw=screenrect.h,screenrect.w
     awscale=scales[self.wscale]
     aiscale=scales[self.invscale]
     riscale=self.invscale+1
     m=(sw/float(awscale)+1)/2.0
     rm=int(ceil(m))
     wconvmult=awscale/64.0
     if not (p.shop or (p.dead and not p.dt)):
         asx=p.x*awscale+ir(p.xoff)*wconvmult-(m-1)*awscale
         asy=p.y*awscale+ir(p.yoff)*wconvmult-(m-1)*awscale-aiscale
         r=(p.rumbling-1)//10+1
         rx=randint(-r,r)
         ry=randint(-r,r)
         sx=p.x
         sy=p.y
         for y in range(sy-rm-1,sy+rm+1):
             for x in range(sx-rm-1,sx+rm+1):
                 screen.blit(Tiles.tiles[self.get_t(x,y)].get_img()[self.wscale],(x*awscale-asx+rx,y*awscale-asy+ry))
         for y in range(sy-rm-1,sy+rm+1):
             for x in range(sx-rm-1,sx+rm+1):
                 objs=self.get_os(x,y)
                 for o in objs:
                     if not o.is_hidden(self,p):
                         screen.blit(o.get_img(self)[self.wscale],(x*awscale+ir(o.xoff)*wconvmult-asx+rx,y*awscale+ir(o.yoff)*wconvmult-asy-o.o3d*(self.wscale+1)+ry))
         pygame.draw.rect(screen,(200,200,200),pygame.Rect(0,0,sw,aiscale))
         for n,i in enumerate(p.iinv.inv if p.iinv else p.inv):
             screen.blit(i.get_img(p,self)[self.invscale],(n*aiscale,0))
             if i.stack>1:
                 screen.blit(numerals[i.stack-2][self.invscale],(n*aiscale+(11 if i.stack<10 else 9)*(self.invscale+1),36))
             if n==p.isel:
                 pygame.draw.rect(screen,p.col,pygame.Rect(n*aiscale,15*riscale,aiscale,riscale))
         if p.statuseffects:
             maxt=max([se[1] for se in p.statuseffects])
             maxse=[se for se in p.statuseffects if se[1]==maxt][0]
             pygame.draw.rect(screen,p.col,pygame.Rect(0,sh-9,maxt*sw//Players.etimes[maxse[0]],12))
     elif p.shop:
         screen.fill((150,150,150))
         pygame.draw.rect(screen,(200,200,200),pygame.Rect(0,0,sw,64))
         Img.bcentrex(bcfont,p.shop.title,screen,-16)
         for n,i in enumerate(p.shop.items):
             Img.cxblit(i[0].img[self.invscale],screen,n*aiscale+aiscale,-8*riscale)
             Img.bcentrex(cashfont,str(i[1]),screen,n*aiscale+aiscale,(255,255,0),8*riscale)
         screen.blit(p.simg[self.invscale],(0,p.ssel*aiscale+aiscale))
     else:
         p.dead.render(screen)
     Img.bcentrex(cashfont,str(p.cash),screen,sh-48,(255,255,0))
     pygame.draw.rect(screen,p.col,pygame.Rect(0,0,sw,sh),2)
Ejemplo n.º 47
0
 def get_img(self, world):
     screen = Img.blank32.copy()
     Img.bcentre(Img.sfont, str(self.rgb[0]), screen, -8, (self.rgb[0], 0, 0))
     Img.bcentre(Img.sfont, str(self.rgb[1]), screen, 1, (0, self.rgb[1], 0))
     Img.bcentre(Img.sfont, str(self.rgb[2]), screen, 10, (0, 0, self.rgb[2]))
     img = self.img.copy()
     img.blit(screen, (0, 0))
     return img
Ejemplo n.º 48
0
def train():
    for i in range(10):
        try:
            os.mkdir(fontpath)
        except:
            print(fontpath+" exist!")
        download_image("http://jwxt.bupt.edu.cn/validateCodeAction.do?random=")
        img=Img(fname="vcode.jpg")
        img.binary()
        img.save("tempBinary.jpg")
        img.show()
        x=input()
        if x=="next":          #如果分割破坏严重或者二值化后图片花了,直接输入next跳过该图片,以免污染字库
            continue
        images=img.divide()

        random.randint(1,100)
        for s,i in zip(x,images):
            f=open(fontpath+s+"-"+str(random.randint(1,100))+".txt","w+")
            f.write(i.get_feature()) #将特征值保存
            f.close()
Ejemplo n.º 49
0
def train2():
    for i in range(10):
        try:
            os.mkdir(fontpath)
        except:
            print(fontpath+" exist!")
        download_image("http://jwxt.bupt.edu.cn/validateCodeAction.do?random=")
        img=Img(fname="vcode.jpg")
        img.binary()
        img.save("tempBinary.jpg")
        img.show()
        images=img.divide()
        random.randint(1,100)
        for i in images:
            result=i.recognise()
            print("hello:"+result)
            x=input()
            if x=="":   #如果上面识别结果没错,输入回车则保存特征值。否则随意输入其他字符,跳过
                f=open(fontpath+result+"-"+str(random.randint(1,100))+".txt","w+")
                f.write(i.get_feature())
                f.close()
Ejemplo n.º 50
0
 def __init__(self,edit,level,lvlsize):
     self.guitorun=None
     self.edit=edit
     self.olist=[]
     if edit:
         self.size=lvlsize
         s=self.size
         self.eworld=[[0]*s[1] for n in range(s[0])]
         self.terr=[[0]*s[1] for n in range(s[0])]
         self.objs=[[None]*(s[1]+1) for n in range(s[0])]
         self.oconvert()
         self.objs[0][0]=[Scroller(0,0)]
         self.player=self.objs[0][0][0]
     else:
         savfile=open(Img.np("lvls/%s-%s.sav" % tuple(level)))
         savr = savfile.readlines()
         self.size=(len(savr)-1,len(savr[1].split()))
         s=self.size
         self.fltext = savr[0][:-1]
         self.terr=[[0]*s[1] for n in range(s[0])]
         self.objs=[[None]*(s[1]+1) for n in range(s[0])]
         self.oconvert()
         del savr[0]
         for x,row in enumerate(savr):
             for y,n in enumerate(row.split()):
                 try:
                     n=int(n)
                 except ValueError:
                     n=self.symbreconvert(n)
                 if n:
                     obj=EDITORLIST[n-1]
                     if obj in Terrain.terrlist:
                         self.set_terr(x,y,n)
                     elif obj in editorobjs:
                         self.spawn(obj(x,y))
                     else:
                         if obj==Player.Player:
                             self.player=obj(x,y)
                             self.spawn(self.player)
                         else:
                             self.spawn(obj(x,y))
     self.complete=False
     self.pdone=False
Ejemplo n.º 51
0
import Forestry
import Vehicles
import Img
import Power
import UM
import Robotics
import Crafting

pygame.init()
loc = os.path.dirname(os.getcwd()) + "/Assets/"
imgconv = "u", "l", "", "r"
colinpl = (255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 255, 255), (255, 0, 255), (255, 255, 0), (0, 0, 0), (255, 255, 255)
hdirconv = {(0, -1): 0, (-1, 0): 1, (0, 1): 2, (1, 0): 3}
ps2map = [2, 1, 5, 6, 7, 0, 4, 9]
xboxmap = [0, 1, 2]
picksound = Img.sndget("Randomize2.wav")
sellsound = Img.sndget("Pickup_Coin.wav")


class MechCategory(object):
    img = Img.imgret2("Gear.png")
    iscat = True
    doc = "Tech stuff"

    def __init__(self):
        self.menu = [Buyers.CRotObjBuyer(Mech.SlowConv), Buyers.RotObjBuyer(Mech.Conv, 100),
                     Buyers.RotObjBuyer(Mech.RainConv, 1000),
                     Buyers.RotObjBuyer(Mech.DownTunnel, 200), Buyers.RotObjBuyer(Mech.DownTunnelL, 1000),
                     Buyers.RotObjBuyer(Mech.UpTunnel, 500),
                     Buyers.RotObjBuyer(Mech.Output, 100), Buyers.RotObjBuyer(Mech.Output2, 200),
                     Buyers.ObjBuyer(Mech.Input, 100), Buyers.RotObjBuyer(Mech.IOput, 300),
Ejemplo n.º 52
0
__author__ = 'NoNotCar'
import pygame, sys, os
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((640, 704))
import BattleWorld, Img
from random import choice
import Controllers

pdf = pygame.font.get_default_font()
tfont=pygame.font.Font(pdf,60)
sfont=pygame.font.Font(pdf,20)
clock = pygame.time.Clock()
expimg=Img.img2("Exp")
pexpimg=Img.img2("ExpPen")
bombimg=Img.img2("Bomb")
tickimg=Img.img2("Tick")
crossimg=Img.img2("Null")
pimgs=[Img.img2("men/"+x) for x in ["Man2","FMan","SMan","Tman"]]#+[Img.imgstrip("men/CMan")[0]]
breaking = False
Img.musplay("ChOrDs.ogg")
while not breaking:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            breaking = True
    screen.fill((255, 0, 0))
    Img.bcentre(tfont,"BOMB BATTLES",screen)
    Img.bcentre(sfont,"Click to start",screen,50)
    pygame.display.flip()
Ejemplo n.º 53
0
def imgref2(fil):
    return Img.imgret2("Fishery/"+fil)
Ejemplo n.º 54
0
 def __init__(self,num):
     self.cost=0
     self.gui=HelpGUI(Img.imgret("Tutorial/"+str(num)+".png"))
Ejemplo n.º 55
0
__author__ = 'NoNotCar'
import pygame, sys
pygame.init()
screen = pygame.display.set_mode((640, 704))
import World
import Tiles
import Img

clock = pygame.time.Clock()
selmenu=0
selobjs=[0 for _ in Tiles.tilemenus+Tiles.objmenus]
w=World.World(True)
expimg=Img.img2("Exp")
pexpimg=Img.img2("ExpPen")
bombimg=Img.img2("Bomb")
while True:
    kmods=pygame.key.get_mods()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type==pygame.KEYDOWN and event.key==pygame.K_s and kmods&pygame.KMOD_LCTRL:
            w.save()
            print "SAVED"
        elif event.type==pygame.KEYDOWN:
            menus=Tiles.tilemenus+Tiles.objmenus
            menu=menus[selmenu]
            if event.key==pygame.K_w:
                selobjs[selmenu]=(selobjs[selmenu]-1)%len(menu)
            elif event.key==pygame.K_s:
                selobjs[selmenu]=(selobjs[selmenu]+1)%len(menu)
            elif event.key==pygame.K_a:
Ejemplo n.º 56
0
'''
Created on 24 Jun 2015

@author: NoNotCar
'''
import Img
import pygame

destsound=Img.sndget("explode.wav")
class Tool(object):
    img=Img.blank32
    def use(self,x,y,world,p):
        pass
class Axe(Tool):
    img=Img.imgret2("Axe.png")
    def use(self,x,y,world,p):
        if world.get_obj(x,y):
            return world.get_obj(x,y).cut(world)
class Wrench(Tool):
    img=Img.imgret2("Wrench.png")
    def use(self,x,y,world,p):
        kmods=pygame.key.get_mods()
        if world.get_obj(x,y):
            if kmods & pygame.KMOD_LSHIFT:
                world.get_obj(x,y).rotate()
                return True
            elif kmods & pygame.KMOD_LCTRL:
                world.get_obj(x,y).wrench(world)
                return True
            elif world.get_obj(x,y).is_owner(p):
                world.dest_obj(x,y)
Ejemplo n.º 57
0
Created on 14 Jun 2015
"All The Latest Gadgets"
@author: NoNotCar
'''
import Object
import Img
import pygame
import GUI
import Buyers
import GameRegistry
import Crafting

convimgs = []
slowconvimgs = []
rainconvimgs = []
baseimg = Img.imgret("Conv/ConvBase.png")
sbaseimg = Img.imgret("Conv/ConvBaseSlow.png")
rbaseimg = Img.imgret("Conv/ConvBaseRain.png")
plusimg = Img.imgret("Conv/ConvPlus.png")
splusimg = Img.imgret("Conv/SlowConvPlus.png")
rplusimg = Img.imgret("Conv/RainConvPlus.png")
dirconv = [[-1, 0], [0, 1], [1, 0], [0, -1]]
odirconv = [[0, -1], [-1, 0], [0, 1], [1, 0]]
idirconv = [[0, 1], [1, 0], [0, -1], [-1, 0]]
for bi, imgs, pimg in [(baseimg, convimgs, plusimg), (sbaseimg, slowconvimgs, splusimg),
                       (rbaseimg, rainconvimgs, plusimg)]:
    for ani in range(14):
        bit1 = pimg.subsurface(pygame.Rect(0, 0, ani, 10))
        bit2 = pimg.subsurface(pygame.Rect(ani, 0, 14 - ani, 10))
        newimg = bi.copy()
        newimg.blit(bit1, (15 - ani, 3))
Ejemplo n.º 58
0
@author: NoNotCar
'''
import Players
from Img import imgret2
import Img
from random import randint, choice
from Terrain import terrlist
import Object
import Generators
import Tutorial
import pygame
# util
e = enumerate
selimage = imgret2("Mouse.png")
border = imgret2("MenuWrapper.png")
picon = Img.imgret("PowerIcon.png")
border2 = pygame.transform.rotate(border, 90)
ranconv = {32: (1, 7), 64: (1, 1), 128: (4, 1)}


def cmenu(menu, select):
    return [menu[(select + n) % len(menu)] for n in range(-3, 4)]


class World(object):
    def __init__(self, np, wgen, puz, pn, ps, kp, godmode, size=(32, 32)):
        self.guitorun = None
        self.puz = puz
        if puz == 2:
            generator = Tutorial.tutorials[pn]
        elif puz: