コード例 #1
0
def main():
    easy_dices = [
        './images/easy/dice1.jpg', './images/easy/dice2.jpg',
        './images/easy/dice3.jpg', './images/easy/dice4.jpg',
        './images/easy/dice5.jpg', './images/easy/dice6.jpg',
        './images/easy/dice7.jpg', './images/easy/dice8.jpg',
        './images/easy/dice9.jpg', './images/easy/dice10.jpg'
    ]
    medium_dices = [
        './images/medium/dice1.jpg', './images/medium/dice2.jpg',
        './images/medium/dice3.jpg', './images/medium/dice4.jpg',
        './images/medium/dice5.jpg', './images/medium/dice6.jpg',
        './images/medium/dice7.jpg', './images/medium/dice8.jpg',
        './images/medium/dice9.jpg', './images/medium/dice10.jpg'
    ]
    hard_dices = [
        './images/hard/dice1.jpg', './images/hard/dice2.jpg',
        './images/hard/dice3.jpg', './images/hard/dice4.jpg',
        './images/hard/dice5.jpg', './images/hard/dice6.jpg',
        './images/hard/dice7.jpg', './images/hard/dice8.jpg',
        './images/hard/dice9.jpg', './images/hard/dice10.jpg'
    ]
    pictures = []
    for easy_dice, medium_dice, hard_dice in zip(easy_dices, medium_dices,
                                                 hard_dices):
        pictures.append(Picture(easy_dice))
        pictures.append(Picture(medium_dice))
        pictures.append(Picture(hard_dice))

    for picture in pictures:
        picture.process_picture()
        result(result)
コード例 #2
0
ファイル: Figure.py プロジェクト: ludovicvalet/phystricks
 def new_pspicture(self, name=None, pspict=None):
     if name == None:
         number = len(self.record_pspicture)
         name = "sub" + latinize(str(number))
     if pspict is None:
         from Picture import Picture
         pspict = Picture("FIG" + self.name + "PICT" + name)
     pspict.mother = self
     pspict.figure_mother = self.mother  # The mother of a pspict inside a subfigure is the figure (not the subfigure)
     pspict.subfigure_mother = self
     self._add_pspicture(pspict)
     return pspict
コード例 #3
0
ファイル: Database.py プロジェクト: lukstafi/subte
 def close(self):
     self._is_open = False
     self._dbname = None
     
     # clear everything
     Agency.clear()
     Calendar.clear()
     Stop.clear()
     Path.clear()
     Route.clear()
     TripRoute.clear()
     Trip.clear()
     Frequency.clear()
     Picture.clear()
コード例 #4
0
 def toDictionary(self, options=[], user=None):
     '''For packaging in JSON objects.
     
     Pass in list of VisionComment.Options.* to include other info in objs
     '''
     obj = {  VisionComment.Key.ID : self.id(),
              VisionComment.Key.VISION_ID : self.visionId(),
              VisionComment.Key.AUTHOR_ID : self.authorId(),
              VisionComment.Key.TEXT : self.text(),
              VisionComment.Key.CREATED: self.created().isoformat(),
           }
     if VisionComment.Options.AUTHOR in options:
         from User import User
         obj = self.toDictionary()
         author = User.getById(self.authorId())
         if author:
             obj[VisionComment.Key.AUTHOR] = author.toDictionary()
     if VisionComment.Options.LIKES in options:
         obj[VisionComment.Key.LIKE] = { 
                             VisionComment.Key.LIKE_COUNT: self.likeCount() }
         if user:
             obj[VisionComment.Key.LIKE][VisionComment.Key.USER_LIKE] = \
                                                         self.likedBy(user)
     if VisionComment.Options.PICTURE in options:
         if self.hasPicture():
             from Picture import Picture
             picture = Picture.getById(self.pictureId())
             if picture:
                 obj[VisionComment.Key.PICTURE] = picture.toDictionary()
     return obj
コード例 #5
0
 def __init__(self, header, rows, output_file):
     self.output_file = output_file
     self.num_photos = header
     self.pictures = []
     for row in rows:
         self.pictures.append(Picture(row))
     self.slideShow = SlideShow(self.pictures)
コード例 #6
0
def main():
    channels = int(
        input("Channels? "))  #Selects if the plotting is in XT mode or XY
    if channels == 1:
        print(" Waveform generator mode ")
        Waveform = int(
            input(
                " Select Waveform\n 1.Sine \n 2.Square \n 3.Sawtooth \n 4.Triangle \n 5.Exp Inc Sawtooth \n 6.Exp Dec Sawtooth \n 7.Beats \n"
            ))
        frequency = int(input(" Frequency? "))
        Waveform_dict = {
            1: sine_wave,
            2: square,
            3: sawtooth,
            4: triangle,
            5: exo_inc_sawtooth,
            6: exo_dec_sawtooth
        }
        if Waveform in Waveform_dict:
            Output.out, a = signal_periodic_maker(
                Waveform_dict[Waveform](frequency))
            plt.plot(
                Output.t,
                Output.out)  #Comment out the plt lines to stop graph plotting
            plt.show()
            play(Output.out, 1)
        if Waveform == 7:
            Frequency_Difference = int(input(" Frequency Difference "))
            Phase_Difference = int(input(" Phase Difference "))
            x = sine_wave(frequency)
            y = sine_wave(frequency + Frequency_Difference, Phase_Difference)
            play(adder(x, y), 1, 100000)

        else:
            print("Invalid option")
    elif channels == 2:
        print(" XY mode ")
        Mode = int(
            input(
                " Select mode \n 1.Lissajous mode \n 2.Picture Mode \n 3.Spiroraph mode \n"
            ))
        if Mode == 1:
            Output.out = Lissajous(int(input('Freq X ')),
                                   int(input('Freq Y ')),
                                   float(input('Phase X ')),
                                   float(input('Phase Y ')))
            play(Output.out, 2)
        elif Mode == 2:
            Output.out = Picture(input("Path for the image "),
                                 int(input("Upper Threshold ")),
                                 int(input("Upper Threshold ")))
            play(Output.out, 2, 100000)
        elif Mode == 3:
            Output.out = spirograph(float(input("Inner Radius? ")),
                                    float(input("Radius ratio? ")))
            plt.show()
            play(Output.out, 2, 100000)
        else:
            print("Invalid option")
