コード例 #1
0
class SeventhScreen(Screen):

    # def on_pre_enter(self):
    # 	providers = ()
    # 	providers += (('picamera', 'camera_picamera', 'CameraPiCamera'), )
    # 	providers += (('gi', 'camera_gi', 'CameraGi'), )
    # 	providers += (('opencv', 'camera_opencv', 'CameraOpenCV'), )
    # 	Camera = core_select_lib('camera', (providers))

    def on_enter(self):
        self.cam = Camera(play=False, resolution=(640, 480))
        self.ids.cambox.add_widget(self.cam)

    def capture(self):
        timestr = time.strftime("%Y%m%d_%H%M%S")
        self.cam.export_to_png("IMG_{}.png".format(timestr))
        print("capture")

    def play(self):
        self.cam.play = not self.cam.play
        print("play")

    def on_leave(self):
        self.cam.play = False
        self.ids.cambox.remove_widget(self.cam)
コード例 #2
0
ファイル: main.py プロジェクト: KobeUyeda/Google
class works(FloatLayout):
    def __init__(self):
        super().__init__()

        self.camobj = Camera(play=True, index=0, resolution=(1000, 1000))
        self.add_widget(self.camobj)

        self.flip = Button(text="Switch to different camera")
        self.flip.bind(on_press=self.camflip)
        self.flip.size_hint = (.5, .1)
        self.add_widget(self.flip)

        self.flip = Button(text="Capture")
        self.flip.bind(on_press=self.take)
        self.flip.pos_hint = {'right': 1}
        self.flip.size_hint = (.5, .1)
        self.add_widget(self.flip)

    def take(self, f):
        self.camobj.export_to_png('lower.png')
        print('work')

    def camflip(self, f):
        if self.camobj.index == 0:
            self.camobj.index = 1
        elif self.camobj.index == 1:
            self.camobj.index = 0
コード例 #3
0
class CameraExample(App):
    def build(self):

        layout = BoxLayout(orientation='vertical')

        # create a camera object

        self.cameraObject = Camera(play=False)

        self.cameraObject.play = True

        self.cameraObject.resolution = (300, 300)  # Define resolution

        # button for taking photograph( can also be defined in kv file )

        self.camaraClick = Button(text="capture")

        self.camaraClick.size_hint = (.5, .2)

        self.camaraClick.pos_hint = {'x': .25, 'y': .75}

        self.camaraClick.bind(on_press=self.onCameraClick)

        layout.add_widget(self.cameraObject)

        layout.add_widget(self.camaraClick)

        return layout

    # current frame of the video as the photograph

    def onCameraClick(self, *args):

        self.cameraObject.export_to_png('selfie_{}.jpg')
コード例 #4
0
ファイル: ws.py プロジェクト: Shree3245/ESA_PROJECT_FINAL
class CameraExample(App):

 

    def build(self):

        layout = BoxLayout(orientation='vertical')

       

        # Create a camera object

        self.cameraObject            = Camera(play=False)

        self.cameraObject.play       = True

        self.cameraObject.resolution = (300, 300) # Specify the resolution

       

        # Create a button for taking photograph

        self.camaraClick = Button(text="Take Photo")

        self.camaraClick.size_hint=(.5, .2)

        self.camaraClick.pos_hint={'x': .25, 'y':.75}

 

        # bind the button's on_press to onCameraClick

        self.camaraClick.bind(on_press=self.onCameraClick)

       

        # add camera and button to the layout

        layout.add_widget(self.cameraObject)

        layout.add_widget(self.camaraClick)

       

        # return the root widget

        return layout

 

    # Take the current frame of the video as the photo graph       

    def onCameraClick(self, *args):

        self.cameraObject.export_to_png('/kivyexamples/selfie.png')
コード例 #5
0
class Capture(FloatLayout):
    def __init__(self, sn_root, **kwargs):
        super().__init__(**kwargs)
        self.sn_root = sn_root

        self.cameraObject = Camera(play=False)
        self.cameraObject.play = True
        self.cameraObject.resolution = (500, 500)
        self.cameraObject.pos_hint = {'x': 0, 'y': 0.2}

        anchor1 = AnchorLayout(anchor_x='left', anchor_y='bottom')
        home_button = Button(text="Home", size_hint=(0.33, .30))
        home_button.bind(on_press=self.go_home)
        anchor1.add_widget(home_button)
        self.add_widget(anchor1)

        anchor2 = AnchorLayout(anchor_x='center', anchor_y='bottom')
        cameraClick = Button(text="Take Photo", size_hint=(0.33, .30))
        cameraClick.bind(on_press=self.onCameraClick)
        anchor2.add_widget(cameraClick)
        self.add_widget(anchor2)

        anchor3 = AnchorLayout(anchor_x='right', anchor_y='bottom')
        cameraClick = Button(text="Evaluate", size_hint=(0.33, .30))
        cameraClick.bind(on_press=self.go_results)
        anchor3.add_widget(cameraClick)
        self.add_widget(anchor3)

        self.add_widget(self.cameraObject)

    def onCameraClick(self, *args):
        timest = time.strftime("%Y%m%d-%H%M%S")
        self.cameraObject.export_to_png(
            os.path.join(".\\gui\\captures", ("capture_" + timest + ".png")))

    def go_home(self, instance):
        self.sn_root.go_home()

    def go_results(self, instance):
        self.sn_root.go_results()
        list_of_files = glob.glob(
            '.\\gui\\captures\\*.png'
        )  # * means all if need specific format then *.<format>
        latest_file = max(list_of_files, key=os.path.getctime)
        self.sn_root.results_.print_results(latest_file)
コード例 #6
0
class CameraExample(App):

    def build(self):
        self.clicked = False
        self.layout = FloatLayout(orientation='vertical')
        # Create a camera object
        self.cameraObject            = Camera(play=False, pos=(0,346))
        self.cameraObject.play       = True
        self.cameraObject.resolution = (1000, 600) # Specify the resolution
        # Create a button for taking photograph
        self.cameraClick = Button(text="Take Photo and Evaluate", pos=(0, 440), font_size='60dp')
        self.cameraClick.size_hint=(1, .2)
        # bind the button's on_press to onCameraClick
        self.cameraClick.bind(on_press=self.onCameraClick)
        # add camera and button to the layout
        self.layout.add_widget(self.cameraObject)
        self.layout.add_widget(self.cameraClick)
        return self.layout 

    def delete_output_pngs(self):
        import glob, os, multiprocessing
        p = multiprocessing.Pool(4)
        p.map(os.remove, glob.glob("output*.png"))

    # Take the current frame of the video as the photo graph       
    def onCameraClick(self, *args):
        Cache.remove('kv.image')
        Cache.remove('kv.texture')
        self.delete_output_pngs()
        if self.clicked == True:
            self.layout.remove_widget(self.output)
        self.clicked = True
        self.cameraObject.export_to_png('output.png')
        latex_string = image_to_latex('output.png')
        #latex_string = u'\\left. \\begin{array} { l } { 4 x ^ { 3 } + \\int _ { 0 } ^ { x } x ^ { 2 } d x } \\\\ { = 4 x ^ { 3 } + 3 x ^ { 3 } } \\\\ { = 7 x ^ { 3 } } \\end{array} \\right.'
        print latex_string.__repr__()
        latex_equations = split_into_equations(latex_string)
        print latex_equations
        self.output = Output(latex_equations, size_hint=(1, .35))
        self.layout.add_widget(self.output)
