Ejemplo n.º 1
0
    def __init__(self, ganpreffinder):
        """
        :param ganpreffinder: GANPrefFinder class instance
        """
        self.optimize_Theta = False

        self.GANpf = ganpreffinder

        WIDGET_CONTINIOUS_UPDATE = self.GANpf.USING_CUDA
        WIDGET_WIDTH = 300

        self.strength = 0
        self.w = self.GANpf.get_init_W()
        init_img = self.GANpf.get_init_img()

        self.X, self.Xi = self.GANpf.get_next_query()

        self.widget_image = widgets.Image(format='png',
                                          width=WIDGET_WIDTH,
                                          value=self.to_bytes(init_img))

        self.widget_pref_image = widgets.Image(format='png',
                                               width=WIDGET_WIDTH,
                                               value=self.to_bytes(init_img))

        self.widget_image_init = widgets.Image(format='png',
                                               width=WIDGET_WIDTH,
                                               value=self.to_bytes(init_img))

        self.widget_strength_slider = widgets.IntSlider(
            min=self.GANpf.left_bound,
            max=self.GANpf.right_bound,
            value=self.strength,
            continuous_update=WIDGET_CONTINIOUS_UPDATE,
            description='strength:')

        self.widget_strength_text = widgets.IntText(
            description="strength:",
            continuous_update=WIDGET_CONTINIOUS_UPDATE)

        self.widget_button_incs = widgets.Button(
            description="slider +10 (both sides)",
            buttin_style="info",
            layout=widgets.Layout(width="150px"))

        self.widget_button_decs = widgets.Button(
            description="slider -10 (both sides)",
            buttin_style="info",
            layout=widgets.Layout(width="150px"))

        self.widget_button_nq = widgets.Button(
            description="next query",
            buttin_style="info",
            layout=widgets.Layout(width="300px"))

        self.widget_chb_adaptive_init = widgets.Checkbox(
            value=self.GANpf.ADAPTIVE_INITIALIZATION,
            description='adaptive initialization',
            disabled=False,
            indent=False)
Ejemplo n.º 2
0
 def __init__(self, output, presenter, **kwargs):
     self.output = output
     self.presenter = presenter
     super().__init__(**kwargs)
     self.heatmap_image = widgets.Image(format='png')
     self.heatmap_image_fix = widgets.Image(format='png')
     self.mark = bqplot.Image(scales=self.scales, image=self.heatmap_image)
     self.figure.marks = self.figure.marks + [self.mark]
Ejemplo n.º 3
0
def contentsPage(out, grid):
    grid = close_FrontPage(out, grid)

    with open('./image/leftup.png', 'rb') as f1:
        leftup = f1.read()
        grid[1:6, :4] = widgets.Image(value=leftup)
    f1.close()

    with open('./image/rightdown.png', 'rb') as f2:
        rightdown = f2.read()
        grid[15:, 25:29] = widgets.Image(value=rightdown)
    f2.close()

    with open('./image/contents.png', 'rb') as f3:
        content = f3.read()
        grid[9:14, 7:12] = widgets.Image(value=content)
    f3.close()

    knowledge_button = widgets.Button(description='知识梳理',
                                      style={'button_color': '#004080'},
                                      button_style='info',
                                      layout=widgets.Layout(height='1cm'))
    process_button = widgets.Button(description='过程演示',
                                    style={'button_color': '#004080'},
                                    button_style='info',
                                    layout=widgets.Layout(height='1cm'))
    test_button = widgets.Button(description='巩固测试',
                                 style={'button_color': '#004080'},
                                 button_style='info',
                                 layout=widgets.Layout(height='1cm'))
    temp = widgets.Label(layout=widgets.Layout(height='1cm'))
    temp1 = widgets.Label(layout=widgets.Layout(height='1cm'))
    contents_ui = widgets.VBox(
        [knowledge_button, temp, process_button, temp1, test_button])
    grid[6:15, 16:21] = contents_ui
    '''
    设置按钮事件:“知识梳理”、“过程演示”、“巩固测试”
    '''
    def act_knowledgeButton(b):
        knowledgePage(out, grid)

    knowledge_button.on_click(act_knowledgeButton)

    def act_processButton(b):
        processPage(out, grid)

    process_button.on_click(act_processButton)

    def act_testButton(b):
        testPage(out, grid)

    test_button.on_click(act_testButton)

    return