コード例 #7
0
ファイル: Figure.py プロジェクト: ludovicvalet/phystricks
    def new_pspicture(self, name=None, pspict=None):
        if name == None:
            number = len(self.record_pspicture)
            name = "sub" + latinize(str(number))
        if pspict == None:
            from Picture import Picture

            # Simplifying the auxiliary files names and then also the
            # logging messages.  November 2016.
            #pspict=Picture("FIG"+self.name+"PICT"+name)
            #logging("self.name = "+self.name)
            #logging("name = "+name)

            pspict = Picture(name)

        pspict.figure_mother = self
        self._add_pspicture(pspict)
        return pspict
コード例 #8
0
ファイル: Main.py プロジェクト: cog-isa/mpf-simple
def generate_pics(folders, number):
    files = {}
    for folder in range(len(folders)):
        files[folder] = []
        for n in range(number):
            files[folder].append('pictures/samples/'+folders[folder]+'/0'+str(n+1)+'.txt')
    models = {}
    for a in range(len(folders)):
        models[a] = []
        for file in files[a]:
            p = Picture()
            p.load(file)
            models[a].append(p)
            p = Picture()
            p.load(file)
            p.mirror()
            models[a].append(p)
    return models
コード例 #9
0
    def toDictionary(self, options=[], user=None):
        '''For packaging JSON objects
        
        Pass in list of VisionComment.Options.* for extra information
        '''
        objs = []
        commentList = self._commentModels

        if self.length() > 0:
            from Picture import Picture
            idToPicture = dict()
            if VisionComment.Options.PICTURE in options:
                pictureIds = set([c.pictureId() for c in self.comments()])
                pictureIds.discard(0)
                pictures = Picture.getByIds(pictureIds)
                idToPicture = dict([(picture.id(), picture)
                                   for picture in pictures])

            if VisionComment.Options.AUTHOR in options:
                authorIds = set([comment.authorId()
                                                for comment in self.comments()])
                authors = DataApi.getUsersFromIds(authorIds)
                idToAuthor = dict([(u.id, u) for u in authors])

            # If LIKES
            if VisionComment.Options.LIKES in options:
                commentIds = [c.id() for c in self.comments()]
                tuples = DataApi.getVisionCommentListLikeCount(commentIds)
                idToLikeCount = dict([(commentId, count)
                                       for commentId, count in tuples])
                if user:
                    commentUserLikes = DataApi.getVisionCommentIdsLikedByUser(
                                                        commentIds, user.id())

            for comment in commentList:
                obj = VisionComment(comment).toDictionary()
                if VisionComment.Options.AUTHOR in options:
                    from User import User
                    author = idToAuthor[comment.authorId]
                    obj[VisionComment.Key.AUTHOR] = User(author).toDictionary()
                    # If LIKES
                    if VisionComment.Options.LIKES in options:
                        obj[VisionComment.Key.LIKE] = \
                                    { VisionComment.Key.LIKE_COUNT :
                                      idToLikeCount[comment.id] if
                                      comment.id in idToLikeCount else 0 }
                        if user:
                            obj[VisionComment.Key.LIKE]\
                               [VisionComment.Key.USER_LIKE] =\
                                                comment.id in commentUserLikes
                if VisionComment.Options.PICTURE in options:
                    if comment.pictureId > 0 and \
                       comment.pictureId in idToPicture:
                        cp = idToPicture[comment.pictureId]
                        obj[VisionComment.Key.PICTURE] = cp.toDictionary()
                objs.append(obj)
        return objs
コード例 #10
0
def parseInput(s):
    lines = s.split('\n')
    [nRows, nColumns] = [int(i) for i in lines[0].split()]

    grid = []
    for i in range(nRows):
        grid.append([
            True if j == '#' else False for j in lines[i + 1]
            if j == '#' or j == '.'
        ])

    return Picture(grid)
コード例 #11
0
 def run(self):
     count = 0  # 如果count>0则说明该文件夹下有图片;如果first为true说明还没有添加该文件夹的图片,可以清空listWidget,而不会清空本文件中包含的图片
     first = True
     for item in os.listdir(self.path):
         if item.split('.')[-1] in FILE_TYPE:
             # print(item)
             count += 1
             if count > 0 and first is True:  # 如果该文件夹下有图片,则清空listWidget,重新添加缩略图
                 self.listWidget.clear()
                 first = False
             try:
                 path = str(self.path) + '/' + str(item)
                 widgetItem = Picture(path)
                 self.listWidget.addItem(widgetItem)
             except:
                 pass