コード例 #7
0
ファイル: ejemplo3.py プロジェクト: kevinchuca/IAII
class CameraExample(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')

        # Create a camera object

        self.cameraObject = Camera(play=False)

        self.cameraObject.play = True

        self.cameraObject.resolution = (800, 500)  # Specify the resolution

        # Create a button for taking photograph

        self.camaraClick = Button(text="Take Photo",
                                  background_color=(0, 0, 255, 255))

        self.camaraClick.size_hint = (.5, .2)

        self.camaraClick.pos_hint = {'x': .25, 'y': .75}

        # bind the button's on_press to onCameraClick

        self.camaraClick.bind(on_press=self.onCameraClick)

        # add camera and button to the layout

        layout.add_widget(self.cameraObject)

        layout.add_widget(self.camaraClick)

        # return the root widget

        return layout

    # Take the current frame of the video as the photo graph

    def onCameraClick(self, *args):
        timestr = time.strftime("%Y%m%d_%H%M%S")
        self.cameraObject.export_to_png("inumero.jpg".format(timestr))
コード例 #8
0
class CamApp(App):

    def build(self):
        main_layout = FloatLayout(size=(300, 300))

        self.camera = Camera(resolution=(640, 480), play=True, pos_hint={'x': 0, 'y': .25}, size_hint=(1, .65))

        photo_button = Button(text='Photo', background_color=[0, 1, 1], font_size=20, pos_hint={'x': .15, 'y': 0}, size_hint=(.7, .2))
        photo_button.bind(on_press=self.photo)
        main_layout.add_widget(photo_button)

        return main_layout
    def photo(self, instance):
        print(self.camera.export_to_png())
コード例 #9
0
class CameraExample(App):
    pictaken = False
    imagedata = ""

    def build(self):
        self.layout = FloatLayout(size=(50, 50))

        # Create a camera object
        self.cameraObject = Camera(play=False)

        self.cameraObject.play = True

        self.cameraObject.resolution = (300, 300)  # Specify the resolution

        # Create a button for taking photograph

        self.camaraClick = Button(text="Take Photo")

        self.camaraClick.size_hint = (.1, .1)

        self.camaraClick.pos_hint = {'x': .30, 'y': .10}

        # bind the button's on_press to onCameraClick

        self.camaraClick.bind(on_press=self.onCameraClick)
        self.back = Button(text="back")

        self.back.size_hint = (.1, .1)

        self.back.pos_hint = {'x': .60, 'y': .10}

        # bind the button's on_press to onCameraClick

        self.back.bind(on_press=self.backclick)

        # add camera and button to the layout

        self.layout.add_widget(self.cameraObject)

        self.layout.add_widget(self.camaraClick)
        self.layout.add_widget(self.back)

        # return the root widget

        return self.layout

    # Take the current frame of the video as the photo graph

    def onCameraClick(self, *args):
        self.cameraObject.play = False
        self.cameraObject.export_to_png('/root/thisisthepicof.jpg')
        with open("/root/thisisthepicof.jpg", "rb") as imageFile:
            CameraExample.imagedata = base64.b64encode(imageFile.read())
            print('given size', len(CameraExample.imagedata))
            CameraExample.pictaken = True

    def backclick(self, *args):
        print('hi')
        self.layout.clear_widgets()
        self.cameraObject.resolution = (-1, -1)

        app1 = additem.additem1()

        app1.run()

        self.layout.walk_reverse()
コード例 #10
0
class MyApp(App):
    def build(self):
        self.title = 'Big Bang Factory'
        #--:Initiating plot pan
        self.fig, self.ax, self.canvas = self.PlotPan()
        self.fig0, self.ax0, self.canvas0 = self.PlotPan()

        #--: Home Page
        self.img = mpimg.imread('BBF_frontpage.png')
        self.ax.imshow(self.img)
        self.anim_running = True
        self.anim_compare = True
        self.settings_running = True
        self.lensing_running = True

        #--: Widgets
        btn_user = IconButton(source='./icons/user.png',
                              text='',
                              size_hint_x=None,
                              width=50)
        btn_user.bind(on_release=self.show_popup_user)

        btn_sim = IconButton(source='./icons/sim.png',
                             size_hint_x=None,
                             width=50)
        btn_sim.bind(on_release=self.show_popup_sim)

        btn_lens = IconButton(source='./icons/lens.png',
                              size_hint_x=None,
                              width=50)
        btn_lens.bind(on_release=self.lensing_icons)

        btn_settings = IconButton(source='./icons/settings.png',
                                  size_hint_x=None,
                                  width=50)
        btn_settings.bind(on_release=self.settings_icons)

        btn_home = IconButton(source='./icons/home.png',
                              size_hint_x=None,
                              width=50)
        btn_home.bind(on_release=self.clean)

        self.btn_pause = IconButton(source='./icons/pause.png',
                                    size_hint_x=None,
                                    width=50)
        self.btn_pause.bind(on_press=self.pause)

        self.btn_compare = IconButton(source='./icons/compare.ico',
                                      size_hint_x=None,
                                      width=50)
        self.btn_compare.bind(on_press=self.compare)

        self.btn_stop = IconButton(source='./icons/stop.png',
                                   size_hint_x=None,
                                   width=50)
        self.btn_stop.bind(on_press=self.sim_stop)

        self.btn_sim_save = IconButton(source='./icons/save.png',
                                       size_hint_x=None,
                                       width=50)
        self.btn_sim_save.bind(on_release=self.save_movie)

        self.btn_send = IconButton(source='./icons/send.ico',
                                   size_hint_x=None,
                                   width=50)
        self.btn_send.bind(on_release=self.send_movie)

        self.btn_database = IconButton(source='./icons/database.png',
                                       size_hint_x=None,
                                       width=50)
        self.btn_database.bind(on_release=self.show_popup_simselect)

        self.btn_savedir = IconButton(source='./icons/savedir.png',
                                      size_hint_x=None,
                                      width=50)
        self.btn_savedir.bind(on_release=self.show_popup_dirselect)

        self.btn_halo = IconButton(source='./icons/halo.png',
                                   size_hint_x=None,
                                   width=50)
        self.btn_halo.bind(on_release=self.HaloLensedImage)

        self.btn_cluster = IconButton(source='./icons/cluster.gif',
                                      size_hint_x=None,
                                      width=50)
        self.btn_cluster.bind(on_release=self.MapLensedImage)

        self.slider_comdist = Slider(min=0.0,
                                     max=100.0,
                                     value=10.0,
                                     step=10.0,
                                     orientation='horizontal',
                                     value_track=True,
                                     value_track_color=[1, 0, 0, 1],
                                     size_hint_x=None,
                                     width=150)

        #--:Page Layout
        #--- Page 1
        Pages = PageLayout(orientation="vertical")
        self.Box_sim = BoxLayout(orientation="horizontal")
        self.Box_sim.add_widget(self.canvas)
        self.label_status = Label(text='Welcome to BBF',
                                  size_hint_y=None,
                                  height='28dp')
        self.BigBox_sim = BoxLayout(orientation="vertical")
        self.BigBox_sim.add_widget(self.Box_sim)
        self.BigBox_sim.add_widget(self.label_status)
        Pages.add_widget(self.BigBox_sim)
        #--- Page 2
        self.Settings_Page = GridLayout(cols=1,
                                        row_force_default=True,
                                        row_default_height=40)
        self.subSettings_Page = GridLayout(cols=1,
                                           row_force_default=True,
                                           row_default_height=40)

        self.Settings_Page.add_widget(btn_user)
        self.Settings_Page.add_widget(btn_sim)
        self.Settings_Page.add_widget(btn_lens)
        self.Settings_Page.add_widget(btn_settings)
        self.Settings_Page.add_widget(self.btn_send)
        self.Settings_Page.add_widget(btn_home)

        self.Box_icons = BoxLayout(orientation='vertical')

        self.Box_icons.add_widget(self.Settings_Page)
        self.Box_icons.add_widget(self.subSettings_Page)

        Pages.add_widget(self.Box_icons)
        return Pages

    def PlotPan(self):
        #--:PLot Pan
        fig = plt.Figure(facecolor='0.7', frameon=False)
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        fig.add_axes(ax)
        canvas = FigureCanvasKivyAgg(fig)
        return fig, ax, canvas

    def compare(self, *args):
        if self.anim_compare:
            self.Box_sim.add_widget(self.canvas0)
            self.anim_compare = False
        else:
            self.Box_sim.remove_widget(self.canvas0)
            self.anim_compare = True

    def show_popup_user(self, *args):

        self.label_name = Image(source='./icons/name.png')
        self.input_name = TextInput(text='',
                                    multiline=False,
                                    size_hint_x=None,
                                    width=200)

        self.label_email = Image(source='./icons/email.png')
        self.input_email = TextInput(text='',
                                     multiline=False,
                                     size_hint_x=None,
                                     width=200)

        self.btn_cam = IconButton(source='./icons/photo.png')
        self.btn_cam.bind(on_release=self.show_popup_cam)

        Settings_content = BoxLayout(orientation='horizontal')

        subSettings_content = BoxLayout(orientation='vertical')

        user_content = GridLayout(cols=2, size_hint_y=None, height='58dp')

        user_content.add_widget(self.label_name)
        user_content.add_widget(self.input_name)
        user_content.add_widget(self.label_email)
        user_content.add_widget(self.input_email)

        subSettings_content.add_widget(Image(source='./icons/sir.png'))
        subSettings_content.add_widget(user_content)

        Settings_content.add_widget(subSettings_content)
        Settings_content.add_widget(self.btn_cam)

        self.popup = Popup(title='',
                           size_hint=(None, None),
                           size=(500, 200),
                           content=Settings_content,
                           auto_dismiss=True,
                           separator_height=0)
        self.popup.open()

    def lensing_icons(self, *args):
        self.Box_sim.add_widget(self.canvas0)
        self.subSettings_Page.remove_widget(self.btn_pause)
        self.subSettings_Page.remove_widget(self.btn_compare)
        #self.subSettings_Page.remove_widget(self.btn_preview)
        self.subSettings_Page.remove_widget(self.btn_sim_save)
        if self.lensing_running:
            self.subSettings_Page.add_widget(self.btn_halo)
            self.subSettings_Page.add_widget(self.btn_cluster)
            self.subSettings_Page.add_widget(self.slider_comdist)
            self.lensing_running = False
        else:
            self.subSettings_Page.remove_widget(self.btn_halo)
            self.subSettings_Page.remove_widget(self.btn_cluster)
            self.subSettings_Page.remove_widget(self.slider_comdist)
            self.lensing_running = True

    def settings_icons(self, *args):
        if self.settings_running:
            self.subSettings_Page.add_widget(self.btn_savedir)
            self.subSettings_Page.add_widget(self.btn_database)
            self.settings_running = False
        else:
            self.subSettings_Page.remove_widget(self.btn_savedir)
            self.subSettings_Page.remove_widget(self.btn_database)
            self.settings_running = True

    def show_popup_dirselect(self, *args):
        self.dirselect = FileChooserListView(dirselect=True)
        box_dir = BoxLayout(orientation='vertical')
        box_dir.add_widget(self.dirselect)

        btn_select = IconButton(source='./icons/select.ico',
                                size_hint_y=None,
                                height='48dp')
        btn_select.bind(on_release=self.selectdir)

        box_dir.add_widget(btn_select)
        self.popup_dirselect = Popup(title='',
                                     size_hint=(.680, .460),
                                     content=box_dir,
                                     auto_dismiss=True,
                                     separator_height=0)
        self.popup_dirselect.open()

    def show_popup_simselect(self, *args):
        self.simselect = FileChooserListView(dirselect=True)
        box_dir = BoxLayout(orientation='vertical')
        box_dir.add_widget(self.simselect)

        sim_select = IconButton(source='./icons/select.ico',
                                size_hint_y=None,
                                height='48dp')
        sim_select.bind(on_release=self.simselectdir)

        box_dir.add_widget(sim_select)
        self.popup_dirselect = Popup(title='',
                                     size_hint=(.680, .460),
                                     content=box_dir,
                                     auto_dismiss=True,
                                     separator_height=0)
        self.popup_dirselect.open()

    def selectdir(self, *args):
        self.savedir = self.dirselect.selection[0]
        print self.savedir
        self.popup_dirselect.dismiss()

    def simselectdir(self, *args):
        self.simdir = self.simselect.selection[0]
        print self.simdir
        self.popup_dirselect.dismiss()

    def show_popup_preview(self, *args):
        player = Video(source=self.savedir + "/" + self.img_filenamedir + "/" +
                       self.img_filenamedir + "_mux_movie.mp4",
                       state='play',
                       options={'allow_stretch': True})
        videobox = BoxLayout()
        videobox.add_widget(player)
        self.popup_player = Popup(title='',
                                  size_hint=(.680, .460),
                                  content=videobox,
                                  auto_dismiss=True,
                                  separator_height=0)
        self.popup_player.open()

    def show_popup_sim(self, *args):

        self.btn_sim_start = IconButton(source='./icons/play.png',
                                        text='',
                                        size_hint_y=None,
                                        height='48dp')
        self.btn_sim_start.bind(on_release=self.sim_start)

        self.image_dm = Image(source='./icons/dm.png')
        self.value_dm = Label(text='0.25')
        self.image_de = Image(source='./icons/de.png')
        self.value_de = Label(text='0.75')

        self.slider_dm = Slider(min=0.0,
                                max=1.0,
                                value=0.25,
                                step=0.25,
                                orientation='vertical',
                                value_track=True,
                                value_track_color=[1, 0, 0, 1],
                                size_hint_y=None,
                                height='160dp')
        self.slider_dm.bind(value=self.update_dm)
        self.slider_de = Slider(min=0.0,
                                max=1.0,
                                value=0.75,
                                step=0.25,
                                orientation='vertical',
                                value_track=True,
                                value_track_color=[1, 0, 0, 1],
                                size_hint_y=None,
                                height='160dp')
        self.slider_de.bind(value=self.update_de)

        self.label_dm = Label(text=text_dict['t24'])
        self.label_de = Label(text=text_dict['t20'])
        self.label_png = Label(text=text_dict['t27'])
        self.label_gvr = Label(text=text_dict['t31'])

        self.spinner_dm = Spinner(text=text_dict['t54'],
                                  values=(text_dict['t25'], text_dict['t26']))
        self.spinner_de = Spinner(text=text_dict['t54'],
                                  values=(text_dict['t21'], text_dict['t22'],
                                          text_dict['t23']))
        self.spinner_png = Spinner(text=text_dict['t54'],
                                   values=(text_dict['t28'], text_dict['t29'],
                                           text_dict['t30']))
        self.spinner_gvr = Spinner(text=text_dict['t54'],
                                   values=(text_dict['t32'], text_dict['t33']))

        Settings_content = BoxLayout(orientation='horizontal')

        slider_dm_content = GridLayout(cols=1)
        slider_dm_content.add_widget(self.image_dm)
        slider_dm_content.add_widget(self.value_dm)
        slider_dm_content.add_widget(self.slider_dm)

        slider_de_content = GridLayout(cols=1)
        slider_de_content.add_widget(self.image_de)
        slider_de_content.add_widget(self.value_de)
        slider_de_content.add_widget(self.slider_de)

        subSettings_content = GridLayout(cols=2, size_hint_x=None, width=350)
        subSettings_content.add_widget(self.label_dm)
        subSettings_content.add_widget(self.spinner_dm)
        subSettings_content.add_widget(self.label_de)
        subSettings_content.add_widget(self.spinner_de)
        subSettings_content.add_widget(self.label_png)
        subSettings_content.add_widget(self.spinner_png)
        subSettings_content.add_widget(self.label_gvr)
        subSettings_content.add_widget(self.spinner_gvr)

        Settings_content.add_widget(subSettings_content)
        Settings_content.add_widget(slider_dm_content)
        Settings_content.add_widget(slider_de_content)
        Settings_content.add_widget(self.btn_sim_start)

        self.popup_sim = Popup(title='',
                               size_hint=(None, None),
                               size=(600, 280),
                               content=Settings_content,
                               auto_dismiss=True,
                               separator_height=0)
        self.popup_sim.open()

    def update_dm(self, instance, value):
        if value == 0.0:
            self.value_dm.text = str(0.1)
        else:
            self.value_dm.text = str(value)

    def update_de(self, instance, value):
        self.value_de.text = str(value)

    def show_popup_cam(self, *args):
        self.cam = Camera(resolution=(640, 480))
        content = BoxLayout(orientation='vertical')
        btn_capture = IconButton(source='./icons/shot.png',
                                 text='',
                                 size_hint_y=None,
                                 height='48dp')
        btn_capture.bind(on_release=self.camera)

        content.add_widget(self.cam)
        content.add_widget(btn_capture)

        self.popup = Popup(title='',
                           size_hint=(None, None),
                           size=('540dp', '480dp'),
                           content=content,
                           auto_dismiss=True,
                           separator_height=0)
        self.popup.open()

    def clean(self, *args):
        self.ax.clear()
        self.ax.axis('off')
        self.ax.imshow(self.img)
        self.canvas.draw()
        self.subSettings_Page.remove_widget(self.btn_pause)
        self.subSettings_Page.remove_widget(self.btn_compare)
        self.subSettings_Page.remove_widget(self.btn_sim_save)
        self.subSettings_Page.remove_widget(self.btn_stop)
        self.subSettings_Page.remove_widget(self.btn_halo)
        self.subSettings_Page.remove_widget(self.btn_cluster)
        self.subSettings_Page.remove_widget(self.slider_comdist)
        self.Box_sim.remove_widget(self.canvas0)

    def camera(self, *args):
        self.cam.play = not self.cam.play
        self.img_filename = self.input_name.text
        self.img_filenamedir = ''.join(e for e in self.img_filename
                                       if e.isalnum())

        try:
            os.stat(CWD + "/tmp")
        except:
            os.mkdir(CWD + "/tmp")
        try:
            os.stat(self.savedir + "/" + self.img_filenamedir)
        except:
            os.mkdir(self.savedir + "/" + self.img_filenamedir)

        self.cam.export_to_png(CWD + "/tmp/" + self.img_filenamedir +
                               "_image.jpg")
        self.btn_cam.source = CWD + "/tmp/" + self.img_filenamedir + "_image.jpg"
        self.popup.dismiss()

    def sim_start(self, *args):
        self.ax.clear()
        self.ax.axis('off')
        self.canvas.draw()
        self.ax0.clear()
        self.ax0.axis('off')
        self.canvas0.draw()

        self.sim_nonStand()
        self.sim_stand()
        self.subSettings_Page.add_widget(self.btn_pause)
        self.subSettings_Page.add_widget(self.btn_compare)
        self.subSettings_Page.add_widget(self.btn_stop)
        self.subSettings_Page.add_widget(self.btn_sim_save)
        self.popup_sim.dismiss()

    def sim_stop(self, *args):
        self.subSettings_Page.remove_widget(self.btn_pause)
        self.subSettings_Page.remove_widget(self.btn_compare)
        self.subSettings_Page.remove_widget(self.btn_stop)
        self.subSettings_Page.remove_widget(self.btn_sim_save)

        self.ax.clear()
        self.ax.axis('off')
        self.canvas.draw()
        self.ax0.clear()
        self.ax0.axis('off')
        self.canvas0.draw()

    def sim_stand(self):
        Simu_Dir = "BBF_Lambda_0.25-0.75" + "/Dens-Maps/"

        cosmo = wCDM(70.3, 0.25, 0.75, w0=-1.0)
        filenames = sorted(glob.glob(self.simdir + "/" + Simu_Dir + '*.npy'))
        lga = np.linspace(np.log(0.05), np.log(1.0), 300)
        a = np.exp(lga)
        z = 1. / a - 1.0
        lktime = cosmo.lookback_time(z).value

        def animate(filename):
            image = np.load(filename)
            indx = filenames.index(
                filename
            )  #; image=ndimage.gaussian_filter(image, sigma= sigmaval, truncate=truncateval, mode='wrap')
            im.set_data(image +
                        1)  #; im.set_clim(image.min()+1.,image.max()+1.)
            self.time0.set_text('%s %s' %
                                (round(lktime[indx], 4), text_dict['t49']))
            return im

        dens_map = np.load(
            filenames[0]
        )  #;  dens_map=ndimage.gaussian_filter(dens_map, sigma= sigmaval, truncate=truncateval, mode='wrap') #; dens_map0 = load(filenames[-1]); #print dens_map0.min()+1, dens_map0.max()+1.
        im = self.ax0.imshow(dens_map + 1,
                             cmap=cm.magma,
                             norm=colors.LogNorm(vmin=1.,
                                                 vmax=1800.,
                                                 clip=True),
                             interpolation="bicubic")  #, clim = (1, 1800.+1.))

        self.time0 = self.ax0.text(0.1,
                                   0.05,
                                   text_dict['t43'] +
                                   ' %s Gyr' % round(lktime[0], 4),
                                   horizontalalignment='left',
                                   verticalalignment='top',
                                   color='white',
                                   transform=self.ax0.transAxes,
                                   fontsize=10)

        arr_hand = mpimg.imread(CWD + "/tmp/" + self.img_filenamedir +
                                "_image.jpg")
        imagebox = OffsetImage(arr_hand, zoom=.1)
        xy = (0.1, 0.15)  # coordinates to position this image

        ab = AnnotationBbox(imagebox,
                            xy,
                            xybox=(0.1, 0.15),
                            xycoords='axes fraction',
                            boxcoords='axes fraction',
                            pad=0.1)
        self.ax0.add_artist(ab)

        arr_hand1 = mpimg.imread("./icons/simcode.png")
        imagebox1 = OffsetImage(arr_hand1, zoom=.1)
        xy = (0.9, 0.9)  # coordinates to position this image
        ab1 = AnnotationBbox(imagebox1,
                             xy,
                             xybox=(0.9, 0.9),
                             xycoords='axes fraction',
                             boxcoords='axes fraction',
                             pad=0.1)
        self.ax0.add_artist(ab1)

        #iMpc = lambda x: x*1024/125  #x in Mpc, return in Pixel *3.085e19
        ob = AnchoredHScaleBar(size=0.1,
                               label="10Mpc",
                               loc=4,
                               frameon=False,
                               pad=0.6,
                               sep=2,
                               color="white",
                               linewidth=0.8)
        self.ax0.add_artist(ob)

        sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % (
            text_dict['t42'], self.input_name.text, text_dict['t53'],
            text_dict['t50'], text_dict['t20'], text_dict['t21'],
            text_dict['t24'], text_dict['t25'], text_dict['t27'],
            text_dict['t28'], text_dict['t31'], text_dict['t32'])
        print sim_details_text
        self.ax0.text(0.1,
                      0.83,
                      sim_details_text,
                      color='white',
                      bbox=dict(facecolor='none',
                                edgecolor='white',
                                boxstyle='round,pad=1',
                                alpha=0.5),
                      transform=self.ax0.transAxes,
                      alpha=0.5)

        self.ani0 = animation.FuncAnimation(self.fig0,
                                            animate,
                                            filenames,
                                            repeat=False,
                                            interval=25,
                                            blit=False)
        self.ax0.axis('off')
        self.ax0.get_xaxis().set_visible(False)
        self.ax0.get_yaxis().set_visible(False)
        self.canvas0.draw()

    def sim_nonStand(self):
        Simu_Dir = self.model_select() + "/Dens-Maps/"

        cosmo = wCDM(70.3, self.slider_dm.value, self.slider_de.value, w0=-1.0)
        filenames = sorted(glob.glob(self.simdir + "/" + Simu_Dir + '*.npy'))
        lga = np.linspace(np.log(0.05), np.log(1.0), 300)
        a = np.exp(lga)
        z = 1. / a - 1.0
        lktime = cosmo.lookback_time(z).value

        def animate(filename):
            image = np.load(filename)
            indx = filenames.index(
                filename
            )  #; image=ndimage.gaussian_filter(image, sigma= sigmaval, truncate=truncateval, mode='wrap')
            im.set_data(image +
                        1)  #; im.set_clim(image.min()+1.,image.max()+1.)
            self.time.set_text('%s %s' %
                               (round(lktime[indx], 4), text_dict['t49']))
            return im

        dens_map = np.load(
            filenames[0]
        )  #;  dens_map=ndimage.gaussian_filter(dens_map, sigma= sigmaval, truncate=truncateval, mode='wrap') #; dens_map0 = load(filenames[-1]); #print dens_map0.min()+1, dens_map0.max()+1.
        im = self.ax.imshow(dens_map + 1,
                            cmap=cm.magma,
                            norm=colors.LogNorm(vmin=1., vmax=1800.,
                                                clip=True),
                            interpolation="bicubic")  #, clim = (1, 1800.+1.))

        self.time = self.ax.text(0.1,
                                 0.05,
                                 text_dict['t43'] +
                                 ' %s Gyr' % round(lktime[0], 4),
                                 horizontalalignment='left',
                                 verticalalignment='top',
                                 color='white',
                                 transform=self.ax.transAxes,
                                 fontsize=10)

        arr_hand = mpimg.imread(CWD + "/tmp/" + self.img_filenamedir +
                                "_image.jpg")
        imagebox = OffsetImage(arr_hand, zoom=.1)
        xy = (0.1, 0.15)  # coordinates to position this image

        ab = AnnotationBbox(imagebox,
                            xy,
                            xybox=(0.1, 0.15),
                            xycoords='axes fraction',
                            boxcoords='axes fraction',
                            pad=0.1)
        self.ax.add_artist(ab)

        arr_hand1 = mpimg.imread("./icons/simcode.png")
        imagebox1 = OffsetImage(arr_hand1, zoom=.1)
        xy = (0.9, 0.9)  # coordinates to position this image
        ab1 = AnnotationBbox(imagebox1,
                             xy,
                             xybox=(0.9, 0.9),
                             xycoords='axes fraction',
                             boxcoords='axes fraction',
                             pad=0.1)
        self.ax.add_artist(ab1)

        #iMpc = lambda x: x*1024/125  #x in Mpc, return in Pixel *3.085e19
        ob = AnchoredHScaleBar(size=0.1,
                               label="10Mpc",
                               loc=4,
                               frameon=False,
                               pad=0.6,
                               sep=2,
                               color="white",
                               linewidth=0.8)
        self.ax.add_artist(ob)

        sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % (
            text_dict['t42'], self.input_name.text, text_dict['t53'],
            self.SC_Type, text_dict['t20'], self.spinner_de.text,
            text_dict['t24'], self.spinner_dm.text, text_dict['t27'],
            self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text)
        print sim_details_text
        self.ax.text(0.1,
                     0.83,
                     sim_details_text,
                     color='white',
                     bbox=dict(facecolor='none',
                               edgecolor='white',
                               boxstyle='round,pad=1',
                               alpha=0.5),
                     transform=self.ax.transAxes,
                     alpha=0.5)

        self.ani = animation.FuncAnimation(self.fig,
                                           animate,
                                           filenames,
                                           repeat=False,
                                           interval=25,
                                           blit=False)

        self.ax.axis('off')
        self.ax.get_xaxis().set_visible(False)
        self.ax.get_yaxis().set_visible(False)
        self.canvas.draw()

    def pause(self, *args):
        if self.anim_running:
            self.btn_pause.source = './icons/play.png'
            self.ani.event_source.stop()
            self.ani0.event_source.stop()
            self.anim_running = False
        else:
            self.btn_pause.source = './icons/pause.png'
            self.ani.event_source.start()
            self.ani0.event_source.start()
            self.anim_running = True

    def save_movie(self, *args):
        print 'Saving movie ....'
        self.label_status.text = 'Saving movie ....'
        simulate = multiprocessing.Process(None, self.moviesave)
        simulate.start()

    def moviesave(self):
        writer = animation.writers['ffmpeg'](
            fps=15)  #, bitrate=16000, codec='libx264')
        self.ani.save(self.savedir + "/" + self.img_filenamedir + "/" +
                      self.img_filenamedir + "_movie.mp4",
                      writer=writer,
                      dpi=dpi)  #, savefig_kwargs={'dpi' : 200}

        video_file = self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_movie.mp4"
        muxvideo_file = self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_mux_movie.mp4"

        audio_file = "ChillingMusic.wav"
        cmd = 'ffmpeg -i ' + video_file + ' -i ' + audio_file + ' -shortest ' + muxvideo_file
        subprocess.call(cmd, shell=True)
        print('Saving and Muxing Done')
        self.label_status.text = 'Saving and Muxing Done!!'
        self.muxvideo = self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_mux_movie.mp4"
        os.remove(video_file)

    def MapLensedImage(self, *args):
        self.ax.clear()
        self.ax.axis('off')
        fileimage = CWD + "/tmp/" + self.img_filenamedir + "_image.jpg"

        Simu_Dir = self.model_select() + "/Lens-Maps/"
        filelens = self.simdir + "/" + Simu_Dir + self.model_name + 'kappaBApp_2.fits'

        image, xsize, ysize = readimage(fileimage)
        image_arr = np.array(image)

        alpha1, alpha2 = buildlens(filelens)
        cosmo = wCDM(70.3, self.slider_dm.value, self.slider_de.value, w0=-1.0)
        self.maplensedimage = deflect(image_arr, alpha1, alpha2, xsize, ysize,
                                      self.slider_comdist.value, cosmo, "LSS")
        self.ax.imshow(self.maplensedimage)

        arr_hand1 = mpimg.imread("./icons/simcode.png")
        imagebox1 = OffsetImage(arr_hand1, zoom=.1)
        xy = [950.0, 85.0]
        ab1 = AnnotationBbox(imagebox1,
                             xy,
                             xybox=(0., 0.),
                             xycoords='data',
                             boxcoords="offset points",
                             pad=0.1)
        self.ax.add_artist(ab1)

        sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % (
            text_dict['t42'], self.input_name.text, text_dict['t53'],
            self.SC_Type, text_dict['t20'], self.spinner_de.text,
            text_dict['t24'], self.spinner_dm.text, text_dict['t27'],
            self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text)
        print sim_details_text
        self.ax.text(0.1,
                     0.83,
                     sim_details_text,
                     color='white',
                     bbox=dict(facecolor='none',
                               edgecolor='white',
                               boxstyle='round,pad=1',
                               alpha=0.5),
                     transform=self.ax.transAxes,
                     alpha=0.5)

        self.ax.axis('off')
        self.ax.get_xaxis().set_visible(False)
        self.ax.get_yaxis().set_visible(False)
        self.canvas.draw()
        #imsave(self.savedir + "/" + self.img_filename + "_LensedMap_Photo.jpg", self.maplensedimage)
        self.fig.savefig(self.savedir + "/" + self.img_filenamedir + "/" +
                         self.img_filenamedir + "_LensedMap_Photo.png")
        self.LensedMap_Photo = self.img_filename + "_LensedMap_Photo.png"
        self.showlensMap()

    def HaloLensedImage(self, *args):
        self.ax.clear()
        self.ax.axis('off')
        fileimage = CWD + "/tmp/" + self.img_filenamedir + "_image.jpg"

        Simu_Dir = self.model_select() + "/Lens-Maps/"
        filelens = self.simdir + "/" + Simu_Dir + self.model_name + '_Halo.fits'

        image, xsize, ysize = readimage(fileimage)
        image_arr = np.array(image)

        alpha1, alpha2 = buildlens(filelens)
        cosmo = wCDM(70.3, self.slider_dm.value, self.slider_de.value, w0=-1.0)
        self.halolensedimage = deflect(image_arr, alpha1, alpha2, xsize, ysize,
                                       self.slider_comdist.value, cosmo,
                                       "HALO")
        self.ax.imshow(self.halolensedimage)

        arr_hand1 = mpimg.imread("./icons/simcode.png")
        imagebox1 = OffsetImage(arr_hand1, zoom=.1)
        xy = [950.0, 85.0]
        ab1 = AnnotationBbox(imagebox1,
                             xy,
                             xybox=(0., 0.),
                             xycoords='data',
                             boxcoords="offset points",
                             pad=0.1)
        self.ax.add_artist(ab1)

        sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % (
            text_dict['t42'], self.input_name.text, text_dict['t53'],
            self.SC_Type, text_dict['t20'], self.spinner_de.text,
            text_dict['t24'], self.spinner_dm.text, text_dict['t27'],
            self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text)
        print sim_details_text
        self.ax.text(0.1,
                     0.83,
                     sim_details_text,
                     color='white',
                     bbox=dict(facecolor='none',
                               edgecolor='white',
                               boxstyle='round,pad=1',
                               alpha=0.5),
                     transform=self.ax.transAxes,
                     alpha=0.5)

        self.ax.axis('off')
        self.ax.get_xaxis().set_visible(False)
        self.ax.get_yaxis().set_visible(False)
        self.canvas.draw()
        #imsave(self.savedir + "/" + self.img_filename + "_LensedHalo_Photo.jpg", self.halolensedimage)
        self.fig.savefig(self.savedir + "/" + self.img_filenamedir + "/" +
                         self.img_filenamedir + "_LensedHalo_Photo.png")
        self.LensedHalo_Photo = self.img_filename + "_LensedHalo_Photo.png"
        self.showlenscluster()

    def showlensMap(self):
        self.ax0.clear()
        self.ax0.axis('off')
        Simu_Dir = self.model_select() + "/Lens-Maps/"
        filename = self.simdir + "/" + Simu_Dir + self.model_name + 'kappaBApp_2.fits'
        self.Lens_map = fits.getdata(filename, ext=0)
        LenImg = self.ax0.imshow(
            self.Lens_map + 1,
            cmap=matplotlib.cm.magma,
            norm=matplotlib.colors.LogNorm(),
            interpolation="bicubic")  #vmin=1., vmax=1800., clip = True

        arr_hand1 = mpimg.imread("./icons/simcode.png")
        imagebox1 = OffsetImage(arr_hand1, zoom=.1)
        xy = [950.0, 85.0]
        ab1 = AnnotationBbox(imagebox1,
                             xy,
                             xybox=(0., 0.),
                             xycoords='data',
                             boxcoords="offset points",
                             pad=0.1)
        self.ax0.add_artist(ab1)

        sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % (
            text_dict['t42'], self.input_name.text, text_dict['t53'],
            self.SC_Type, text_dict['t20'], self.spinner_de.text,
            text_dict['t24'], self.spinner_dm.text, text_dict['t27'],
            self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text)
        print sim_details_text
        self.ax0.text(0.1,
                      0.83,
                      sim_details_text,
                      color='white',
                      bbox=dict(facecolor='none',
                                edgecolor='white',
                                boxstyle='round,pad=1',
                                alpha=0.5),
                      transform=self.ax0.transAxes,
                      alpha=0.5)

        self.ax0.axis('off')
        self.ax0.get_xaxis().set_visible(False)
        self.ax0.get_yaxis().set_visible(False)
        self.canvas0.draw()
        #imsave(self.savedir + "/" + self.img_filename + "_LensedMap.jpg", log(self.Lens_map + 1), cmap=matplotlib.cm.magma)
        self.fig0.savefig(self.savedir + "/" + self.img_filenamedir + "/" +
                          self.img_filenamedir + "_LensedMap.png")
        self.LensedMap = self.img_filename + "_LensedMap.png"

    def showlenscluster(self):
        self.ax0.clear()
        self.ax0.axis('off')
        Simu_Dir = self.model_select() + "/Lens-Maps/"
        filename = self.simdir + "/" + Simu_Dir + self.model_name + '_Halo.fits'
        self.Halo_map = fits.getdata(filename, ext=0)
        HaloImg = self.ax0.imshow(
            self.Halo_map + 1,
            cmap=matplotlib.cm.magma,
            norm=matplotlib.colors.LogNorm(),
            interpolation="bicubic")  #vmin=1., vmax=1800., clip = True

        arr_hand1 = mpimg.imread("./icons/simcode.png")
        imagebox1 = OffsetImage(arr_hand1, zoom=.1)
        xy = [950.0, 85.0]
        ab1 = AnnotationBbox(imagebox1,
                             xy,
                             xybox=(0., 0.),
                             xycoords='data',
                             boxcoords="offset points",
                             pad=0.1)
        self.ax0.add_artist(ab1)

        sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % (
            text_dict['t42'], self.input_name.text, text_dict['t53'],
            self.SC_Type, text_dict['t20'], self.spinner_de.text,
            text_dict['t24'], self.spinner_dm.text, text_dict['t27'],
            self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text)
        print sim_details_text
        self.ax0.text(0.1,
                      0.83,
                      sim_details_text,
                      color='white',
                      bbox=dict(facecolor='none',
                                edgecolor='white',
                                boxstyle='round,pad=1',
                                alpha=0.5),
                      transform=self.ax0.transAxes,
                      alpha=0.5)

        self.ax0.axis('off')
        self.ax0.get_xaxis().set_visible(False)
        self.ax0.get_yaxis().set_visible(False)
        self.canvas0.draw()
        #imsave(self.savedir + "/" + self.img_filename + "_LensedHalo.jpg", log(self.Halo_map + 1), cmap=matplotlib.cm.magma)
        self.fig0.savefig(self.savedir + "/" + self.img_filenamedir + "/" +
                          self.img_filenamedir + "_LensedHalo.png")
        self.LensedHalo = self.img_filename + "_LensedHalo.png"

    def model_select(self):
        SimDict = {
            text_dict['t21']: 'Lambda_',
            text_dict['t22']: 'Quint_',
            text_dict['t23']: 'Phantom_',
            text_dict['t25']: 'Lambda_',
            text_dict['t26']: 'wDM_0.1-',
            text_dict['t28']: 'Lambda_',
            text_dict['t29']: 'LocalPNG_1000-',
            text_dict['t30']: 'LocalPNG_-1000-',
            text_dict['t32']: 'Lambda_',
            text_dict['t33']: 'MGfR_1.2-'
        }

        if self.spinner_de.text != text_dict['t21']:
            run_type = SimDict[self.spinner_de.text]
        elif self.spinner_dm.text != text_dict['t25']:
            run_type = SimDict[self.spinner_dm.text]
        elif self.spinner_png.text != text_dict['t28']:
            run_type = SimDict[self.spinner_png.text]
        elif self.spinner_gvr.text != text_dict['t32']:
            run_type = SimDict[self.spinner_gvr.text]
        else:
            run_type = SimDict[self.spinner_de.text]

        if self.slider_dm.value == 0.0:
            Omega_m = 0.1
        else:
            Omega_m = self.slider_dm.value

        Omega_k = 1. - (Omega_m + self.slider_de.value)

        if Omega_k == 0:
            self.SC_Type = text_dict['t50']
        elif Omega_k > 0:
            self.SC_Type = text_dict['t52']
        else:
            self.SC_Type = text_dict['t51']

        model = "BBF_" + run_type + str(Omega_m) + "-" + str(
            self.slider_de.value)
        self.model_name = run_type + str(Omega_m) + "-" + str(
            self.slider_de.value)
        print model

        return model

    def send_movie(self, *args):
        print 'Sending ....'
        self.label_status.text = 'Sending ....'
        Thread(target=self.moviesend).start()

    def moviesend(self):
        #files=sorted(glob.glob(self.img_filename + '/*'))
        files = os.listdir(self.savedir + "/" + self.img_filenamedir)
        From = '*****@*****.**'
        PWD = 'unibo2018'
        emailling(self.input_name.text, From, self.input_email.text, PWD,
                  self.savedir + "/" + self.img_filenamedir, files)
        self.label_status.text = 'Mail Sent !!'
コード例 #11
0
class MainApp(App):  #main class
    def build(self):  #overriding build method

        self.camera_obj = Camera(resolution=(1024, 1024), allow_stretch=True)
        self.plGen = Playlist.playlistGen()
        return GUI  #returns user interface

    def change_screen(self, screen_name):  #changes screen in app
        screen_manager = self.root.ids['screen_manager']  #gets widget you want
        screen_manager.current = screen_name  #current screen on app

    def take_pic(self, *args):
        self.camera_obj.export_to_png("./selfie.png")
        im1 = ImageConv.open(
            r'C:\Users\Jackson Meyer\PycharmProjects\pythonProject\selfie.png')
        im2 = im1.convert('RGB')
        im2.save(
            r'C:\Users\Jackson Meyer\PycharmProjects\pythonProject\selfie1.jpg'
        )
        self.get_mood()

    def get_mood(self, *args):
        img = plt.imread("selfie1.jpg")
        detector = FER(mtcnn=True)
        valence = self.get_valence(detector, img)
        energy = self.get_energy(detector, img)
        print(detector.detect_emotions(img))
        print(valence, energy)
        self.create_playlist(valence, energy)

    def get_valence(self, detector, img):
        x = detector.detect_emotions(img)
        dict = x[0]
        happy = dict["emotions"]["happy"] * 100
        angry = dict["emotions"]["angry"] * 100
        disgust = dict["emotions"]["disgust"] * 100
        fear = dict["emotions"]["fear"] * 100
        sad = dict["emotions"]["sad"] * 100
        surprise = dict["emotions"]["surprise"] * 100
        neutral = dict["emotions"]["neutral"] * 100

        valence = ((happy * 1) + (angry * .1) + (disgust * .2) + (fear * .3) +
                   (sad * 0) + (surprise * .7) + (neutral * .5))
        valence = valence / 100
        return valence

    def get_energy(self, detector, img):
        x = detector.detect_emotions(img)
        dict = x[0]
        happy = dict["emotions"]["happy"] * 100
        angry = dict["emotions"]["angry"] * 100
        disgust = dict["emotions"]["disgust"] * 100
        fear = dict["emotions"]["fear"] * 100
        sad = dict["emotions"]["sad"] * 100
        surprise = dict["emotions"]["surprise"] * 100
        neutral = dict["emotions"]["neutral"] * 100

        energy = ((happy * .9) + (angry * 1) + (disgust * .2) + (fear * .25) +
                  (sad * .1) + (surprise * .75) + (neutral * .5))
        energy = energy / 100
        return energy

    def create_playlist(self, valence, energy):
        tracks = self.plGen.gen_recs([valence, energy])
        pl = self.plGen.gen_playlist(tracks)
        print(self.plGen.str_playlist(pl))
        self.plGen.genre_list()

        # to save a playlist to user's spotify account
        self.plGen.save_playlist(tracks)

    def login(self):
        self.plGen.force_login()

    def disconnect(self):
        webbrowser.open("https://www.spotify.com/us/account/apps/")

    def github_about(self):
        webbrowser.open(
            "https://github.com/manleydrake/capstone-project-team-15-gme")
コード例 #12
0
ファイル: Proect_3.0.py プロジェクト: ivio05/Filter
class CamApp(App):
    def build(self):
        main_layout = FloatLayout(size=(300, 300))

        self.camera = Camera(resolution=(640, 480),
                             play=True,
                             pos_hint={
                                 'x': 0,
                                 'y': .25
                             },
                             size_hint=(1, .65))
        main_layout.add_widget(self.camera)

        self.label = Label(text='0р',
                           font_size=20,
                           pos_hint={
                               'x': .45,
                               'y': .9
                           },
                           size_hint=(.1, .1),
                           color=[1, 1, 1, 1])
        main_layout.add_widget(self.label)

        self.slider = Slider(min=45,
                             max=60,
                             value=46,
                             pos_hint={
                                 'x': 0,
                                 'y': .2
                             },
                             size_hint=(1, .05))
        main_layout.add_widget(self.slider)
        self.slider_value = self.slider.value

        photo_button = Button(text='Photo',
                              background_color=[0, 1, 1],
                              font_size=20,
                              pos_hint={
                                  'x': .15,
                                  'y': 0
                              },
                              size_hint=(.7, .2))
        photo_button.bind(on_press=self.photo)
        main_layout.add_widget(photo_button)

        return main_layout

    def photo(self, instance):
        self.camera.export_to_png("new.png")

        frame = cv2.imread("new.png")

        self.slider_value = round(self.slider.value)

        buf1 = cv2.flip(frame, 1)
        buf1 = cv2.flip(buf1, 0)
        self.fc = buf1.copy()

        self.circles = coindetect(buf1, 25, self.slider_value)

        summa = 0
        cnt = 0

        min_ten = 0
        min_ne_ten = 0

        spisok_radius_10 = []
        spisok_radius_ne10 = []

        kernel = np.array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1],
                           [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])
        kernel = kernel / sum(kernel)

        res = cv2.filter2D(self.fc, -1, kernel)

        ten = self.circles.copy()
        ne_ten = self.circles.copy()

        if len(self.circles) != 0:
            for i in self.circles[0, :]:
                kef = 1.05
                sr, sc = round(i[1] - kef * i[2]), round(i[0] - kef * i[2])

                er, ec = round(i[1] + kef * i[2]), round(i[0] + kef * i[2])

                imgm = res[sr:er, sc:ec]
                circle_ten = coindetect(imgm, 20, 40)
                if len(circle_ten) > 0:
                    ne_ten = np.delete(ne_ten, cnt - min_ne_ten, axis=1)
                    spisok_radius_10.append(i[2])
                    min_ne_ten += 1
                    summa += 10
                else:
                    ten = np.delete(ten, cnt - min_ten, axis=1)
                    min_ten += 1
                    spisok_radius_ne10.append(i[2])
                cnt += 1

            print('ten:' + str(ten))
            print()
            print('neten:' + str(ne_ten))
            print()

            if len(spisok_radius_10) > 0:
                avg = statistics.mean(spisok_radius_10)
            else:
                avg = min(spisok_radius_ne10) / 0.93

            for i in ne_ten[0, :]:
                if i[2] > avg * 1.07:
                    summa += 5
                elif i[2] < avg * 0.93:
                    summa += 1
                else:
                    summa += 2

        self.label.text = (str(summa) + "р")

        print("summa = {0}".format(summa))
        cv2.imshow('orange', res)