def firstPage(out, grid):
    grid = close_FrontPage(out, grid)

    with open('./leftup.png', 'rb') as f1:
        leftup = f1.read()
        grid[1:5, :4] = widgets.Image(value=leftup)
    f1.close()

    with open('./rightdown.png', 'rb') as f2:
        rightdown = f2.read()
        grid[15:, 25:29] = widgets.Image(value=rightdown)
    f2.close()

    with open('./xiaohui.png', 'rb') as f3:
        content = f3.read()
        grid[4:13, 9:24] = widgets.Image(value=content)
    f3.close()

    file_upload = widgets.FileUpload(accept='.xlsm',
                                     multiple=False,
                                     layout=widgets.Layout(height='0.8cm',
                                                           width='3cm'),
                                     description='选择文件')
    enter_button = widgets.Button(description='确定',
                                  style={'button_color': '#004080'},
                                  button_style='info',
                                  disabled=True,
                                  layout=widgets.Layout(height='0.8cm',
                                                        width='3cm'))
    grid[15:17, 10:24] = widgets.HBox([
        file_upload,
        widgets.Label(layout=widgets.Layout(height='1cm', width='1cm')),
        enter_button
    ],
                                      layout=widgets.Layout(height='auto',
                                                            width='auto'))

    #监测选择文件组件的变化
    def file_upload_metadata_change(change):
        if change['new'] != []:  #已选择文件
            enter_button.disabled = False

    file_upload.observe(file_upload_metadata_change, names='metadata')
    '''
    设置按钮事件:
    '''

    def act_enterButton(b):
        mainPage(out, grid, file_upload.metadata[0]['name'])

    enter_button.on_click(act_enterButton)

    return
 def __init__(self, module, width, height):
     self.module = module
     self.count = 0
     self.hook = None
     super(ModuleVisualizer2D, self).__init__()
     self.module_input_widget = ipywidgets.Image(width=width, height=height)
     self.module_output_widget = ipywidgets.Image(width=width,
                                                  height=height)
     self.children = [
         ipywidgets.HBox([self.module_input_widget]),
         ipywidgets.HBox([self.module_output_widget])
     ]
Ejemplo n.º 6
0
def loginPage(out, grid):
    with open('./image/leftup.png', 'rb') as f1:
        leftup = f1.read()
        grid[1:6, :4] = widgets.Image(value=leftup)
    f1.close()

    with open('./image/rightdown.png', 'rb') as f2:
        rightdown = f2.read()
        grid[15:, 25:29] = widgets.Image(value=rightdown)
    f2.close()

    stu_number = widgets.Text(description='StudentID',
                              value='20200000',
                              disabled=True,
                              layout=widgets.Layout(width='6.5cm'))
    user_password = widgets.Text(description='Password',
                                 value='123456',
                                 disabled=True,
                                 layout=widgets.Layout(width='6.5cm'))
    login_button = widgets.Button(description='start',
                                  icon='info',
                                  style={'button_color': '#004080'},
                                  button_style='info',
                                  layout=widgets.Layout(width='3cm'))
    temp1 = widgets.Label(layout=widgets.Layout(height='0.7cm'))
    temp2 = widgets.Label(layout=widgets.Layout(height='0.5cm'))
    temp3 = widgets.Label(layout=widgets.Layout(width='2.5cm'))
    login_ui = widgets.VBox([
        temp1, stu_number, user_password, temp2,
        widgets.HBox([temp3, login_button])
    ])
    children = [login_ui]
    tab = widgets.Tab(layout=widgets.Layout(width='8.5cm', height='5.5cm'))
    tab.children = children
    tab.set_title(0, 'Login')

    grid[6:11, 10:17] = tab

    #设置按钮”start“事件
    def start_button(b):
        temp1.value = ''
        n = stu_number.value
        p = user_password.value
        if login.checkUser(n, p):
            contentsPage(out, grid)
        else:
            temp1.value = '用户名/密码不正确!'

    login_button.on_click(start_button)

    return