コード例 #12
0
    def postPicture(self, picture):
        """API request to post a new Picture object on the Wiface API

        Arguments:
            picture {[Picture]} -- [Picture to post]

        Returns:
            [Picture] -- [Picture created on the server]
        """
        self.getTokens()
        api_url = '{0}pictures'.format(self.api_url_base)
        picture_json = {'timestamp': picture.timestamp, 'picPath': picture.picPath, "fk_place": picture.fk_place}
        response = self.session.post(api_url, json=picture_json)

        loaded_json = json.loads(response.text)
        pic = Picture(loaded_json.get('timestamp'), loaded_json.get('picPath'),
                      loaded_json.get('fk_place'), loaded_json.get('id'))
        return pic
コード例 #13
0
def showPicture(DBC, RES, ID=None, size=0):
    """
    shows the specified picture.. Should be the only thing called
    on the page.
    """
    import Image
    import cStringIO

    assert ID is not None

    picture = Picture(DBC, ID=ID)
    RES.contentType = picture.type
    if size:
        im = Image.open(cStringIO.StringIO(picture.picture))
        im.thumbnail((size, size))
        im.save(RES, im.format)
    else:
        RES.write(picture.picture)
コード例 #14
0
    def __init__(self, xmlfile):
        self.xmlfile = xmlfile
        if not os.path.exists(self.xmlfile):
            return
        try:
            tree = ElementTree.parse(self.xmlfile)
            p = tree.getroot()

            # 地图
            self.map = Map(p)

            # get picture para class
            self.picture = Picture(p, self.map.clipborders)

            # Get the micaps files list
            self.micapsfiles = []
            micapsfiles = p.find("MicapsFiles").getchildren()
            for micapsfile in micapsfiles:
                self.micapsfiles.append(MicapsFile(micapsfile))

        except Exception as err:
            print(u'【{0}】{1}-{2}'.format(self.xmlfile, err, datetime.now()))
            return None
コード例 #15
0
ファイル: main.py プロジェクト: s-haya-123/subtitles
# -*- coding:utf-8 -*-
from flask import Flask, jsonify, request, render_template, session, redirect, url_for, send_from_directory
from werkzeug import secure_filename
import os
from Picture import Picture

#import MeCab

UPLOAD_FOLDER = './uploads'
app = Flask(__name__, static_url_path='', static_folder='./static')
app.config['JSON_AS_ASCII'] = False
app.secret_key = 'test'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
pic = Picture()


@app.route('/', methods=['GET'])
def start():
    return render_template('index.html')


@app.route('/send', methods=['GET', 'POST'])
def send():
    if request.method == 'POST':
        imgFile = request.files['img_file']
        if imgFile:
            filename = secure_filename(imgFile.filename)
            imgFile = pic.writeDescription(imgFile)
            imgFile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            imgUrl = "/uploads/" + filename
            return render_template('index.html', url=imgUrl)
コード例 #16
0
from Picture import Picture
from Line import Line
from Rectangle import Rectangle
from Text import Text

aPicture = Picture()
aPicture.Add(Text())
aPicture.Add(Line())
aPicture.Add(Rectangle())

picture = Picture()
picture.Add(Line())
picture.Add(Rectangle())
picture.Add(aPicture)
picture.Add(Line())