コード例 #13
0
ファイル: main.py プロジェクト: iot-linti/wenuapp
class Login(MDTabbedPanel):
    """Clase de inicio de sesion/coneccion al servidor de influx mediante wenuapi"""
    usr = ObjectProperty(None)
    password = ObjectProperty(None)
    server_ip = ObjectProperty(None)
    cam = None

    def conectar(self, user, password, server):
        """Conecta al servidor"""
        config = App.get_running_app().config
        try:
            config.set('WENU', 'USER', user)
            config.set('WENU', 'PASS', password)
            config.set('WENU', 'SERVER', server)
            config.write()
            #~ server = config.get('WENU', 'SERVER')

            session = wenuclient.get_session(
                '/'.join((server, 'login')),
                user,
                password,
            )
            self.parent.parent.client = wenuclient.Client(server, session)
        except requests.exceptions.RequestException as e:
            print e
            print("Error al efectuar la conexion")
            self.error_dialog(
                "Error al conectar. Verifique el usuario y contraseña.")
        else:
            token = session.auth[0]
            a = open('token.txt', 'w')
            a.write(token)
            a.write('\n' + self.server_ip.text)
            a.close()
            self.parent.parent.current = 'progressbar'
            #~ self.parent.parent.iniciar("bottomsheet","piso_1", self.client, self)
            #~ self.parent.parent.current = 'main'
            self.parent.remove_widget(self)

    def read_qr(self):
        """Abre la camara para leer un codigo de QR"""
        self.content = Widget()
        if platform == 'android':
            self.detector = ZbarQrcodeDetector()
            self.detector.bind(symbols=self.connect_qr)
            self.content.add_widget(self.detector)
            #~ self.dialog = MDDialog(title="Enfoque el codigo QR",content=self.content, size_hint=(.8, None),height=dp(500),auto_dismiss=False)
            #~ self.dialog.add_action_button("Cerrar", action= lambda x: self.close_dialog())
            #~ self.dialog.open()
            self.detector.start()
        else:
            if self.cam == None:
                self.cam = Camera(resolution=(640, 480),
                                  size=(400, 400),
                                  play=True)
                #~ self.add_widget(self.cam)
            else:
                self.cam.play = True
            self.content.size_hint = None, None
            self.content.height = dp(400)
            self.content.add_widget(self.cam)
            self.check_qr = Clock.schedule_interval(self.detect_qr, 1)
        self.dialog = MDDialog(title="Enfoque el codigo QR",
                               content=self.content,
                               size_hint=(.8, None),
                               height=dp(500),
                               auto_dismiss=False)
        self.dialog.add_action_button("Cerrar",
                                      action=lambda x: self.close_dialog())
        self.dialog.open()

    def close_dialog(self):
        """Cierra el dialogo de mensajes de error."""
        self.dialog.dismiss()
        if platform == 'android':
            self.detector.stop()
            self.content.remove_widget(self.detector)

    def connect_qr(self, *args):  #, token):
        """Se loguea con el token leido por el qr"""
        if platform == 'android':
            self.detector.stop()
            try:
                token = self.detector.symbols[0][1]
            except IndexError:
                print self.detector.symbols
                token = []
            print token
        else:
            token = args[0]
        self.dialog.dismiss()
        try:
            session = wenuclient.get_session_by_qr(token)
            self.parent.parent.client = wenuclient.Client(
                self.server_ip.text, session)
        except requests.exceptions.RequestException as e:
            print("Error al efectuar la conexion")
            self.error_dialog("Token incorrecto")
        else:
            self.parent.parent.current = 'progressbar'
            a = open('token.txt', 'w')
            a.write(token)
            a.write(self.server_ip.text)
            a.close()
            #~ self.parent.parent.iniciar("bottomsheet","piso_1", self.client, self)
            #~ self.parent.parent.current = 'main'
            self.parent.remove_widget(self)

    def detect_qr(self, *largs):
        """Detecta el qr, en caso de estar en una pc/notebook."""
        self.cam.export_to_png("qrtests.png")
        file_path = 'qrtests.png'
        with open(file_path, 'rb') as image_file:
            image = ImagePil.open(image_file)
            image.load()
        codes = zbarlight.scan_codes('qrcode', image)
        print('QR codes: %s' % codes)
        if codes != None:
            self.dialog.dismiss()
            self.check_qr.cancel()
            self.content.remove_widget(self.cam)
            self.remove_widget(self.content)
            self.cam.play = False
            self.connect_qr(codes[0])

    def error_dialog(self, txt):
        """Muestra un dialogo de error en caso de no poder conectarse."""
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text=txt,
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="Error",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)
        self.dialog.add_action_button("Cerrar",
                                      action=lambda x: self.dialog.dismiss())
        self.dialog.open()