Ejemplo n.º 7
0
    def __init__(self, cameras, stereo, sep_thread=True, render_depth=True,
                 render_preview=False):
        super().__init__(cameras)
        self.stereo = stereo

        self.widgets = []
        self.widgets.append(ipywidgets.Image(width=720))
        self.widgets.append(ipywidgets.Image(width=720))
        self.widget_fps = ipywidgets.Label()

        self.render_depth = render_depth
        self.render_preview = render_preview

        self._sep_thread = sep_thread
Ejemplo n.º 8
0
def slide_borderline():
    global file_name
    imageLocation = 'photo/zumi.png'

    if (file_name != ''):
        imageLocation = 'photo/' + file_name + ".png"

    wImg1E = widgets.Image(
        layout=Layout(border="solid"),
        width=300,
        height=400  # 이미지 크기
    )

    wImg2E = widgets.Image(
        layout=Layout(border="solid"),
        width=300,
        height=400  # 이미지 크기
    )

    wSlidE = widgets.IntSlider(
        value=10,
        min=0,
        max=1500,
        step=10,
        description='variable:',
        continuous_update=False,
        orientation='vertical',
    )

    def on_edge_change(change):
        contour(change['new'])

    def contour(range):

        image = cv2.imread(imageLocation)  # 이미지 읽기

        gray_img = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  # 흑백이미지로 변환
        originalImg = cv2.imencode(".png", image)[1].tostring()
        wImg1E.value = originalImg

        canny_img = cv2.Canny(gray_img, 0, range)  # Canny edge 알고리즘
        canny_img = cv2.imencode(".png", canny_img)[1].tostring()
        wImg2E.value = canny_img

    contour(10)

    wSlidE.observe(on_edge_change, names='value')

    BOX_NEW = widgets.Box([wImg1E, wImg2E, wSlidE])
    display(BOX_NEW)
Ejemplo n.º 9
0
def build_UI():
    import ipywidgets as widgets
    import matplotlib.pyplot as plt
    img = widgets.Image(format='png', width=282, height=282)
    w = widgets.IntSlider(description='Confidence')
    b1 = widgets.Button(description='1')
    b7 = widgets.Button(description='7')
    hbox = widgets.HBox([b1, b7])
    vbox = widgets.VBox([img, w, hbox])
    acc = None  #widgets.Image(format='png', width=282, height=352)
    corr = widgets.Image(format='png', width=282, height=352)
    ui = widgets.HBox([vbox, corr])
    display(ui)

    return img, acc, corr, w, b1, b7
Ejemplo n.º 10
0
        def color_map(self):
            temp_path = self.p["temp_path"]
            cmap = self.p["task"]["options"]["Colormap"]
            img = os.path.join(temp_path, "legend.png")
            (v_min, v_max) = cmap[1]
            type = cmap[2]
            if type == "linear":
                norm = mpl.colors.Normalize(vmin=v_min, vmax=v_max)
            else:
                norm = mpl.colors.LogNorm(vmin=v_min, vmax=v_max)
            fig, ax = plt.subplots(figsize=(5, 0.2))
            fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap[0]),
                         cax=ax, orientation="horizontal")
            plt.savefig(img, bbox_inches="tight", pad_inches=0.02)
            plt.close()

            # build legend widget
            legend = widgets.Image(
                value=open(img, "rb").read(),
                format="png",
                layout=widgets.Layout(height="25px", width="250px")
            )
            os.remove(img)

            return legend