picture.Draw()
コード例 #17
0
    def toDictionary(self, options=[], user=None):
        '''For packaging to JSON output.

        options input is list of Vision.Options when we want more information
        fetched from DB and placed into objects
       
        This batches up queries for pictures and comments across all the
        visions. Whenever we want to get all this data across a list of 
        visions, it is good to use VisionList.toDictionary() instead of the
        individual toDictionary() calls on objects.

        'user' parameter is only used when LIKES in provided as
        an option. If it is passed in, we also check whether this user likes
        the visions or not.
        '''
        from User import User

        retObj = []

        # Start collecting picture ids
        pictureIds = set()
        if Vision.Options.PICTURE in options:
            pictureIds = set([vision.pictureId() for vision in self.visions()])

        # Get parent users if we need them
        parentUserIds = set()
        if Vision.Options.PARENT_USER in options:
            parentVisionIds = set([vision.parentId()
                                                 for vision in self.visions()])
            parentVisionIds.discard(0)
            parentVisions = VisionList.getByIds(parentVisionIds,
                                                allowRemovedVisions=True)
            idToParentVisions = dict([(v.id(), v)
                                             for v in parentVisions.visions()])
            parentUserIds = set([parent.userId()
                                        for parent in parentVisions.visions()])

        # Get all users (including parent users if needed)
        userIds = set([vision.userId() for vision in self.visions()])
        users = User.getByUserIds(userIds.union(parentUserIds))
        idToUser = dict([(u.id(), u) for u in users])

        # If COMMENTS, get comments
        if Vision.Options.COMMENTS in options:
            commentList = VisionCommentList.getEmptyList()
            for vision in self.visions():
                # TODO: Speed up performance of this some time!
                commentList.extend(vision.comments(5))

            idToComments = {}
            for comment in commentList.comments():
                if not comment.visionId() in idToComments:
                    idToComments[comment.visionId()] = [comment]
                else:
                    idToComments[comment.visionId()].append(comment)

                if Vision.Options.COMMENT_PICTURES:
                    if comment.hasPicture():
                        pictureIds.add(comment.pictureId())
            authorIds = set([comment.authorId() 
                                        for comment in commentList.comments()])
            authors = User.getByUserIds(authorIds)
            idToAuthor = dict([(author.id(), author) for author in authors])

            # If COMMENT_LIKES
            if Vision.Options.COMMENT_LIKES in options:
                commentIds = [c.id() for c in commentList.comments()]
                tuples = DataApi.getVisionCommentListLikeCount(commentIds)
                idToCommentLikes = dict([(commentId, count)
                                                for commentId, count in tuples])
                if user:
                    commentUserLikes = DataApi.getVisionCommentIdsLikedByUser(
                                                        commentIds, user.id())

        # If LIKES, get vision likes in batch
        if Vision.Options.LIKES in options:
            visionIds = [v.id() for v in self.visions()]
            tuples = DataApi.getVisionListLikeCount(visionIds)
            idToLikes = dict([(visionId, count) for visionId, count in tuples])
            if user:
                userLikes = DataApi.getVisionIdsLikedByUser(visionIds,
                                                            user.id())

        # Get pictures and hash them
        if (Vision.Options.PICTURE in options) or \
           (Vision.Options.COMMENT_PICTURES in options):
            pictureIds.discard(0)
            pictures = Picture.getByIds(pictureIds)
            idToPicture = dict([(picture.id(), picture)
                                                      for picture in pictures])
            idToPicture[0] = ""

        # Now start building object list to return
        for vision in self.visions():
            obj = vision.toDictionary()
            if Vision.Options.USER in options:
                obj[Vision.Key.USER] = idToUser[vision.userId()].toDictionary()

            # If PICTURE
            if Vision.Options.PICTURE in options:
                if vision.pictureId != 0:
                    picture = idToPicture[vision.pictureId()].toDictionary()
                    obj[Vision.Key.PICTURE] = picture
            # If COMMENTS
            if Vision.Options.COMMENTS in options:
                obj[Vision.Key.COMMENTS] = []
                if vision.id() in idToComments:
                    for comment in idToComments[vision.id()]:
                        commentObj = comment.toDictionary()
                        author = idToAuthor[comment.authorId()]
                        commentObj[VisionComment.Key.AUTHOR] = author.toDictionary()
                        if Vision.Options.COMMENT_LIKES in options:
                            commentObj[VisionComment.Key.LIKE] = {
                                            VisionComment.Key.LIKE_COUNT:
                                            idToCommentLikes[comment.id()]
                                            if comment.id() in idToCommentLikes
                                            else 0 }
                            if user:
                                commentObj[VisionComment.Key.LIKE]\
                                          [VisionComment.Key.USER_LIKE] = \
                                            comment.id() in commentUserLikes
                            if Vision.Options.COMMENT_PICTURES in options:
                                if comment.hasPicture() and\
                                   comment.pictureId() in idToPicture:
                                    cp = idToPicture[comment.pictureId()]
                                    commentObj[VisionComment.Key.PICTURE] =\
                                                            cp.toDictionary()
                        obj[Vision.Key.COMMENTS].append(commentObj)

            # If PARENT_USER
            if Vision.Options.PARENT_USER in options:
                if not vision.isOriginalVision():
                    if vision.parentId() in idToParentVisions:
                        parentVision = idToParentVisions[vision.parentId()]
                        if parentVision.userId() in idToUser:
                            parentUser = idToUser[parentVision.userId()]
                            obj[Vision.Key.PARENT_USER] = \
                                                     parentUser.toDictionary()
            # If LIKES
            if Vision.Options.LIKES in options:
                obj[Vision.Key.LIKE] = { Vision.Key.LIKE_COUNT: 
                                         idToLikes[vision.id()]
                                         if vision.id() in idToLikes else 0 }
                if user:
                    obj[Vision.Key.LIKE][Vision.Key.USER_LIKE] = \
                                                    vision.id() in userLikes

            # finally append object to list
            retObj.append(obj)
        return retObj