コード例 #14
0
class CamApp(App):
    def build(self):
        layout = RelativeLayout(size=(500, 500))
        self.cam = Camera(play=True, resolution=(1500, 1500))
        self.button = Button(text='Detect a face!',
                             size_hint=(.5, .07),
                             pos=(450, 100))
        self.button.bind(on_press=self.on_press_button)
        self.button_sketch = Button(text='Create a sketch!',
                                    size_hint=(.5, .07),
                                    pos=(450, 10))
        self.button_paint = Button(text='Create a painting',
                                   size_hint=(.5, 0.07),
                                   pos=(450, 190))
        self.button_sketch.bind(on_press=self.on_press_sketch_button)
        self.button_paint.bind(on_press=self.on_press_paint_button)
        layout.add_widget(self.cam)
        layout.add_widget(self.button)
        layout.add_widget(self.button_sketch)
        layout.add_widget(self.button_paint)
        return layout

    def on_press_button(self, instance):
        #       try:
        self.imagePath = os.path.join('Selfies', 'Selfie.png')
        self.cam.export_to_png(self.imagePath)
        haarCascade = cv2.CascadeClassifier(
            "haarcascade_frontalface_default.xml")
        # Read the image
        image = cv2.imread(self.imagePath)

        # Detect faces in the image
        faces = haarCascade.detectMultiScale(cv2.cvtColor(
            image, cv2.COLOR_BGR2GRAY),
                                             scaleFactor=1.1,
                                             minNeighbors=5,
                                             minSize=(30, 30),
                                             flags=cv2.CASCADE_SCALE_IMAGE)
        # Draw a rectangle around the faces
        for (x, y, w, h) in faces:
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

        cv2.imwrite(os.path.join('Selfies', 'Selfie_detected.jpg'), image)

        return 0

    def on_press_sketch_button(self, instance):
        self.imagePath = os.path.join('Sketch', 'Selfie_sketch.png')
        self.cam.export_to_png(self.imagePath)
        image = cv2.imread(self.imagePath)
        img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        img_gray_inv = 255 - img_gray
        img_blur = cv2.GaussianBlur(img_gray_inv,
                                    ksize=(21, 21),
                                    sigmaX=0,
                                    sigmaY=0)
        img_blend = cv2.divide(img_gray, 255 - img_blur, scale=256)
        cv2.imwrite(os.path.join('Sketch', 'transformed.png'), img_blend)

        return 0

    def on_press_paint_button(self, instance):
        self.imagePath = os.path.join('Paint', 'Selfie.png')
        self.cam.export_to_png(self.imagePath)
        img = cv2.imread(self.imagePath)
        res = cv2.stylization(img, sigma_s=30, sigma_r=0.3)
        cv2.imwrite(os.path.join('Paint', 'painting.png'), res)

        return 0