Ejemplo n.º 11
0
def image_filter(path, category, columns=4, height=200, width=200):
    def on_click(button):
        for r in rows:
            if type(r) is widgets.HBox:
                for c in r.children:
                    checkbox = c.children[1]
                    if checkbox.value:
                        print(checkbox.description_tooltip)
                        os.remove(checkbox.description_tooltip)

    imagefiles = [f for f in path.glob(category + '/*')]
    rows = []
    cols = []
    for i, imgfile in enumerate(tqdm(imagefiles)):
        row = i // columns
        col = i % columns
        img = open(imgfile, 'rb').read()
        image = widgets.Image(value=img, width=width, height=height)
        button = widgets.Checkbox(description='Delete',
                                  description_tooltip=str(imgfile))
        box = widgets.VBox([image, button])
        cols.append(box)
        if len(cols) == columns:
            rows.append(widgets.HBox(cols))
            cols = []
    if len(cols) > 0:
        rows.append(widgets.HBox(cols))
    button = widgets.Button(description='Delete')
    button.on_click(on_click)
    rows.append(button)
    return widgets.VBox(rows)
Ejemplo n.º 12
0
    def __init__(self, label='light-1'):
        self.labeltext = label
        self.label = ipw.Label('{0} state: {1}'.format(self.labeltext,
                                                       self.state))
        img_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "")
        img_light_on_path = os.path.join(img_path, "light_on.png")
        img_light_off_path = os.path.join(img_path, "light_off.png")
        self._img_light_on = open(img_light_on_path, "rb").read()
        self._img_light_off = open(img_light_off_path, "rb").read()
        self._light = ipw.Image(
            value=self._img_light_off,
            format='png',
            width=75,
            height=120,
        )

        super(Light, self).__init__()

        #self.layout.display = 'flex'
        #self.layout.align_items = 'center'
        #self.layout.flex_flow = 'column'
        #self.layout.border = 'none'
        #self.width = '100%'
        self.children = [self._light]  #, self.label]
        _lights[label] = self

        self.observe(self._togglestate, 'state')
Ejemplo n.º 13
0
    def __init__(self,
                 display,
                 verbose=False,
                 dims=None,
                 canvas_format='jpeg',
                 *args,
                 **kwargs):
        """
        Initialise a ginga display

        canvas_type  file type for displays ('jpeg': fast; 'png' : better, slow)
        dims         (x,y) dimensions of image display widget in screen pixels
        """
        virtualDevice.DisplayImpl.__init__(self, display, verbose=False)
        if dims is None:
            # TODO: get defaults from Jupyter defaults?
            width, height = 1024, 768
        else:
            width, height = dims
        self._imageWidget = ipywidgets.Image(format=canvas_format,
                                             width=width,
                                             height=height)
        logger = get_logger("ginga", log_stderr=True, level=40)
        self._viewer = EnhancedCanvasView(logger=logger)
        self._viewer.set_widget(self._imageWidget)
        bd = self._viewer.get_bindings()
        bd.enable_all(True)
        self._canvas = self._viewer.add_canvas()
        self._canvas.enable_draw(False)
        self._maskTransparency = 0.8
        self._redraw = True
Ejemplo n.º 14
0
def create_widget(result):
    '''Generate image widget from couchbase return'''
    diffImage = decodeImage(result['differenceImage'])
    sciImage = decodeImage(result['scienceImage'])
    templateImage = decodeImage(result['templateImage'])

    #read as fits file from byte array
    outputArray = []
    imageArray = [diffImage, sciImage, templateImage]

    image_layout = w.Layout(object_fit='cover', width="40%")
    for image in imageArray:
        with gzip.open(io.BytesIO(image), 'rb') as f:
            with fits.open(io.BytesIO(f.read())) as hdul:
                output = io.BytesIO()
                #convert to image (RGB)
                data = np.uint8(255 * (hdul[0].data - hdul[0].data.min()) /
                                (hdul[0].data.max() - hdul[0].data.min()))
                im = Image.fromarray(hdul[0].data)
                im = im.convert('RGB')
                im = equalize(im)
                #save as bye array and read into widget
                im.save(output, format='PNG')
        outputArray.append(
            w.Image(value=output.getvalue(), format='png',
                    layout=image_layout))
    return outputArray