コード例 #18
0
def main(nombreImagen, rangoBinarizacion):
	print 'Julio 2013: Osvaldo Hinojosa'

	im = Picture(nombreImagen) # obtenemos las caracteristicas de la imagen
	
	# si la imagen supera los 300 pixeles de ancho o alto la redimensionamos
	# para mayor velocidad
	REDUCIR = False
	new_w = im.w
	new_h = im.h
	while new_w > 300 or new_h > 300: # calculamos el nuevo ancho
		new_w = new_w/2
		new_h = new_h/2
		REDUCIR = True
	if REDUCIR:
		ta = Tamano(im)
		imagenReducida = ta.redimensionar(new_w, new_h)
		# sustituimos a los nuevos valores
		im.w = new_w
		im.h = new_h
		im.pixeles = imagenReducida.load()

	
	pm = PictureManage(im) # jugamos con la imagen
	mascaraX, mascaraY = sobel() # cargamos la mascara, tiene que ser de 3x3

	# aplicar convolucion para gx
	imaGradienteX = pm.convolucion(mascaraX)
	# aplicar convolucion para gy
	imaGradienteY = pm.convolucion(mascaraY) 
	# aplicamos convolucion
	imaConvolucion = pm.convolucion(mascaraX, mascaraY)
	
	# aplicamos binarizacion
	imaBinarizacion = pm.binarizacion(imaConvolucion, rangoBinarizacion)
	
	# detectar objetos
	# pixel = de que color son los objetos a buscar
	# 'blanco' = bordes || 'negro' = cosas que no sean bordes
	pm.buscarObjetos(imaBinarizacion, pixel='blanco') # le mandamos la imagen 
													  # y el color del pixel a buscar
		
	# detectamos las esquinas de la imagen
	pixelesEsquinas = pm.esquinas(imaBinarizacion)
	
	# engordamos pixeles de toda la imagen, el valor del nivel debe ser 1, 2 o 3.
	imagenBorde = pm.engordarBorde(imaBinarizacion, nivel=1)

	# volvemos a encontrar objetos, ahora con los bordes mas gruesos
	# esto para que la lista de '._objetos' se actualize y detectar poligonos
	# puedar correr sin problemas.
	pm.buscarObjetos(imagenBorde, pixel='blanco')

	# detectar poligonos
	poligonos, imaPoligonos = pm.detectarPoligonos(imaBinarizacion, pixelesEsquinas)
	
	im.imReducida = imaPoligonos # se sustituye el valor de la imagen copia
								 # esta trae las nuevas dimensiones.
								 # Es necesario en el metodo 'dibujarCirculos()'
	
	# detectar cosas redondas de los objetos que no fueron poligonos
	pm.detectarCirculos(imaPoligonos, imaGradienteX, imaGradienteY)
	
	# distigir entre eclipses y circulos
	''' PENDIENTE '''
コード例 #19
0
def main(nombreImagen, rangoBinarizacion):
    print 'Julio 2013: Osvaldo Hinojosa'

    im = Picture(nombreImagen)  # obtenemos las caracteristicas de la imagen

    # si la imagen supera los 300 pixeles de ancho o alto la redimensionamos
    # para mayor velocidad
    REDUCIR = False
    new_w = im.w
    new_h = im.h
    while new_w > 300 or new_h > 300:  # calculamos el nuevo ancho
        new_w = new_w / 2
        new_h = new_h / 2
        REDUCIR = True
    if REDUCIR:
        ta = Tamano(im)
        imagenReducida = ta.redimensionar(new_w, new_h)
        # sustituimos a los nuevos valores
        im.w = new_w
        im.h = new_h
        im.pixeles = imagenReducida.load()

    pm = PictureManage(im)  # jugamos con la imagen
    mascaraX, mascaraY = sobel()  # cargamos la mascara, tiene que ser de 3x3

    # aplicar convolucion para gx
    imaGradienteX = pm.convolucion(mascaraX)
    # aplicar convolucion para gy
    imaGradienteY = pm.convolucion(mascaraY)
    # aplicamos convolucion
    imaConvolucion = pm.convolucion(mascaraX, mascaraY)

    # aplicamos binarizacion
    imaBinarizacion = pm.binarizacion(imaConvolucion, rangoBinarizacion)

    # detectar objetos
    # pixel = de que color son los objetos a buscar
    # 'blanco' = bordes || 'negro' = cosas que no sean bordes
    pm.buscarObjetos(imaBinarizacion, pixel='blanco')  # le mandamos la imagen
    # y el color del pixel a buscar

    # detectamos las esquinas de la imagen
    pixelesEsquinas = pm.esquinas(imaBinarizacion)

    # engordamos pixeles de toda la imagen, el valor del nivel debe ser 1, 2 o 3.
    imagenBorde = pm.engordarBorde(imaBinarizacion, nivel=1)

    # volvemos a encontrar objetos, ahora con los bordes mas gruesos
    # esto para que la lista de '._objetos' se actualize y detectar poligonos
    # puedar correr sin problemas.
    pm.buscarObjetos(imagenBorde, pixel='blanco')

    # detectar poligonos
    poligonos, imaPoligonos = pm.detectarPoligonos(imaBinarizacion,
                                                   pixelesEsquinas)

    # CLASIFICAR LOS POLIGONOS DETECTADOS
    ''' PENDIENTE '''

    im.imReducida = imaPoligonos  # se sustituye el valor de la imagen copia
    # esta trae las nuevas dimensiones.
    # Es necesario en el metodo 'dibujarCirculos()'

    # detectar cosas redondas de los objetos que no fueron poligonos
    pm.detectarCirculos(imaPoligonos, imaGradienteX, imaGradienteY)

    # distigir entre eclipses y circulos
    ''' PENDIENTE '''
コード例 #20
0
ファイル: Database.py プロジェクト: lukstafi/subte
                headway = frequency_node.findtext('headway')

                trip_route = TripRoute.get(int(trip_route_id))
                if trip_route is None:
                    print "Missing trip route id ", trip_route_id
                    print "for frequency id ", frequency_id
                    continue
                    

                frequency = trip_route.add_frequency(start, end, headway)
                frequency.frequency_id = int(frequency_id)
                frequency.gtfs_id = gtfs_id


            for picture_node in tree.getroot().findall('Picture'):
                picture_id = picture_node.get('id', Picture.new_id())
                relative_image = picture_node.findtext('image')
                stop_id = picture_node.findtext('stop_id', -1)
                ignored = picture_node.findtext('ignored')
                latitude = picture_node.findtext('latitude')
                longitude = picture_node.findtext('longitude')
                orientation = picture_node.findtext('orientation')

                # update the image with the full path
                dirname = os.path.dirname(fname)
                image = os.path.join(dirname, relative_image)

                try:
                    stop_id = int(stop_id)
                    ignored = bool(int(ignored))
コード例 #21
0
    time.sleep(1)

    #Actuators
    outsideFan = TimedDigitalActuator(20)
    time.sleep(1)
    insideFan = TimedDigitalActuator(21)
    time.sleep(1)
    humidifier = TimedDigitalActuator(16)
    time.sleep(1)
    hatch = Hatch()
    time.sleep(1)
    stepper = Stepper()
    time.sleep(1)

    #picture
    picture = Picture("Plant1")

    #silencer
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    timeToSilence = 0
    alloff = False

    while True:

        if not GPIO.input(12):
            print "Silence"
            timeToSilence = time.time() + 60 * 60

        if timeToSilence > time.time():
コード例 #22
0
    def game(self, screen, background):
        music = pygame.mixer.music
        music.load("files/music.ogg")
        music.play(-1)

        RULES_rect = pygame.Rect(80, 740, 100, 50)
        NEXT_TURN_rect = pygame.Rect(220, 740, 100, 50)
        self.NEXT_TURN = PygButton.PygButton(
            NEXT_TURN_rect, 'Next Turn', (0, 0, 0), (255, 0, 0),
            pygame.font.SysFont("Verdana", 18))
        self.RULES = PygButton.PygButton(RULES_rect, 'Rules', (0, 0, 0),
                                         (255, 0, 0),
                                         pygame.font.SysFont("Verdana", 20))

        self.spinner = Spinner(screen)
        self.dice = Dice(screen, 140, 225)
        self.dice2 = Dice(screen, 140, 285)

        self.ANGLE = 0
        self.SPINS_TILL_DONE = 0
        self.DICE_TILL_DONE = 0
        self.showDiceNum = 0
        self.showDiceNum2 = 1
        self.switchDie = 0

        self.player = Player(screen)
        self.PLAYER_TURN = 0
        self.MOVE_SPEED = 20
        self.movePlayer = False
        self.PLAYER_MOVE_X = 0
        self.PLAYER_MOVE_Y = 0

        picture = Picture(screen)

        n = True

        keep_going = True
        clock = pygame.time.Clock()
        hideRules = True
        muteState = False

        while keep_going:
            clock.tick(20)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    keep_going = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        hideRules = True
                    elif event.key == pygame.K_ESCAPE:
                        keep_going = False
                    elif event.key == pygame.K_q:
                        keep_going = False
                    elif event.key == pygame.K_p:
                        if muteState == False:
                            music.pause()
                            muteState = True
                        else:
                            music.unpause()
                            muteState = False

                if event.type == pygame.MOUSEBUTTONUP:

                    x, y = pygame.mouse.get_pos()
                    #        print (x)
                    #        print (y)

                    spin = self.checkDoSpinner()

                    if spin == False:
                        dice = self.checkDoDice()

                        if dice == False:
                            self.movePlayer = True

                            x, y = pygame.mouse.get_pos()
                            self.PLAYER_MOVE_X = x
                            self.PLAYER_MOVE_Y = y

                    self.distance()

                if 'click' in self.NEXT_TURN.handleEvent(event):

                    self.movePlayer = False

                    if self.PLAYER_TURN == 2:
                        self.PLAYER_TURN = 0
                    else:
                        self.PLAYER_TURN += 1
                #    print ("CLICKED")
                #  if random.randint(0, 1) == 0:

                    picture.newRotatePicture(random.randint(1, 4), True,
                                             self.player)

                if 'click' in self.RULES.handleEvent(event):
                    hideRules = False
                    self.movePlayer = False

            screen.blit(background, (0, 0))

            circus = ("C", "", "R", "C", "U", "S")
            circles = ("C", "", "R", "C", "L", "E", "S")

            if hideRules:
                picture.drawPicture()
                picture.rotatePicture(self.player)
                self.NEXT_TURN.draw(screen)
                self.RULES.draw(screen)
                for i in range(0, 6):
                    Label(screen, circus[i], 80, 50, 230 + i * 80)
                for i in range(0, 7):
                    Label(screen, circles[i], 80, 1100, 200 + i * 80)
                Label(screen, "I", 80, 60, 310)
                Label(screen, "I", 80, 1110, 280)
                Label(screen, "Player 1", 25, 150, 700)
                Label(screen, "Player 2", 25, 950, 70)
                Label(screen, "Player 3", 25, 910, 750)
                self.spinnerAnimation()
                self.diceAnimation()
                self.playerAnimation()

            else:
                Photo(screen, "files/rules.png", 0, 0)

            pygame.display.flip()
コード例 #23
0
from Line import Line
from Rectangle import Rectangle
from Text import Text
from Picture import Picture

if __name__ == '__main__':
    picture1 = Picture()
    picture1.add(Line())
    picture1.add(Rectangle())

    picture2 = Picture()
    picture2.add(Text())
    picture2.add(Line())
    picture2.add(Rectangle())

    picture1.add(picture2)

    picture1.add(Line())
    picture1.draw()