Ejemplo n.º 15
0
def selectah(data, labels, m=20, n=20):

    n_classes = labels.max()
    inputs = [
        widgets.Dropdown(options=particle_classes,
                         value=-1,
                         description="Class:") for i in range(n_classes + 1)
    ]

    box_layout = widgets.Layout(display="flex",
                                flex_flow="column",
                                justify_content="center")
    images = []
    for i in range(n_classes + 1):
        inds = np.where(labels == i)[0]
        img = img_to_bytes(sample_particles(data, inds, 20, 20))
        img = widgets.Image(value=img, format="png", width=500, height=500)
        images += [img]

    box = widgets.VBox([
        widgets.HBox([img, widgets.VBox([input], layout=box_layout)])
        for img, input in zip(images, inputs)
    ])

    return box, inputs
Ejemplo n.º 16
0
    def generate_ipyimages(self, images):
        '''
        Create an ipywidgets.Image object for each image.
        
        Args:
            images (list): A list of image bytes objects.
            
        Returns:
            ipyimges (list): A list of ipywidgets.Image objects.
            
        '''

        if isinstance(images, list):
            try:
                ipyimages = []
                for image in images:
                    assert isinstance(image, bytes)
                    ipyimage = widgets.Image(value=image,
                                             format=self.image_format)
                    ipyimages.append(ipyimage)
                return ipyimages
            except AssertionError as e:
                raise ValueError(
                    f'images parameter must contain a list of image bytes objects.'
                ) from e

        else:
            raise ValueError(
                f'images parameter must contain a list of image bytes objects.'
            )
Ejemplo n.º 17
0
    def __init__(self, figure=None, name="jupyter_image"):
        super().__init__(name, on_next=self.on_image)

        self.figure = figure or widgets.Image()
        self.figure.format = "jpeg"
        self.figure.width = 800
        self.figure.height = 600
Ejemplo n.º 18
0
 def _setup(self, cameras):
     logging.info("Starting jupyter notebook stream.")
     for _ in range(len(self.cameras.devices)):
         self.widgets.append(ipywidgets.Image(width=480))
     self.cameras.capture_black_screen()
     IPython.display.display(*self.widgets)
     self._update(cameras)
Ejemplo n.º 19
0
    def display_view(self, tup, status_text):
        try:
            ascImg = tup['image']
            prepImg = tup['prepared_image']
            stage = widgets.Output(layout={'border': '1px solid green'})
            oimg = widgets.Image(value=io.BytesIO(
                base64.b64decode(ascImg)).getvalue(),
                                 width=300,
                                 height=400)
            self.orig.clear_output(wait=True)
            self.prep.clear_output(wait=True)
            self.camera.value = tup['camera']
            self.result.value = "Model's prediction : {:d}".format(
                tup['result_class'])
            self.status.value = status_text
            with self.orig:
                stage.append_display_data(oimg)
            with self.prep:
                imshow(prepImg, cmap=plt.cm.gray_r, interpolation='nearest')
                plt.show()
            radio_buttons = [
                '%d:%9.5f' % (idx, x)
                for idx, x in enumerate(tup['predictions'])
            ] + ['Camera Error', '2nd Opinion', 'Not a Digit', 'Other']
            self.correct_radio.options = radio_buttons
            if self.image_index in self.corrected_images:
                self.correct_radio.value = self.corrected_images[
                    self.image_index]
            else:
                self.correct_radio.value = radio_buttons[tup['result_class']]

        except Exception as e:
            self.status.value = "Key error : {0:}".format(e)