コード例 #24
0
'''
	pictureTest.py

'''

#Add the api.py (parent) folder
import sys
sys.path.append("../objects")

from Picture import Picture
from Vision import Vision

v = Vision()
v.setInfo(1,1,"hi!", 1, 0, '12312312323')

p = Picture()
#filename is the name of the file on the web server
p.setInfo(1,'www.facebook.com/hi.jpg', '1')

v.setPicture(p)

print(v.toDictionary())
コード例 #25
0
ファイル: Vision.py プロジェクト: nikilster/projectAwesome
 def picture(self):
     '''Returns Picture object for this Vision, or None'''
     return Picture.getById(self.pictureId())
コード例 #26
0
ファイル: Main.py プロジェクト: cog-isa/mpf-simple
def get_set(folder, iterations, repeats, learning=True):
    pygame.init()
    screen = pygame.display.set_mode(DISPLAY)
    pygame.display.set_caption("Pictures")
    background = Surface(DISPLAY)
    background.fill(Color("#000000"))

    p = Picture()
    p.load('pictures/samples/car/01.txt')
    raw_set = generate_pics(['bird', 'cactus', 'car', 'cup', 'helicopter', 'loco', 'octopus', 'tree'], 8)
    #raw_set = generate_pics(['loco', 'octopus', 'tree'], 8)
    #getting learning set

    if learning:
        p_name = 'train-images.idx3-ubyte'
        l_name = 'train-labels.idx1-ubyte'
    else:
        p_name = 't10k-images.idx3-ubyte'
        l_name = 't10k-labels.idx1-ubyte'
    p_f = open(folder+'/'+p_name, 'wb')
    l_f = open(folder+'/'+l_name, 'wb')
    l_f.write(struct.pack('>i', 48*4*repeats))
    p_f.write(struct.pack('>i', 48*4*repeats))
    p_f.write(struct.pack('>i', 32))
    p_f.write(struct.pack('>i', 32))

    for label in raw_set:
        for img in raw_set[label]:
            p = img
            for r in range(3*repeats):
                pic = Picture(p.body)
                for i in range(iterations):
                    pic = add_noise(pic, 40)
                    pic = add_noise(pic, -40)
                for row in pic.body:
                    for i in row:
                        p_f.write(struct.pack('B', i))
                l_f.write(struct.pack('B', label))
                pic.show(screen, PIXEL_SIZE)
                pygame.display.update()
	pygame.image.save(screen, 'screen'+str(label)+'.png')
    for label in raw_set:
        for img in raw_set[label]:
            p = img
            for r in range(repeats):
                pic = Picture(p.body)
                for i in range(iterations):
                    pic = add_noise(pic, 40)
                    pic = add_noise(pic, -40)
                for row in pic.body:
                    for i in row:
                        p_f.write(struct.pack('B', i))
                l_f.write(struct.pack('B', label))
                pic.show(screen, PIXEL_SIZE)
                pygame.display.update()
	pygame.image.save(screen, 'screen'+str(r)+'.png')
    p_f.close()
    l_f.close()