Ejemplo n.º 20
0
def SlideShower(folder, frame_duration=800):
	slides = list([open(os.path.join(folder,s), 'rb').read()
                   for s in natural_sort(os.listdir(folder))])

	x, y = _get_png_info(slides[0])
	img = widgets.Image(value=slides[0], width=x, height=y)

	def on_frame(change):
		n = change['new']
		img.value = slides[n]

	play = widgets.Play(
        value=0,
        min=0,
        max=len(slides),
        step=1,
        interval=frame_duration,
        disabled=False
    )
	slider = widgets.IntSlider(
        value=0,
        min=0,
        max=len(slides)-1,
        step=1
    )
	slider.observe(on_frame, names='value')
	widgets.jslink((play, 'value'), (slider, 'value'))
	box = widgets.VBox([img, widgets.HBox([play, slider])])
	return box
Ejemplo n.º 21
0
    def update_data_and_display(self):
        if not self.hidden:
            # filter the image if need be
            self.filtered_frame.copy_bgr(self.raw_frame.get())
            if self.filter_fn is not None:
                self.filtered_frame.link_bgr(
                    self.filter_fn(self.filtered_frame))

            self.labelled_frame.copy_bgr(self.filtered_frame.get())
            if self.vision_system is not None:
                self.labelled_frame.link_bgr(
                    self.vision_system.update_with_and_label_frame(
                        self.labelled_frame))

            for cb in self.update_frame_cbs:
                cb()

            ipy_img = ipy.Image(value=cv2.imencode(
                '.jpg', self.labelled_frame.get(
                    self.display_colorspace))[1].tostring(),
                                format='jpg')

            if self.bq_img is None:
                self.bq_img = bq.Image(image=ipy_img,
                                       scales=self.image_plot_scales)
            else:
                self.bq_img.image = ipy_img
Ejemplo n.º 22
0
 def __init__(self, image_fnames):
     self.display_w = 400
     self.display_h = 400
     self.fnames = image_fnames
     self.index = 0
     self.data = []
     for fname in self.fnames:
         with open(fname, "rb") as f:
             self.data.append(f.read())
     self.label = ipywidgets.Label(value=self.fnames[self.index])
     self.image = ipywidgets.Image(value=self.data[self.index],
                                   width=self.display_w,
                                   height=self.display_h,
                                   format="png")
     self.check = ipywidgets.Checkbox(value=False,
                                   description='Show absolute file path',
                                   disabled=False,
                                   indent=False)
     self.slider = ipywidgets.IntSlider()
     self.play   = ipywidgets.Play(value=0,
                              min=0,
                              max=len(self.data)-1,
                              step=1,
                              interval=500)
     ipywidgets.jslink((self.play, "min"), (self.slider, "min"))
     ipywidgets.jslink((self.play, "max"), (self.slider, "max"))
     ipywidgets.jslink((self.play, "value"), (self.slider, "value"))
    def __init__(self, config):
        self.config = config
        self._timeout = config['timeout']

        self.color = np.zeros((720, 1280))
        self.depth = np.zeros((720, 1280))

        self._widgets = self.config['widgets']
        self._stream_color = self.config['stream_color']
        self._stream_depth = self.config['stream_depth']

        if self._widgets:
            self.color_widget = ipywidgets.Image(height=310, width=640)
            self.depth_widget = ipywidgets.Image(height=310, width=640)

        self._command_queue = deque()
Ejemplo n.º 24
0
def render_image(image_url=None, output_region=None):
    """Write the image into a output region.

    Args::
        url: image
        output_region: output region

    .. note:: The creation of the output 'stage', if this is not done the image is rendered in the page and
        the output region.

    """

    try:
        response = requests.get(image_url)
        stage = widgets.Output(layout={'border': '1px solid green'})
    except:
        print("Error on request : ", image_url)
    else:
        if response.status_code == 200:
            with output_region:
                stage.append_display_data(widgets.Image(
                    value=response.content,
                    # format='jpg',
                    width=300,
                    height=400,
                ))
            output_region.clear_output(wait=True)
Ejemplo n.º 25
0
    def __init__(self,
                 logo: str = None,
                 button_style: Union[ButtonStyle, str] = None,
                 **kwargs):
        logo = logo if logo is not None else "optimade-text-right-transparent-bg.png"
        logo = self._get_file(str(IMG_DIR.joinpath(logo)))
        logo = ipw.Image(value=logo, format="png", width=375, height=137.5)

        if button_style:
            if isinstance(button_style, str):
                button_style = ButtonStyle[button_style.upper()]
            elif isinstance(button_style, ButtonStyle):
                pass
            else:
                raise TypeError(
                    "button_style should be either a string or a ButtonStyle Enum. "
                    f"You passed type {type(button_style)!r}.")
        else:
            button_style = ButtonStyle.DEFAULT

        header = ipw.HTML(self.HEADER)

        # Hidden input HTML element, storing the log
        self._debug_log = REPORT_HANDLER.get_widget()
        self.report_bug = ipw.HTML(f"""
<button type="button" class="p-Widget jupyter-widgets jupyter-button widget-button mod-{button_style.value}"
title="Create a bug issue on GitHub that includes a log file" style="width:auto;"
onclick="
var log = document.getElementById('{self._debug_log.element_id}');

var link = document.createElement('a');
link.target = '_blank';
link.href = '{SOURCE_URL}issues/new?{urlencode(self.BUG_TEMPLATE, encoding="utf-8")}' + log.getAttribute('value');

document.body.appendChild(link);
link.click();
document.body.removeChild(link);">
<i class="fa fa-bug"></i>Report a bug</button>""")
        self.report_suggestion = ipw.HTML(f"""
<form target="_blank" style="width:auto;height:auto;" action="{SOURCE_URL}issues/new">
<input type="hidden" name="title" value="{self.SUGGESTION_TEMPLATE["title"]}" />
<input type="hidden" name="body" value="{self.SUGGESTION_TEMPLATE["body"]}" />
<button type="submit" class="p-Widget jupyter-widgets jupyter-button widget-button mod-{button_style.value}"
title="Create an enhancement issue on GitHub" style="width:auto;">
<i class="fa fa-star"></i>Suggest a feature/change</button></form>""")
        reports = ipw.HBox(children=(
            ipw.HTML(
                '<p style="font-size:14px;margin-top:0px;margin-bottom:0px">'
                "<b>Help improve the application:</b></p>"),
            self.report_bug,
            self.report_suggestion,
        ), )

        description = ipw.HTML(self.DESCRIPTION)

        super().__init__(
            children=(self._debug_log, logo, header, reports, description),
            layout=ipw.Layout(width="auto"),
            **kwargs,
        )
Ejemplo n.º 26
0
    def _initGamePlot(self, initFrame, initScore):
        bnew = ipywidgets.Button(layout=self.ilay,
                                 style=ipywidgets.ButtonStyle(
                                     font_weight='bold', button_color='green'),
                                 description='New')
        self.stat = ipywidgets.HTML(layout=self.ilay,
                                    value=self.scoreFmt.format(
                                        initScore, self.aggScore))

        controls = [bnew]
        for _, i in sorted(tuple(self.game.actions.items())):
            button = ipywidgets.Button(layout=self.blay,
                                       style=ipywidgets.ButtonStyle(
                                           font_weight='bold',
                                           button_color='yellow'),
                                       icon=self.actionMap[i])
            controls.append(button)
        for c in controls:
            c.on_click(self._onButtonClicked)
        controls.append(self.stat)
        self.ctrlbox = ipywidgets.HBox(controls)

        self.canvas = ipywidgets.Image()
        self.imbuf = io.BytesIO()
        self._plotGame(initFrame)

        ibox = ipywidgets.VBox([self.canvas, self.ctrlbox])
        ibox.layout.align_items = 'center'
        self.gamebox = ipywidgets.HBox([ibox])
Ejemplo n.º 27
0
def import_cs(image_path):
    """Import the image of the cross-section"""
    with open(image_path, 'rb') as fid:
        raw_img = fid.read()

    ipyimg = widgets.Image(value=raw_img, format=image_path[-3:])
    return ipyimg