コード例 #27
0
    def Draw(self, products, micapsfile, debug=True):
        """
        根据产品参数绘制图像
        :param micapsfile: 指定绘制产品中包含的一个micapsfile
        :param debug: 调试状态
        :param products: 产品参数 
        :return: 
        """
        self.UpdateData(products, micapsfile)
        extents = products.picture.extents
        xmax = extents.xmax
        xmin = extents.xmin
        ymax = extents.ymax
        ymin = extents.ymin

        # 设置绘图画板的宽和高 单位:英寸
        h = products.picture.height
        if products.map.projection.name == 'sall':  # 等经纬度投影时不用配置本身的宽度,直接根据宽高比得到
            w = h * np.math.fabs(
                (xmax - xmin) / (ymax - ymin)) * products.picture.widthshrink
        else:
            w = products.picture.width

        # 创建画布
        fig = plt.figure(figsize=(w, h),
                         dpi=products.picture.dpi,
                         facecolor="white")  # 必须在前面
        ax = fig.add_subplot(111)
        ax.spines['bottom'].set_linewidth(products.map.projection.axisthick)
        ax.spines['left'].set_linewidth(products.map.projection.axisthick)
        ax.spines['right'].set_linewidth(products.map.projection.axisthick)
        ax.spines['top'].set_linewidth(products.map.projection.axisthick)
        # 设置绘图区域
        plt.xlim(xmin, xmax)
        plt.ylim(ymin, ymax)

        # 背景透明
        fig.patch.set_alpha(products.picture.opacity)

        # 坐标系统尽可能靠近绘图区边界
        fig.tight_layout(pad=products.picture.pad)

        clipborder = products.map.clipborders[0]

        # 获得产品投影
        from Projection import Projection
        m = Projection.GetProjection(products)

        if m is not plt:
            # 用投影更新经纬度数据
            self.X, self.Y = Micaps.UpdateXY(m, self.X, self.Y)
            # 用投影更新产品参数中涉及经纬度的数据
            Micaps.Update(products, m)
            # 画世界底图
            Map.DrawWorld(products, m)

        # 绘制裁切区域边界
        patch = Map.DrawClipBorders(products.map.clipborders)

        # draw parallels and meridians.
        Map.DrawGridLine(products, m)

        cmap = nclcmaps.cmaps(
            micapsfile.legend.micapslegendcolor)  # cm.jet  temp_diff_18lev
        vmax = math.ceil(self.max)
        vmin = math.floor(self.min)
        levels = arange(vmin - self.distance, vmax + self.distance + 0.1,
                        self.distance)

        if micapsfile.legend.micapslegendvalue:
            level = levels
        else:
            level = micapsfile.legend.legendvalue

        # 绘制等值线 ------ 等值线和标注是一体的
        c = micapsfile.contour

        Map.DrawContourAndMark(contour=c,
                               x=self.X,
                               y=self.Y,
                               z=self.Z,
                               level=level,
                               clipborder=clipborder,
                               patch=patch,
                               m=m)

        cf = micapsfile.contour
        cbar = micapsfile.legend
        extend = micapsfile.legend.extend
        # 绘制色斑图 ------ 色版图、图例、裁切是一体的
        Map.DrawContourfAndLegend(contourf=cf,
                                  legend=cbar,
                                  clipborder=clipborder,
                                  patch=patch,
                                  cmap=cmap,
                                  levels=levels,
                                  extend=extend,
                                  extents=extents,
                                  x=self.X,
                                  y=self.Y,
                                  z=self.Z,
                                  m=m)

        # 绘制描述文本
        MicapsFile.MicapsFile.DrawTitle(m, micapsfile.title, self.title)

        self.DrawUV(m, micapsfile, clipborder, patch)

        # 绘制地图
        Map.DrawBorders(m, products)

        # 绘制散点
        if micapsfile.contour.scatter:
            if hasattr(self, 'x1'):
                m.scatter(self.x1,
                          self.y1,
                          s=micapsfile.contour.radius,
                          c=self.z1,
                          alpha=micapsfile.contour.alpha,
                          edgecolors='b')
            else:
                m.scatter(self.X,
                          self.Y,
                          s=micapsfile.contour.radius,
                          c=self.Z,
                          alpha=micapsfile.contour.alpha,
                          edgecolors='b')

        # 绘制站点
        stations = products.map.stations
        if stations.visible:
            # 'code': code, 'lon': lon, 'lat': lat, 'height': height,
            # 'iclass': iclass, 'infosum': infosum, 'name': info[0]
            # stations_tuple = tuple(stations.micapsdata.stations)
            # (code, lat, lon, height, iclass, infosum, info[0])
            # stations_array = np.array(stations.micapsdata.stations, dtype=[
            #     ('code', 'U'),
            #     ('lat', np.float32),
            #     ('lon', np.float32),
            #     ('height', np.float32),
            #     ('iclass', 'i'),
            #     ('infosum', 'i'),
            #     ('info', 'U')
            # ])

            # stations_array = [list(ele) for ele in zip(*stations.micapsdata.stations)]
            stations_array = zip(*stations.micapsdata.stations)
            # 画站点mark
            if m is not plt:
                stations_array[2], stations_array[1] = \
                    Micaps.UpdateXY(m, stations_array[2], stations_array[1])
            marker = MarkerStyle(stations.markstyle[0], stations.markstyle[1])
            m.scatter(stations_array[2],
                      stations_array[1],
                      marker=marker,
                      s=stations.radius,
                      c=stations.color,
                      alpha=stations.alpha,
                      edgecolors=stations.edgecolors)

            # 画站点文本

            fontfile = r"C:\WINDOWS\Fonts\{0}".format(stations.font[1])
            if not os.path.exists(fontfile):
                font = FontProperties(size=stations.font[0],
                                      weight=stations.font[2])
            else:
                font = FontProperties(fname=fontfile,
                                      size=stations.font[0],
                                      weight=stations.font[2])
            for sta in stations.micapsdata.stations:
                if m is not plt:
                    lon, lat = Micaps.UpdateXY(m, sta[2], sta[1])
                    lon1, lat1 = Micaps.UpdateXY(m, sta[2] + stations.detax,
                                                 sta[1])
                    deta = lon1 - lon
                else:
                    lon, lat = sta[2], sta[1]
                    deta = stations.detax
                plt.text(lon + deta,
                         lat,
                         sta[6],
                         fontproperties=font,
                         rotation=0,
                         color=stations.font[3],
                         ha='left',
                         va='center')

        # 接近收尾

        # self.Clip(clipborder, fig, patch)

        # 存图
        Picture.savePicture(fig, products.picture.picfile)

        print(products.picture.picfile + u'存图成功!')
        if debug:
            plt.show()
コード例 #28
0
    print('一批保存完成...')


def save2Text(filename, content):
    f = open(filename, 'w', encoding='utf-8')
    f.write(content)
    f.close()



if __name__ == '__main__':

    for i in range(35):
        print('第%d批数据开始处理' %i)
        content = ask_request(str(i))
        # 写入文件
        save2Text('json.txt',str(content))
        # 读取文件
        with open('json.txt', 'r', encoding='utf-8') as f:
            temp = f.read()
        # 截取成json字符串
        pic_json = temp[2:-3]
        print(pic_json)
        # 映射成为类
        list = demjson.decode(pic_json, Picture)
        plist = []
        for i in range(0, len(list)):
            plist.append(Picture(list[i]))
        save2Db(plist)
        # save2Local(plist)