Ejemplo n.º 28
0
    def thread_refresh_icon(self):
        self.refresh_icon_box.layout = widgets.Layout(width='40px', height='40px')
        
        file = open("../files/img/refresh_00.png", "rb")
        image = file.read()
        img_w = widgets.Image(
            value=image,
            format='png',
            width=35,
            height=35,
        )
        
        self.refresh_icon_box.children = (img_w,)

        i = 0
        f = 0
        while self.started_scan:
            time.sleep(0.1)
            i += 1
            file = open("../files/img/refresh_" + str(i).zfill(2) + ".png", "rb")
            image = file.read()
            img_w .value = image
            if i == 11:
                i = -1
            f += 1
        
        # Ended scan, blank the resfresh image
        file = open("../files/img/tick.png", "rb")
        image = file.read()
        img_w .value = image

        if self.interrupted_scan:
            file = open("../files/img/close.png", "rb")
            image = file.read()
            img_w .value = image
Ejemplo n.º 29
0
    def report(self, results):
        panels = []
        for result in results:
            fig = plt.figure(figsize=(self.base_figure_size,
                                      self.base_figure_size))
            self._report_single_result(result, fig)
            plt.close()

            buf = io.BytesIO()
            fig.savefig(buf, format='png')
            buf.seek(0)

            im = widgets.Image(value=buf.getvalue(), format='png')
            buf.close()
            panels.append(im)

        cbs = [widgets.Checkbox(value=False) for r in results]
        cbs_and_labels = [
            widgets.HBox([cb, widgets.Label(str(r.params))])
            for (cb, r) in zip(cbs, results)
        ]

        button = widgets.Button(description="Compare")

        cb_container = widgets.VBox(cbs_and_labels + [button])
        plots_container = widgets.HBox()

        display(cb_container, plots_container)

        def compare(button):
            res = [p for p, cb in zip(panels, cbs) if cb.value]
            plots_container.children = res

        button.on_click(compare)
Ejemplo n.º 30
0
def transform():
    global file_name
    imageLocation = 'photo/zumi.png'

    if (file_name != ''):
        imageLocation = 'photo/' + file_name + ".png"

    #RotaionRatio = 0.5  #  회전시 잘리는 경우 1을 입력

    RotaionRatio = 1  #  회전시 잘리는 경우 1을 입력

    wImagR = widgets.Image(
        layout=Layout(border="solid"),
        width=300,
        height=400  # 이미지 크기
    )

    wRadioR = widgets.RadioButtons(
        options=['원위치', '왼쪽으로 90도 회전', '오른쪽으로 90도 회전', '좌우 반전', '상하 반전'],
        description='Rotate:',
        disabled=False)

    def on_Rotate_change(change):
        ImageRotate(change['new'])

    def ImageRotate(direction):

        image = cv2.imread(imageLocation)  # 이미지 읽기

        (height, width) = image.shape[:2]
        (center_height, center_width) = (height / 2.0, width / 2.0)

        if (direction == '왼쪽으로 90도 회전'):
            angle = 90
            M = cv2.getRotationMatrix2D((center_width, center_height), angle,
                                        RotaionRatio)
            image = cv2.warpAffine(image, M, (width, height))

        elif (direction == '오른쪽으로 90도 회전'):
            angle = -90
            M = cv2.getRotationMatrix2D((center_width, center_height), angle,
                                        RotaionRatio)
            image = cv2.warpAffine(image, M, (width, height))

        elif (direction == '좌우 반전'):
            image = cv2.flip(image, 1)

        elif (direction == '상하 반전'):
            image = cv2.flip(image, 0)

        originalImg = cv2.imencode(".png", image)[1].tostring()
        wImagR.value = originalImg

    ImageRotate('원위치')

    wRadioR.observe(on_Rotate_change, names='value')

    BOX_NEW = widgets.Box([wImagR, wRadioR])
    display(BOX_NEW)