Exemplo n.º 1
0
def three_seven():
    """
    3.7
    Obtain the unnormalized and the normalized histograms of the following 8-bit,
    MxN image.  Give your histogram either in a table or a graph, labeling clearly
    the value and location of each histogram component in terms of M and N.
    Double-check your answer by making sure that the histogram components add to the
    correct value.
    """
    figure_image = np.array([
        [240, 240, 240, 16, 16, 16, 32, 32, 32, 32, 32, 32, 32],
        [240, 240, 240, 16, 16, 16, 228, 32, 32, 32, 32, 32, 255],
        [240, 240, 240, 16, 16, 16, 228, 228, 32, 32, 32, 255, 255],
        [240, 240, 240, 16, 16, 16, 228, 228, 228, 32, 255, 255, 255],
        [240, 240, 240, 16, 16, 16, 228, 228, 228, 0, 255, 255, 255],
        [240, 240, 240, 16, 16, 16, 228, 228, 0, 0, 0, 255, 255],
        [240, 240, 240, 16, 16, 16, 228, 0, 0, 0, 0, 0, 255],
        [240, 240, 240, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0],
        [127, 127, 127, 191, 191, 191, 0, 0, 0, 0, 0, 0, 0],
        [127, 127, 127, 191, 191, 191, 0, 0, 0, 0, 0, 0, 0],
        [127, 127, 127, 191, 191, 191, 0, 0, 0, 0, 0, 0, 0],
    ])

    rows, columns = figure_image.shape

    ImageDisplay.display_image(figure_image)

    histogram = ImageStatistics.calculate_histogram(figure_image)

    # calculate normalized histogram
    counts = 0
    for value in histogram:
        counts += value

    normalized_histogram = histogram / (rows * columns)

    print(histogram)

    plt.hist(figure_image)
    plt.show()

    plt.plot(histogram, label="unnormalized histogram")
    plt.legend()
    plt.show()

    plt.plot(normalized_histogram, label="normalized histogram")
    plt.legend()
    plt.show()
Exemplo n.º 2
0
def three_five():
    """
    3.5
    Do the following:
    (a) Purpose a method for extracting the bit planes of an image based on
    converting the value of its pixels to binary.
    (b) Find all the bit planes o the following 4-bit image:
            0  1  8  6
            2  2  1  1
            1  15 14 12
            3  6  9  10
    """
    four_bit_image = np.array([[0, 1, 8, 6], [2, 2, 1, 1], [1, 15, 14, 12],
                               [3, 6, 9, 10]])

    ImageDisplay.display_image(four_bit_image)

    bit_planes = ImageAnalysis.calculate_bit_planes(four_bit_image,
                                                    bits_per_pixel=4)

    ImageDisplay.display_bit_planes(bit_planes * 256)
Exemplo n.º 3
0
	def __init__(self, *args, **kwargs):
		super(Display, self).__init__(*args, **kwargs)

		self.image_display       = ImageDisplay(
			orientation='vertical'
		)
		self.toolbar_placeholder = Label(
			text='Toolbar Placeholder',
			size_hint_y=None,
			height=50
		)
		self.add_widget(self.image_display)
		self.add_widget(self.toolbar_placeholder)
Exemplo n.º 4
0
    def __init__(self, passed=None):
        """ImageBrowser([passed=None])

        :param passed: Default=None, filepath that runs the program. Default runs os.getcwd()
        """

        self.open_file = ""
        self.entered = False
        self.file_list = []
        self.rotate_qty = 0

        # ------Program Window-----#

        self.window = tk.Tk()
        self.window.title("Image Viewer")

        self.dimY = self.window.winfo_screenheight()
        self.dimX = self.window.winfo_screenwidth()

        self._resize_program()

        image = tk.PhotoImage(file="toolbar/iv_logo.png")
        self.window.iconphoto(False, image)

        self.window.geometry(f"{self.programX}x{self.programY}+100+0")
        self.window.resizable(width=False, height=False)
        self.window.config(background="gray75")

        self.window.bind("<Left>", lambda x: self._back_image())
        self.window.bind("<Right>", lambda x: self._next_image())
        self.window.bind("<BackSpace>", lambda x: self._chg_dir)

        self.file_bar_frame = tk.Frame(self.window,
                                       height=35,
                                       padx=5,
                                       background="gray30")
        self.file_bar_frame.pack(side="top", fill="x")
        self.file_bar_frame.pack_propagate(0)

        load = Image.open("toolbar/up_arrow.png")
        load = load.resize((20, 20))
        self.up_render = ImageTk.PhotoImage(load)

        self.up_dir = tk.Button(self.file_bar_frame,
                                image=self.up_render,
                                background="gray75",
                                borderwidth=0,
                                command=self._chg_dir)
        self.up_dir.pack(side="left")

        self.file_bar = tk.Entry(self.file_bar_frame,
                                 width=95,
                                 font=("Ariel", 12))
        self.file_bar.pack(side="left")

        self.file_bar.bind("<FocusIn>",
                           lambda x: self.window.unbind("<BackSpace>"))
        self.file_bar.bind(
            "<FocusOut>",
            lambda x: self.window.bind("<BackSpace>", self._chg_dir))

        self.go_button = tk.Button(
            self.file_bar_frame,
            text="Go!",
            font=("Ariel", 10),
            borderwidth=0,
            background="gray75",
            command=lambda: self._go_click(self.file_bar.get()),
            activebackground="gray45")
        self.go_button.pack(side="left")
        self.file_bar.bind("<Return>", lambda x: self.go_button.invoke())

        self.image_container_c = tk.Label(self.file_bar_frame,
                                          background="gray30",
                                          pady=5)
        self.image_container_c.pack(side="left")

        tk.Label(self.image_container_c, width=8,
                 background="gray30").pack(side="left")

        self.image_container = tk.Label(self.image_container_c,
                                        background="gray30",
                                        pady=5)
        self.image_container.pack(side="left")

        load = Image.open("toolbar/trash.png")
        load = load.resize((25, 25))
        trash_render = ImageTk.PhotoImage(load)
        self.file_option_trash = tk.Button(self.image_container,
                                           image=trash_render,
                                           width=25,
                                           height=25,
                                           borderwidth=0,
                                           background="gray75",
                                           activebackground="gray45",
                                           command=self._del_image)
        self.file_option_trash.pack(side="left")

        load = Image.open("toolbar/flip_trans.png")
        load = load.resize((25, 25))
        f_h_render = ImageTk.PhotoImage(load)
        self.flip_horizontal = tk.Button(
            self.image_container,
            image=f_h_render,
            height=25,
            width=25,
            borderwidth=0,
            background="gray75",
            activebackground="gray45",
            command=lambda: self.ID.flip("horizontal"))
        self.flip_horizontal.pack(side="left", anchor="center")

        load = load.rotate(90, Image.NEAREST, expand=1)
        f_v_render = ImageTk.PhotoImage(load)
        self.flip_vertical = tk.Button(
            self.image_container,
            image=f_v_render,
            height=25,
            width=25,
            borderwidth=0,
            background="gray75",
            activebackground="gray45",
            command=lambda: self.ID.flip("vertical"))
        self.flip_vertical.pack(side="left", anchor="center")

        load = Image.open("toolbar/rotate_trans.png")
        load = load.resize((25, 25))
        rotate_render = ImageTk.PhotoImage(load)
        self.file_option_rotate = tk.Button(
            self.image_container,
            image=rotate_render,
            width=25,
            height=25,
            borderwidth=0,
            background="gray75",
            activebackground="gray45",
            command=lambda: self.ID.rotate("ccw"))
        self.file_option_rotate.pack(side="left")

        load = load.transpose(Image.FLIP_LEFT_RIGHT)
        rotate_r_render = ImageTk.PhotoImage(load)
        self.file_option_rotate_r = tk.Button(
            self.image_container,
            image=rotate_r_render,
            width=25,
            height=25,
            borderwidth=0,
            background="gray75",
            activebackground="gray45",
            command=lambda: self.ID.rotate("cw"))
        self.file_option_rotate_r.pack(side="left")

        tk.Label(self.image_container_c, width=8,
                 background="gray30").pack(side="left")

        self.zoom_container = tk.Label(self.image_container_c,
                                       background="gray30")
        self.zoom_container.pack(side="left")

        self.zoom_amount = tk.Entry(self.zoom_container,
                                    width=4,
                                    font=("Ariel", 14))
        self.zoom_amount.pack(side="left")

        self.zoom_amount.bind("<FocusIn>",
                              lambda x: self.window.unbind("<BackSpace>"))
        self.zoom_amount.bind(
            "<FocusOut>",
            lambda x: self.window.bind("<BackSpace>", self._chg_dir))

        load = Image.open("toolbar/zoom_trans.png")
        load = load.resize((25, 25))
        zoom_render = ImageTk.PhotoImage(load)
        self.file_option_zoom = tk.Button(self.zoom_container,
                                          image=zoom_render,
                                          width=25,
                                          height=25,
                                          borderwidth=0,
                                          background="gray75",
                                          activebackground="gray45",
                                          command=self._zoom,
                                          justify=tk.CENTER)
        self.file_option_zoom.pack(side="left")
        self.zoom_amount.bind("<Return>",
                              lambda x: self.file_option_zoom.invoke())

        self.slideshow_container = tk.Label(self.file_bar_frame,
                                            width=25,
                                            background="gray75")
        self.slideshow_container.pack(side="right")

        self.slideshow_play = tk.Button(
            self.slideshow_container,
            text="Start Slideshow!",
            font=("Ariel", 10),
            background="gray75",
            command=lambda: self._slideshow_click(self.open_file),
            activebackground="gray45",
            borderwidth=0)
        self.slideshow_play.pack()

        self.slideshow_stop = tk.Button(
            self.slideshow_container,
            text="Stop Slideshow!",
            font=("Ariel", 10),
            background="gray75",
            command=lambda: self._slideshow_click(self.open_file),
            activebackground="gray45",
            borderwidth=0)

        self.top_frame = tk.Frame(self.window, background="gray75")
        self.top_frame.pack(side="top")

        self.folder_frame = tk.Frame(self.top_frame,
                                     width=300,
                                     height=self.height + 4,
                                     borderwidth=2,
                                     relief="flat",
                                     background="gray30")
        self.folder_frame.pack(side="left", anchor="nw")
        self.folder_frame.pack_propagate(0)

        self.folder_text = tk.Text(self.folder_frame,
                                   background="gray75",
                                   relief="flat",
                                   wrap="none")
        self.folder_text.pack(expand=True, fill="both")

        self.folder_text.tag_config("blank",
                                    background="gray30",
                                    foreground="#A4541D",
                                    justify=tk.LEFT,
                                    font=("Ariel", 12, "bold"),
                                    spacing1="4",
                                    spacing2="4",
                                    spacing3="4",
                                    lmargin1="5")

        self.folder_text.tag_config("spacer",
                                    font=("Ariel", 1),
                                    background="gray30")

        self.folder_buttons = ButtonManager(self.folder_text)

        self.folder_scroll = tk.Scrollbar(self.folder_text)
        self.folder_scroll.pack(side="right", fill="y")

        self.folder_text.config(yscrollcommand=self.folder_scroll.set)
        self.folder_scroll.config(command=self.folder_text.yview)

        self.image_frame = tk.Frame(self.top_frame,
                                    height=self.height + 4,
                                    width=self.width + 4,
                                    borderwidth=2,
                                    relief="flat",
                                    background="gray10")
        self.image_frame.pack(side="left", expand=True, anchor=tk.CENTER)
        self.image_frame.pack_propagate(0)

        self.image_frame.bind("<Enter>", lambda x: self.file_options_enter())
        self.image_frame.bind("<Leave>", lambda x: self.file_options_exit())

        load = Image.open("toolbar/default_img.png")
        render = ImageTk.PhotoImage(load)
        """
        self.image_label = tk.Label(self.image_frame, image=render, height=946, width=1146, anchor="center",
                                    background="gray10", borderwidth=2, relief="flat")
        self.image_label.pack(fill="both", expand=True)
        """
        self.image_canvas = tk.Canvas(self.image_frame,
                                      height=self.height,
                                      width=self.width,
                                      background="gray10",
                                      borderwidth=2,
                                      relief="flat")
        self.image_canvas.pack(anchor=tk.CENTER, fill="both")
        self.image_canvas.create_image(self.width / 2,
                                       self.height / 2,
                                       image=render,
                                       anchor="center")

        self.ID = ImageDisplay(self.image_canvas, self.width, self.height)

        self.text_var = tk.StringVar()
        self.text_var.set("")
        self.file_count = tk.StringVar()
        self.file_count.set("")
        self.folder_count = tk.StringVar()
        self.folder_count.set("")
        self.file_name = tk.Frame(self.window, background="gray60")
        self.file_name.pack(side="bottom", fill="x")
        self.file_size = tk.StringVar()
        self.file_size.set("  0.00 MB")

        self.file_count_disp = tk.Label(self.file_name,
                                        textvariable=self.file_count,
                                        background="gray60",
                                        padx=4,
                                        justify=tk.LEFT,
                                        anchor="w",
                                        borderwidth=2,
                                        relief="sunken")
        self.file_count_disp.pack(side="left")

        self.folder_count_disp = tk.Label(self.file_name,
                                          textvariable=self.folder_count,
                                          background="gray60",
                                          padx=4,
                                          justify=tk.LEFT,
                                          anchor="w",
                                          borderwidth=2,
                                          relief="sunken")
        self.folder_count_disp.pack(side="left")

        self.file_link = tk.Label(self.file_name,
                                  textvariable=self.text_var,
                                  background="gray60",
                                  padx=4,
                                  justify=tk.LEFT,
                                  anchor="w",
                                  borderwidth=2,
                                  relief="sunken")
        self.file_link.pack(side="left", expand=True, fill="both")

        self.file_size_disp = tk.Label(self.file_name,
                                       textvariable=self.file_size,
                                       background="gray60",
                                       padx=4,
                                       justify=tk.LEFT,
                                       anchor="w",
                                       borderwidth=2,
                                       relief="sunken")
        self.file_size_disp.pack(side="right")

        if passed is None:
            self.link = os.getcwd()
            self.crawler = FileCrawler()
        else:
            self.link = passed
            self.crawler = FileCrawler(self.link)

        self.open_folder(self.link)
        self.file_bar.delete(0, tk.END)
        self.file_bar.insert(tk.INSERT, self.link)

        self.window.mainloop()
Exemplo n.º 5
0
class ImageBrowser:
    def __init__(self, passed=None):
        """ImageBrowser([passed=None])

        :param passed: Default=None, filepath that runs the program. Default runs os.getcwd()
        """

        self.open_file = ""
        self.entered = False
        self.file_list = []
        self.rotate_qty = 0

        # ------Program Window-----#

        self.window = tk.Tk()
        self.window.title("Image Viewer")

        self.dimY = self.window.winfo_screenheight()
        self.dimX = self.window.winfo_screenwidth()

        self._resize_program()

        image = tk.PhotoImage(file="toolbar/iv_logo.png")
        self.window.iconphoto(False, image)

        self.window.geometry(f"{self.programX}x{self.programY}+100+0")
        self.window.resizable(width=False, height=False)
        self.window.config(background="gray75")

        self.window.bind("<Left>", lambda x: self._back_image())
        self.window.bind("<Right>", lambda x: self._next_image())
        self.window.bind("<BackSpace>", lambda x: self._chg_dir)

        self.file_bar_frame = tk.Frame(self.window,
                                       height=35,
                                       padx=5,
                                       background="gray30")
        self.file_bar_frame.pack(side="top", fill="x")
        self.file_bar_frame.pack_propagate(0)

        load = Image.open("toolbar/up_arrow.png")
        load = load.resize((20, 20))
        self.up_render = ImageTk.PhotoImage(load)

        self.up_dir = tk.Button(self.file_bar_frame,
                                image=self.up_render,
                                background="gray75",
                                borderwidth=0,
                                command=self._chg_dir)
        self.up_dir.pack(side="left")

        self.file_bar = tk.Entry(self.file_bar_frame,
                                 width=95,
                                 font=("Ariel", 12))
        self.file_bar.pack(side="left")

        self.file_bar.bind("<FocusIn>",
                           lambda x: self.window.unbind("<BackSpace>"))
        self.file_bar.bind(
            "<FocusOut>",
            lambda x: self.window.bind("<BackSpace>", self._chg_dir))

        self.go_button = tk.Button(
            self.file_bar_frame,
            text="Go!",
            font=("Ariel", 10),
            borderwidth=0,
            background="gray75",
            command=lambda: self._go_click(self.file_bar.get()),
            activebackground="gray45")
        self.go_button.pack(side="left")
        self.file_bar.bind("<Return>", lambda x: self.go_button.invoke())

        self.image_container_c = tk.Label(self.file_bar_frame,
                                          background="gray30",
                                          pady=5)
        self.image_container_c.pack(side="left")

        tk.Label(self.image_container_c, width=8,
                 background="gray30").pack(side="left")

        self.image_container = tk.Label(self.image_container_c,
                                        background="gray30",
                                        pady=5)
        self.image_container.pack(side="left")

        load = Image.open("toolbar/trash.png")
        load = load.resize((25, 25))
        trash_render = ImageTk.PhotoImage(load)
        self.file_option_trash = tk.Button(self.image_container,
                                           image=trash_render,
                                           width=25,
                                           height=25,
                                           borderwidth=0,
                                           background="gray75",
                                           activebackground="gray45",
                                           command=self._del_image)
        self.file_option_trash.pack(side="left")

        load = Image.open("toolbar/flip_trans.png")
        load = load.resize((25, 25))
        f_h_render = ImageTk.PhotoImage(load)
        self.flip_horizontal = tk.Button(
            self.image_container,
            image=f_h_render,
            height=25,
            width=25,
            borderwidth=0,
            background="gray75",
            activebackground="gray45",
            command=lambda: self.ID.flip("horizontal"))
        self.flip_horizontal.pack(side="left", anchor="center")

        load = load.rotate(90, Image.NEAREST, expand=1)
        f_v_render = ImageTk.PhotoImage(load)
        self.flip_vertical = tk.Button(
            self.image_container,
            image=f_v_render,
            height=25,
            width=25,
            borderwidth=0,
            background="gray75",
            activebackground="gray45",
            command=lambda: self.ID.flip("vertical"))
        self.flip_vertical.pack(side="left", anchor="center")

        load = Image.open("toolbar/rotate_trans.png")
        load = load.resize((25, 25))
        rotate_render = ImageTk.PhotoImage(load)
        self.file_option_rotate = tk.Button(
            self.image_container,
            image=rotate_render,
            width=25,
            height=25,
            borderwidth=0,
            background="gray75",
            activebackground="gray45",
            command=lambda: self.ID.rotate("ccw"))
        self.file_option_rotate.pack(side="left")

        load = load.transpose(Image.FLIP_LEFT_RIGHT)
        rotate_r_render = ImageTk.PhotoImage(load)
        self.file_option_rotate_r = tk.Button(
            self.image_container,
            image=rotate_r_render,
            width=25,
            height=25,
            borderwidth=0,
            background="gray75",
            activebackground="gray45",
            command=lambda: self.ID.rotate("cw"))
        self.file_option_rotate_r.pack(side="left")

        tk.Label(self.image_container_c, width=8,
                 background="gray30").pack(side="left")

        self.zoom_container = tk.Label(self.image_container_c,
                                       background="gray30")
        self.zoom_container.pack(side="left")

        self.zoom_amount = tk.Entry(self.zoom_container,
                                    width=4,
                                    font=("Ariel", 14))
        self.zoom_amount.pack(side="left")

        self.zoom_amount.bind("<FocusIn>",
                              lambda x: self.window.unbind("<BackSpace>"))
        self.zoom_amount.bind(
            "<FocusOut>",
            lambda x: self.window.bind("<BackSpace>", self._chg_dir))

        load = Image.open("toolbar/zoom_trans.png")
        load = load.resize((25, 25))
        zoom_render = ImageTk.PhotoImage(load)
        self.file_option_zoom = tk.Button(self.zoom_container,
                                          image=zoom_render,
                                          width=25,
                                          height=25,
                                          borderwidth=0,
                                          background="gray75",
                                          activebackground="gray45",
                                          command=self._zoom,
                                          justify=tk.CENTER)
        self.file_option_zoom.pack(side="left")
        self.zoom_amount.bind("<Return>",
                              lambda x: self.file_option_zoom.invoke())

        self.slideshow_container = tk.Label(self.file_bar_frame,
                                            width=25,
                                            background="gray75")
        self.slideshow_container.pack(side="right")

        self.slideshow_play = tk.Button(
            self.slideshow_container,
            text="Start Slideshow!",
            font=("Ariel", 10),
            background="gray75",
            command=lambda: self._slideshow_click(self.open_file),
            activebackground="gray45",
            borderwidth=0)
        self.slideshow_play.pack()

        self.slideshow_stop = tk.Button(
            self.slideshow_container,
            text="Stop Slideshow!",
            font=("Ariel", 10),
            background="gray75",
            command=lambda: self._slideshow_click(self.open_file),
            activebackground="gray45",
            borderwidth=0)

        self.top_frame = tk.Frame(self.window, background="gray75")
        self.top_frame.pack(side="top")

        self.folder_frame = tk.Frame(self.top_frame,
                                     width=300,
                                     height=self.height + 4,
                                     borderwidth=2,
                                     relief="flat",
                                     background="gray30")
        self.folder_frame.pack(side="left", anchor="nw")
        self.folder_frame.pack_propagate(0)

        self.folder_text = tk.Text(self.folder_frame,
                                   background="gray75",
                                   relief="flat",
                                   wrap="none")
        self.folder_text.pack(expand=True, fill="both")

        self.folder_text.tag_config("blank",
                                    background="gray30",
                                    foreground="#A4541D",
                                    justify=tk.LEFT,
                                    font=("Ariel", 12, "bold"),
                                    spacing1="4",
                                    spacing2="4",
                                    spacing3="4",
                                    lmargin1="5")

        self.folder_text.tag_config("spacer",
                                    font=("Ariel", 1),
                                    background="gray30")

        self.folder_buttons = ButtonManager(self.folder_text)

        self.folder_scroll = tk.Scrollbar(self.folder_text)
        self.folder_scroll.pack(side="right", fill="y")

        self.folder_text.config(yscrollcommand=self.folder_scroll.set)
        self.folder_scroll.config(command=self.folder_text.yview)

        self.image_frame = tk.Frame(self.top_frame,
                                    height=self.height + 4,
                                    width=self.width + 4,
                                    borderwidth=2,
                                    relief="flat",
                                    background="gray10")
        self.image_frame.pack(side="left", expand=True, anchor=tk.CENTER)
        self.image_frame.pack_propagate(0)

        self.image_frame.bind("<Enter>", lambda x: self.file_options_enter())
        self.image_frame.bind("<Leave>", lambda x: self.file_options_exit())

        load = Image.open("toolbar/default_img.png")
        render = ImageTk.PhotoImage(load)
        """
        self.image_label = tk.Label(self.image_frame, image=render, height=946, width=1146, anchor="center",
                                    background="gray10", borderwidth=2, relief="flat")
        self.image_label.pack(fill="both", expand=True)
        """
        self.image_canvas = tk.Canvas(self.image_frame,
                                      height=self.height,
                                      width=self.width,
                                      background="gray10",
                                      borderwidth=2,
                                      relief="flat")
        self.image_canvas.pack(anchor=tk.CENTER, fill="both")
        self.image_canvas.create_image(self.width / 2,
                                       self.height / 2,
                                       image=render,
                                       anchor="center")

        self.ID = ImageDisplay(self.image_canvas, self.width, self.height)

        self.text_var = tk.StringVar()
        self.text_var.set("")
        self.file_count = tk.StringVar()
        self.file_count.set("")
        self.folder_count = tk.StringVar()
        self.folder_count.set("")
        self.file_name = tk.Frame(self.window, background="gray60")
        self.file_name.pack(side="bottom", fill="x")
        self.file_size = tk.StringVar()
        self.file_size.set("  0.00 MB")

        self.file_count_disp = tk.Label(self.file_name,
                                        textvariable=self.file_count,
                                        background="gray60",
                                        padx=4,
                                        justify=tk.LEFT,
                                        anchor="w",
                                        borderwidth=2,
                                        relief="sunken")
        self.file_count_disp.pack(side="left")

        self.folder_count_disp = tk.Label(self.file_name,
                                          textvariable=self.folder_count,
                                          background="gray60",
                                          padx=4,
                                          justify=tk.LEFT,
                                          anchor="w",
                                          borderwidth=2,
                                          relief="sunken")
        self.folder_count_disp.pack(side="left")

        self.file_link = tk.Label(self.file_name,
                                  textvariable=self.text_var,
                                  background="gray60",
                                  padx=4,
                                  justify=tk.LEFT,
                                  anchor="w",
                                  borderwidth=2,
                                  relief="sunken")
        self.file_link.pack(side="left", expand=True, fill="both")

        self.file_size_disp = tk.Label(self.file_name,
                                       textvariable=self.file_size,
                                       background="gray60",
                                       padx=4,
                                       justify=tk.LEFT,
                                       anchor="w",
                                       borderwidth=2,
                                       relief="sunken")
        self.file_size_disp.pack(side="right")

        if passed is None:
            self.link = os.getcwd()
            self.crawler = FileCrawler()
        else:
            self.link = passed
            self.crawler = FileCrawler(self.link)

        self.open_folder(self.link)
        self.file_bar.delete(0, tk.END)
        self.file_bar.insert(tk.INSERT, self.link)

        self.window.mainloop()

    def file_options_enter(self):
        # self.window.bind("<MouseWheel>", self._scroll)
        # self.window.bind("<Button-4>", self._scroll)
        # self.window.bind("<Button-5>", self._scroll)
        self.entered = True

        load = Image.open("toolbar/file_options.png")
        load = load.resize((120, 50))
        self.options_render = ImageTk.PhotoImage(load)
        self.file_option_bar = tk.Label(self.image_frame,
                                        image=self.options_render,
                                        width=120,
                                        height=50)
        self.file_option_bar.place(x=(self.image_frame.winfo_width() - 120) /
                                   2,
                                   y=850)

        load = Image.open("toolbar/back.png")
        self.back_render = ImageTk.PhotoImage(load)
        self.file_option_back = tk.Button(self.file_option_bar,
                                          image=self.back_render,
                                          width=50,
                                          height=50,
                                          borderwidth=0,
                                          background="white",
                                          command=self._back_image)
        self.file_option_back.place(x=9, y=0)

        load = Image.open("toolbar/next.png")
        self.next_render = ImageTk.PhotoImage(load)
        self.file_option_next = tk.Button(self.file_option_bar,
                                          image=self.next_render,
                                          width=50,
                                          height=50,
                                          borderwidth=0,
                                          background="white",
                                          command=self._next_image)
        self.file_option_next.place(x=59, y=0)

    def _resize_program(self):
        self.width = self.dimX - 774
        self.height = self.dimY - 134 - 25

        self.programX = self.dimX - 470
        self.programY = self.dimY - 72 - 25

    def _zoom(self):
        amount = int(self.zoom_amount.get())
        self.ID.zoom(amount / 100)

    def _scroll(self, event):
        count = 0
        if event.num == 5 or event.delta < 0:
            count += 1
        else:
            count -= 1

        if count > 0:
            self._next_image()
        else:
            self._back_image()

    def _chg_dir(self):
        direct = os.path.split(self.file_bar.get())[0]
        self.file_bar.delete(0, tk.END)
        self.file_bar.insert(tk.INSERT, direct)
        self.go_button.invoke()
        self.open_image()

    def _next_image(self):
        try:
            index = self.file_list.index(self.open_file)
            if index < len(self.file_list) - 1:
                index += 1
                self.open_image(self.file_list[index])
                self.folder_buttons.scroll(self.file_list[index])
        except (AttributeError, ValueError):
            pass

    def _del_image(self):
        try:
            index = self.file_list.index(self.open_file)
            send2trash(self.file_list[index])
            self._next_image()
            self.crawler = FileCrawler(self.link)
            self.open_folder(self.link)
        except (AttributeError, ValueError):
            pass

    def _back_image(self):
        try:
            index = self.file_list.index(self.open_file)
            if index > 0:
                index -= 1
                self.open_image(self.file_list[index])
                self.folder_buttons.scroll(self.file_list[index])
        except (AttributeError, ValueError):
            pass

    def file_options_exit(self):
        self.entered = False
        self.file_option_bar.place_forget()
        # self.window.unbind("<MouseWheel>")
        # self.window.unbind("<Button-4>")
        # self.window.unbind("<Button-5>")

    def _go_click(self, link):
        thread = threading.Thread(target=self._go_click_thread, args=(link, ))
        thread.daemon = True
        thread.start()

    def _go_click_thread(self, link):
        if link.endswith(".jpg") or link.endswith(".png") or link.endswith(".jpeg") or link.endswith(".gif") \
                or link.endswith(".tiff") or link.endswith(".bmp") or link.endswith(".tif"):
            string = os.path.split(link)
            self.open_image(link)
            link = string[0]

        self.folder_text.config(state=tk.NORMAL)
        self.folder_text.delete(1.0, tk.END)
        self.folder_text.insert(tk.END, f"Loading...\n", "blank")
        self.folder_text.config(state=tk.DISABLED)
        self.crawler = FileCrawler(link)
        self.open_folder(link)

    def _slideshow_click(self, link):
        if link == "":
            return
        if len(threading.enumerate()) >= 2:
            self.SLIDESHOW_RUNNING = False
            self.slideshow_play.pack()
            self.slideshow_stop.pack_forget()
        else:
            if len(self.file_list) > 0:
                self.SLIDESHOW_RUNNING = True
                self.slideshow_play.pack_forget()
                self.slideshow_stop.pack()
                cmd_thread = threading.Thread(target=self._slideshow_start,
                                              args=())
                cmd_thread.daemon = True
                cmd_thread.start()

    def _slideshow_start(self):
        # link = link.replace(" ", "%")
        # os.system(f"py slideshow.py {link}")
        for _ in self.file_list:
            time.sleep(2)
            if not self.SLIDESHOW_RUNNING:
                break
            self._next_image()

    def folder_fill(self, link):
        try:
            self.link = link
            self.folder_text.config(state=tk.NORMAL)
            self.folder_text.delete(1.0, tk.END)
            self.folder_text.insert(tk.END,
                                    f"..\\{os.path.split(link)[-1]}\\\n",
                                    "blank")
            folders = self.crawler.pull_folders(link)
            self.folder_count.set(f"{len(folders)} folder(s)")
            for folder in folders:
                dir_path = os.path.join(link, folder)
                self.folder_text.insert(tk.END, "\n", "spacer")
                self.folder_text.insert(
                    tk.END, "> " + folder + "\n",
                    self.folder_buttons.add(self.open_folder, dir_path))
                self.folder_text.insert(tk.END, "\n", "spacer")
            self.folder_text.config(state=tk.DISABLED)
        except (KeyError, TypeError):
            self.folder_count.set(f"0 folder(s)")
            pass

    def open_folder(self, link):
        self.folder_fill(link)
        self.file_bar.delete(0, tk.END)
        self.file_bar.insert(tk.INSERT, link)
        folder = os.path.split(link)[-1]
        self.window.title(f"Image Viewer - {folder}")
        try:
            self.folder_text.config(state=tk.NORMAL)
            self.file_list.clear()
            for file in self.crawler.file_list(link):
                self.file_list.append(file)
                self.folder_text.insert(tk.END, "\n", "spacer")
                self.folder_text.insert(
                    tk.END, "- " + os.path.split(file)[-1] + "\n",
                    self.folder_buttons.addFile(self.open_image, file))
                self.folder_text.insert(tk.END, "\n", "spacer")
            self.file_count.set(f"{len(self.file_list)} file(s)")
        except (TypeError, KeyError):
            self.file_count.set(f"0 file(s)")
            pass
        self.folder_text.config(state=tk.DISABLED)

    def open_image(self, file="toolbar/default_img.png"):
        """open_image(self, [file="toolbar/default_img.png"])
        :param file: the link to the file
        :return: Displays image
        """
        self.open_file = file
        self.ID.open_image(file)
        self.zoom_amount.delete(0, tk.END)
        self.zoom_amount.insert(tk.END, int(self.ID.zoom_percentage()))

        try:
            file_size = os.path.getsize(self.open_file) / 1048576
        except FileNotFoundError:
            return
        self.text_var.set(self.open_file)
        if file_size < 10:
            self.file_size.set("  %.2f MB" % file_size)
        else:
            self.file_size.set("%.2f MB" % file_size)
        if self.entered:
            self.file_option_bar.place_forget()
            self.file_options_enter()
Exemplo n.º 6
0
    def __init__(self, parent=None, infile=None, inimage=None, center_ra=None, center_dec=None, position_angle=None):
        QtGui.QWidget.__init__(self, parent)
        
        #set up the main UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
#        OptimizeTab.__init__(self,self.ui)
        #set up the slitmask
        self.slitmask=SlitMask(center_ra=center_ra, center_dec=center_dec, position_angle=position_angle )
        self.slitlets=self.slitmask.slitlets

        #setup the image interaction
        self.imagedisplay=ImageDisplay(target='pySlitMask:5909')
        self.position_angle=position_angle 
        if inimage:
           self.loadimage(inimage)
        #set up some variables that will be needed later
        self.xmlfile=None
        self.fcfile=None

        #read in the input data if available
        self.infile=infile 
        if infile:
            self.ui.radioButtonInfo_Catalogue.setChecked(True)
            self.setmode2cat()
            self.entercatalog(infile)
            print self.slitmask.center_ra, self.slitmask.center_dec
            if self.slitmask.center_ra is None and self.slitmask.center_dec is None:
                self.slitmask.set_MaskPosition()
                self.displayfootprint()

            #if self.slitmask.center_ra and self.slitmask.center_dec:
                #self.imagedisplay.rssregion(self.slitmask.center_ra, self.slitmask.center_dec)
            
            self.ui.lineEditMain_CenRA.setText(str(self.slitmask.center_ra))
            self.ui.lineEditMain_CenDEC.setText(str(self.slitmask.center_dec))
            self.ui.lineEditMain_PA.setText(str(self.slitmask.position_angle))
            self.ui.lineEditMain_Equinox.setText(str(self.slitmask.equinox))
            
            self.ui.lineEditMain_TargetName.setText(self.slitmask.target_name)
            self.ui.lineEditMain_MaskName.setText(self.slitmask.mask_name)
            self.ui.lineEditInfo_Creator.setText(self.slitmask.creator)
            self.ui.lineEditInfo_Proposer.setText(self.slitmask.proposer)
            self.ui.lineEditInfo_ProposalCode.setText(self.slitmask.proposal_code)
        else:
            self.ui.radioButtonInfo_Catalogue.setChecked(False)
            self.ui.radioButtonInfo_Manual.setChecked(True)
            self.setmode2manual()
            self.ui.toolButtonCat_Load.setEnabled(True)



              #self.displayfootprint()

#        self.opttab = OptimizeTab()
        # setup default values for the optimizer
        self.opt_yspacing = 1.
        self.opt_iter = 10
        self.ui.lineEditOpt_Yspacing.setText(str(self.opt_yspacing))
        self.ui.lineEditOpt_Niter.setText(str(self.opt_iter))

#        self.slitmask.outFoV()
#        print self.slitlets.data['fov_flag']
#        self.updatetabs()
        #Listen to different signals

        #menu items
        QtCore.QObject.connect(self.ui.actionLoad_Catalogue, QtCore.SIGNAL("triggered()"), self.loadcatalog)
        QtCore.QObject.connect(self.ui.actionLoad_Image, QtCore.SIGNAL("triggered()"), self.loadimage)

        #main tabs
        QtCore.QObject.connect(self.ui.lineEditMain_CenRA, QtCore.SIGNAL("editingFinished()"), self.loadCenRA)
        QtCore.QObject.connect(self.ui.lineEditMain_CenDEC, QtCore.SIGNAL("editingFinished()"), self.loadCenDEC)
        QtCore.QObject.connect(self.ui.lineEditMain_PA, QtCore.SIGNAL("editingFinished()"), self.loadpositionangle)
        QtCore.QObject.connect(self.ui.lineEditMain_Equinox, QtCore.SIGNAL("editingFinished()"), self.loadequinox)
        QtCore.QObject.connect(self.ui.lineEditMain_TargetName, QtCore.SIGNAL("editingFinished()"), self.loadtargetname)
        QtCore.QObject.connect(self.ui.lineEditMain_MaskName, QtCore.SIGNAL("editingFinished()"), self.loadmaskname)
        
        #info tabs
        QtCore.QObject.connect(self.ui.lineEditInfo_ProposalCode, QtCore.SIGNAL("editingFinished()"), self.loadproposalcode)
        QtCore.QObject.connect(self.ui.lineEditInfo_Proposer, QtCore.SIGNAL("editingFinished()"), self.loadproposer)
        QtCore.QObject.connect(self.ui.lineEditInfo_Creator, QtCore.SIGNAL("editingFinished()"), self.loadcreator)

#        QtCore.QObject.connect(self.slitmask, SIGNAL('xmlloaded'), self.setcreator)

        QtCore.QObject.connect(self.ui.radioButtonInfo_Catalogue, QtCore.SIGNAL("clicked()"), self.setmode2cat)
        QtCore.QObject.connect(self.ui.radioButtonInfo_Manual, QtCore.SIGNAL("clicked()"), self.setmode2manual)
        QtCore.QObject.connect(self.ui.checkBoxInfo_CentroidOn, QtCore.SIGNAL("clicked()"), self.setmodecentroiding)

        
        
        #catalog tabs
        QtCore.QObject.connect(self.ui.toolButtonCat_Load, QtCore.SIGNAL("clicked(bool)"), self.loadcatalog)
        QtCore.QObject.connect(self.ui.pushButtonCat_AddSlits, QtCore.SIGNAL("clicked(bool)"), self.addslitfromcatalog)
        QtCore.QObject.connect(self.ui.pushButtonCat_Clear, QtCore.SIGNAL("clicked()"), self.clearContents)

        #slit tab
        QtCore.QObject.connect(self.ui.pushButtonSlit_ClearSlits, QtCore.SIGNAL("clicked()"), self.clearslittable)
        QtCore.QObject.connect(self.ui.pushButtonSlit_AddSlitImage, QtCore.SIGNAL("clicked()"), self.addslitletsfromimage)
        QtCore.QObject.connect(self.ui.pushButtonSlit_AddSlitfromCat, QtCore.SIGNAL("clicked()"), self.addslitletsfromcatalogue)
        QtCore.QObject.connect(self.ui.pushButtonSlit_AddSlit, QtCore.SIGNAL("clicked()"), self.addslitmanually)
        QtCore.QObject.connect(self.ui.pushButtonSlit_DeleteSlit, QtCore.SIGNAL("clicked()"), self.deleteslitmanually)
        QtCore.QObject.connect(self.ui.pushButtonSlit_DeleteSlitImage, QtCore.SIGNAL("clicked()"), self.deleteslitfromimage)
        QtCore.QObject.connect(self.ui.tableWidgetSlits, QtCore.SIGNAL("itemSelectionChanged()"), self.setposition)
        QtCore.QObject.connect(self.ui.tableWidgetSlits, QtCore.SIGNAL("cellChanged(int, int)"), self.slitchanged)

        #optimize tab
        QtCore.QObject.connect(self.ui.pushButtonOpt_Optimize, QtCore.SIGNAL("clicked()"), self.optimize)
        QtCore.QObject.connect(self.ui.lineEditOpt_Yspacing, QtCore.SIGNAL("editingFinished()"), self.setoptimizer_yspacing)
        QtCore.QObject.connect(self.ui.lineEditOpt_Niter, QtCore.SIGNAL("editingFinished()"), self.setoptimizer_iter)
        QtCore.QObject.connect(self.ui.checkBoxOpt_IncRefstars, QtCore.SIGNAL("stateChanged(int)"), self.includerefstars)
        QtCore.QObject.connect(self.ui.lineEditOpt_NumRefstars, QtCore.SIGNAL("editingFinished()"), self.setnumrefstars)

        #ref stars
        QtCore.QObject.connect(self.ui.pushButtonRef_ClearRefstars, QtCore.SIGNAL("clicked()"), self.clearrefstartable)
        QtCore.QObject.connect(self.ui.pushButtonRef_AddRefstarImage, QtCore.SIGNAL("clicked()"), self.addslitletsfromimage)
        QtCore.QObject.connect(self.ui.pushButtonRef_AddRefstarsfromCat, QtCore.SIGNAL("clicked()"), self.addrefstarsfromcatalogue)
        QtCore.QObject.connect(self.ui.pushButtonRef_AddRefstar, QtCore.SIGNAL("clicked()"), self.addrefstarmanually)
        QtCore.QObject.connect(self.ui.pushButtonRef_DeleteRefstar, QtCore.SIGNAL("clicked()"), self.deleterefstarmanually)
        QtCore.QObject.connect(self.ui.pushButtonRef_DeleteRefstar_2, QtCore.SIGNAL("clicked()"), self.deleteslitfromimage)
        QtCore.QObject.connect(self.ui.tableWidgetRefstars, QtCore.SIGNAL(" itemSelectionChanged()"), self.setrefposition)
        QtCore.QObject.connect(self.ui.tableWidgetRefstars, QtCore.SIGNAL("cellChanged(int, int)"), self.refchanged)

        # finalize tab
        QtCore.QObject.connect(self.ui.pushButtonFin_Validate, QtCore.SIGNAL("clicked(bool)"),self.validator)
        QtCore.QObject.connect(self.ui.pushButtonFin_WriteXML, QtCore.SIGNAL("clicked(bool)"), self.writexml)
        QtCore.QObject.connect(self.ui.toolButtonFin_WriteRSMT, QtCore.SIGNAL("clicked(bool)"), self.writersmt)
        QtCore.QObject.connect(self.ui.pushButtonFin_CreateFChart_Current, QtCore.SIGNAL("clicked(bool)"), self.writeFC_Current)
        QtCore.QObject.connect(self.ui.pushButtonFin_CreateFChart_DSS, QtCore.SIGNAL("clicked(bool)"), self.writeFC_DSS)

 
        self.ui.tabWidget.setCurrentIndex(0)
Exemplo n.º 7
0
class SlitMaskGui(QtGui.QMainWindow, InfoTab, CatalogTab, OptimizeTab, SlitTab, RefTab, FinalizeTab):
    def __init__(self, parent=None, infile=None, inimage=None, center_ra=None, center_dec=None, position_angle=None):
        QtGui.QWidget.__init__(self, parent)
        
        #set up the main UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
#        OptimizeTab.__init__(self,self.ui)
        #set up the slitmask
        self.slitmask=SlitMask(center_ra=center_ra, center_dec=center_dec, position_angle=position_angle )
        self.slitlets=self.slitmask.slitlets

        #setup the image interaction
        self.imagedisplay=ImageDisplay(target='pySlitMask:5909')
        self.position_angle=position_angle 
        if inimage:
           self.loadimage(inimage)
        #set up some variables that will be needed later
        self.xmlfile=None
        self.fcfile=None

        #read in the input data if available
        self.infile=infile 
        if infile:
            self.ui.radioButtonInfo_Catalogue.setChecked(True)
            self.setmode2cat()
            self.entercatalog(infile)
            print self.slitmask.center_ra, self.slitmask.center_dec
            if self.slitmask.center_ra is None and self.slitmask.center_dec is None:
                self.slitmask.set_MaskPosition()
                self.displayfootprint()

            #if self.slitmask.center_ra and self.slitmask.center_dec:
                #self.imagedisplay.rssregion(self.slitmask.center_ra, self.slitmask.center_dec)
            
            self.ui.lineEditMain_CenRA.setText(str(self.slitmask.center_ra))
            self.ui.lineEditMain_CenDEC.setText(str(self.slitmask.center_dec))
            self.ui.lineEditMain_PA.setText(str(self.slitmask.position_angle))
            self.ui.lineEditMain_Equinox.setText(str(self.slitmask.equinox))
            
            self.ui.lineEditMain_TargetName.setText(self.slitmask.target_name)
            self.ui.lineEditMain_MaskName.setText(self.slitmask.mask_name)
            self.ui.lineEditInfo_Creator.setText(self.slitmask.creator)
            self.ui.lineEditInfo_Proposer.setText(self.slitmask.proposer)
            self.ui.lineEditInfo_ProposalCode.setText(self.slitmask.proposal_code)
        else:
            self.ui.radioButtonInfo_Catalogue.setChecked(False)
            self.ui.radioButtonInfo_Manual.setChecked(True)
            self.setmode2manual()
            self.ui.toolButtonCat_Load.setEnabled(True)



              #self.displayfootprint()

#        self.opttab = OptimizeTab()
        # setup default values for the optimizer
        self.opt_yspacing = 1.
        self.opt_iter = 10
        self.ui.lineEditOpt_Yspacing.setText(str(self.opt_yspacing))
        self.ui.lineEditOpt_Niter.setText(str(self.opt_iter))

#        self.slitmask.outFoV()
#        print self.slitlets.data['fov_flag']
#        self.updatetabs()
        #Listen to different signals

        #menu items
        QtCore.QObject.connect(self.ui.actionLoad_Catalogue, QtCore.SIGNAL("triggered()"), self.loadcatalog)
        QtCore.QObject.connect(self.ui.actionLoad_Image, QtCore.SIGNAL("triggered()"), self.loadimage)

        #main tabs
        QtCore.QObject.connect(self.ui.lineEditMain_CenRA, QtCore.SIGNAL("editingFinished()"), self.loadCenRA)
        QtCore.QObject.connect(self.ui.lineEditMain_CenDEC, QtCore.SIGNAL("editingFinished()"), self.loadCenDEC)
        QtCore.QObject.connect(self.ui.lineEditMain_PA, QtCore.SIGNAL("editingFinished()"), self.loadpositionangle)
        QtCore.QObject.connect(self.ui.lineEditMain_Equinox, QtCore.SIGNAL("editingFinished()"), self.loadequinox)
        QtCore.QObject.connect(self.ui.lineEditMain_TargetName, QtCore.SIGNAL("editingFinished()"), self.loadtargetname)
        QtCore.QObject.connect(self.ui.lineEditMain_MaskName, QtCore.SIGNAL("editingFinished()"), self.loadmaskname)
        
        #info tabs
        QtCore.QObject.connect(self.ui.lineEditInfo_ProposalCode, QtCore.SIGNAL("editingFinished()"), self.loadproposalcode)
        QtCore.QObject.connect(self.ui.lineEditInfo_Proposer, QtCore.SIGNAL("editingFinished()"), self.loadproposer)
        QtCore.QObject.connect(self.ui.lineEditInfo_Creator, QtCore.SIGNAL("editingFinished()"), self.loadcreator)

#        QtCore.QObject.connect(self.slitmask, SIGNAL('xmlloaded'), self.setcreator)

        QtCore.QObject.connect(self.ui.radioButtonInfo_Catalogue, QtCore.SIGNAL("clicked()"), self.setmode2cat)
        QtCore.QObject.connect(self.ui.radioButtonInfo_Manual, QtCore.SIGNAL("clicked()"), self.setmode2manual)
        QtCore.QObject.connect(self.ui.checkBoxInfo_CentroidOn, QtCore.SIGNAL("clicked()"), self.setmodecentroiding)

        
        
        #catalog tabs
        QtCore.QObject.connect(self.ui.toolButtonCat_Load, QtCore.SIGNAL("clicked(bool)"), self.loadcatalog)
        QtCore.QObject.connect(self.ui.pushButtonCat_AddSlits, QtCore.SIGNAL("clicked(bool)"), self.addslitfromcatalog)
        QtCore.QObject.connect(self.ui.pushButtonCat_Clear, QtCore.SIGNAL("clicked()"), self.clearContents)

        #slit tab
        QtCore.QObject.connect(self.ui.pushButtonSlit_ClearSlits, QtCore.SIGNAL("clicked()"), self.clearslittable)
        QtCore.QObject.connect(self.ui.pushButtonSlit_AddSlitImage, QtCore.SIGNAL("clicked()"), self.addslitletsfromimage)
        QtCore.QObject.connect(self.ui.pushButtonSlit_AddSlitfromCat, QtCore.SIGNAL("clicked()"), self.addslitletsfromcatalogue)
        QtCore.QObject.connect(self.ui.pushButtonSlit_AddSlit, QtCore.SIGNAL("clicked()"), self.addslitmanually)
        QtCore.QObject.connect(self.ui.pushButtonSlit_DeleteSlit, QtCore.SIGNAL("clicked()"), self.deleteslitmanually)
        QtCore.QObject.connect(self.ui.pushButtonSlit_DeleteSlitImage, QtCore.SIGNAL("clicked()"), self.deleteslitfromimage)
        QtCore.QObject.connect(self.ui.tableWidgetSlits, QtCore.SIGNAL("itemSelectionChanged()"), self.setposition)
        QtCore.QObject.connect(self.ui.tableWidgetSlits, QtCore.SIGNAL("cellChanged(int, int)"), self.slitchanged)

        #optimize tab
        QtCore.QObject.connect(self.ui.pushButtonOpt_Optimize, QtCore.SIGNAL("clicked()"), self.optimize)
        QtCore.QObject.connect(self.ui.lineEditOpt_Yspacing, QtCore.SIGNAL("editingFinished()"), self.setoptimizer_yspacing)
        QtCore.QObject.connect(self.ui.lineEditOpt_Niter, QtCore.SIGNAL("editingFinished()"), self.setoptimizer_iter)
        QtCore.QObject.connect(self.ui.checkBoxOpt_IncRefstars, QtCore.SIGNAL("stateChanged(int)"), self.includerefstars)
        QtCore.QObject.connect(self.ui.lineEditOpt_NumRefstars, QtCore.SIGNAL("editingFinished()"), self.setnumrefstars)

        #ref stars
        QtCore.QObject.connect(self.ui.pushButtonRef_ClearRefstars, QtCore.SIGNAL("clicked()"), self.clearrefstartable)
        QtCore.QObject.connect(self.ui.pushButtonRef_AddRefstarImage, QtCore.SIGNAL("clicked()"), self.addslitletsfromimage)
        QtCore.QObject.connect(self.ui.pushButtonRef_AddRefstarsfromCat, QtCore.SIGNAL("clicked()"), self.addrefstarsfromcatalogue)
        QtCore.QObject.connect(self.ui.pushButtonRef_AddRefstar, QtCore.SIGNAL("clicked()"), self.addrefstarmanually)
        QtCore.QObject.connect(self.ui.pushButtonRef_DeleteRefstar, QtCore.SIGNAL("clicked()"), self.deleterefstarmanually)
        QtCore.QObject.connect(self.ui.pushButtonRef_DeleteRefstar_2, QtCore.SIGNAL("clicked()"), self.deleteslitfromimage)
        QtCore.QObject.connect(self.ui.tableWidgetRefstars, QtCore.SIGNAL(" itemSelectionChanged()"), self.setrefposition)
        QtCore.QObject.connect(self.ui.tableWidgetRefstars, QtCore.SIGNAL("cellChanged(int, int)"), self.refchanged)

        # finalize tab
        QtCore.QObject.connect(self.ui.pushButtonFin_Validate, QtCore.SIGNAL("clicked(bool)"),self.validator)
        QtCore.QObject.connect(self.ui.pushButtonFin_WriteXML, QtCore.SIGNAL("clicked(bool)"), self.writexml)
        QtCore.QObject.connect(self.ui.toolButtonFin_WriteRSMT, QtCore.SIGNAL("clicked(bool)"), self.writersmt)
        QtCore.QObject.connect(self.ui.pushButtonFin_CreateFChart_Current, QtCore.SIGNAL("clicked(bool)"), self.writeFC_Current)
        QtCore.QObject.connect(self.ui.pushButtonFin_CreateFChart_DSS, QtCore.SIGNAL("clicked(bool)"), self.writeFC_DSS)

 
        self.ui.tabWidget.setCurrentIndex(0)

    def clearContents(self):
        self.slitlets.data = None
        self.ui.tableWidgetCat.clearContents()
        self.ui.tableWidgetCat.setRowCount(0)
        #TODO: Set the number of rows to the current data length
        #print 'nope not doing it'

    # loads mask coordinates
    def loadCenRA(self):
        self.slitmask.validated = False
        self.slitmask.add_center_ra(ra_read(self.ui.lineEditMain_CenRA.text()))
        if self.slitmask.center_ra == None:
            palette = self.setPalette('error')
            self.ui.lineEditMain_CenRA.setPalette(palette)
        else:
            palette = self.setPalette('normal')
            self.ui.lineEditMain_CenRA.setPalette(palette)
            self.ui.lineEditMain_CenRA.setText(str(self.slitmask.center_ra))
            self.slitmask.outFoV()
            self.updatetabs()

    def loadCenDEC(self):
        self.slitmask.validated = False
        self.slitmask.add_center_dec(dec_read(self.ui.lineEditMain_CenDEC.text()))
        if self.slitmask.center_dec == None:
            palette = self.setPalette('error')
            self.ui.lineEditMain_CenDEC.setPalette(palette)
        else:
            palette = self.setPalette('normal')
            self.ui.lineEditMain_CenDEC.setPalette(palette)
            self.ui.lineEditMain_CenDEC.setText(str(self.slitmask.center_dec))
            self.slitmask.outFoV()
            self.updatetabs()

    def loadpositionangle(self):
        #print self.ui.lineEditMain_PA.text()
        self.slitmask.validated = False
        self.slitmask.add_position_angle(dec_read(self.ui.lineEditMain_PA.text()))
        if self.slitmask.position_angle == None:
            palette = self.setPalette('error')
            self.ui.lineEditMain_PA.setPalette(palette)
        else:
            palette = self.setPalette('normal')
            self.ui.lineEditMain_PA.setPalette(palette)
            self.ui.lineEditMain_PA.setText(str(self.slitmask.position_angle))
            self.slitmask.outFoV()
            self.imagedisplay.rotate(self.slitmask.position_angle)
            self.updatetabs()

    def loadequinox(self):
        self.slitmask.validated = False
        self.slitmask.add_equinox(dec_read(self.ui.lineEditMain_Equinox.text()))
        if self.slitmask.equinox == None:
            palette = self.setPalette('error')
            self.ui.lineEditMain_Equinox.setPalette(palette)
        else:
            palette = self.setPalette('normal')
            self.ui.lineEditMain_Equinox.setPalette(palette)
            self.ui.lineEditMain_Equinox.setText(str(self.slitmask.equinox))
            self.slitmask.outFoV()
            
     # load info from the main window
    def loadtargetname(self):
        self.slitmask.target_name=str(self.ui.lineEditMain_TargetName.text()).strip()
        if self.slitmask.validated:  
           if len(self.slitmask.target_name)==0: self.slitmask.validated=False

    def loadmaskname(self):
        self.slitmask.mask_name=str(self.ui.lineEditMain_MaskName.text()).strip()
        if self.slitmask.validated:  
           if len(self.slitmask.mask_name)==0: self.slitmask.validated=False
   
    def loadValue(self):
        self.updatetabs()

    def updatetabs(self):
       """Update all of the information after changes to the slitlet class"""
       print 'Updating tabs'
       self.updatecatalogtable()
       self.updateslittable()
       self.updaterefstartable()
       self.imagedisplay.deleteregions()
       self.displayslits()
#       self.displayfootprint()

    def displayslits(self): 
       """Add the slits to the image """
       ids = np.where(self.slitlets.data['inmask_flag']==1)[0]
       fout = open('tmp.reg', 'w')
       fout.write('# Region file format: DS9 version 4.1\n# Filename: sgpR.fits\n')

       fout.write('global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\n')
       fout.write('fk5\n')

       for i in ids:
           fout.write(self.slitlets.asregion(i,self.slitmask.position_angle)+'\n')
           # show spectral footprint:
           #fout.write(self.slitlets.asregionspec(i,self.slitmask.position_angle)+'\n')
       fout.close()

       self.imagedisplay.regionfromfile('tmp.reg')


    def displayall(self): 
       """Add the slits to the image """
       ids=np.where(self.slitlets.data['inmask_flag']==1)[0]
       fout=open('oth.reg', 'w')
       fout.write('# Region file format: DS9 version 4.1\n# Filename: sgpR.fits\n')

       fout.write('global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\n')
       fout.write('fk5\n')

       for i in ids:
           #fout.write(self.slitlets.asregion(i,self.slitmask.position_angle)+'\n')
           # show spectral footprint:
           fout.write(self.slitlets.asregionspec(i,self.slitmask.position_angle)+'\n')
           # **** also stars, need to be careful about shape
       fout.close()

       self.imagedisplay.regionfromfile('tmp.reg')


    def displayfootprint(self):
        """Add the RSS footprint to the image"""
#       fout=open('tmpfp.reg', 'w')
#       fout.write('# Region file format: DS9 version 4.1\n# Filename: sgpR.fits\n')
#
##       fout.write('global color=yellow dashlist=8 3 width=2 font="helvetica 10 normal roman" select=0 highlite=0 dash=1 fixed=0 edit=0 move=0 delete=0 include=1 source=1\n')
#       fout.write('fk5\n')
#       fout.write('circle(%f,%f,4\') # color=yellow dashlist=8 3 width=2 select=0 highlite=0 dash=1 fixed=0 edit=0 move=1 delete=0 background include=1 source=0\n' % (self.slitmask.center_ra, self.slitmask.center_dec))
#       fout.close()
#       self.imagedisplay.regionfromfile('tmpfp.reg')
        self.imagedisplay.rssregion(self.slitmask.center_ra, self.slitmask.center_dec)

    def loadimage(self, inimage=None):
        if not inimage:
             #launch a file IO dialog
             ldir = os.getcwd()
             inimage = QtGui.QFileDialog.getOpenFileName(caption="Open Catalog", directory=ldir)

        self.inimage=str(inimage)
        self.imagedisplay.display(inimage, pa=self.position_angle)

    def deleteslitfromimage(self):
        #download the slits in the image
        newslits=self.imagedisplay.getregions()
        

        #loop through the list and see which one is missing
        try:
            index=np.where(self.slitlets.data['inmask_flag']==1)[0]
        except:
            return
        
 
        #check to see if it is in the mask
        for i in index:
            sra=self.slitlets.data['targ_ra'][i]
            sdec=self.slitlets.data['targ_dec'][i]
            found=False
            for k in newslits.keys():
              ra = float(newslits[k][0][0])
              dec = float(newslits[k][0][1])
              if abs(sra-ra) < 0.0003 and abs(sdec-dec) < 0.0003:
                 found=True
            if not found:
               self.slitlets.data['inmask_flag'][i]=0

        #update the tabs
        self.updatetabs()      


    def addslitletsfromimage(self):
        """Download the slits from the image and add them to the slitlet or catalog

          If catalog is selected, it will search the catalog for a corresponding object and center the slit on that object

          **TODO**
          If manual centroided is selected, it will centroid around that value in the image and use that position
          If manual uncentroided is selected, it will just use the slit position

        """
        #download the slits in the image
        newslits=self.imagedisplay.getregions()
        #loop through the objects--if they are already in the catalog check to see if they
        #need updating.  If not, then add them to the catalog

        #print "Sorting through regions"

        for i in newslits:
            if newslits[i][1]:
              #if it is tagged we assume it is already in the slitmask
              #print newslits[i]
              pass
            else:
              ra = float(newslits[i][0][0])
              dec = float(newslits[i][0][1])
              #print i,ra,dec
           #width=str(newslits[i][0])
           #height=str(newslits[i][0])
           #tilt=str(newslits[i][0])
              #TODO: This searches that catalog and adds the target that matches the slit drawn
              sid=self.slitlets.findtarget(ra,dec)
              self.slitlets.addtomask(sid)

         
        self.updatetabs()

    def setPalette(self,mode):
        palette = QtGui.QPalette()

        if mode == 'error':
            brush = QtGui.QBrush(QtGui.QColor(255, 148, 148))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
            palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)

            return palette

        if mode == 'normal':
            brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
            palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)

            return palette
Exemplo n.º 8
0
    def __init__(self, parent=None, infile=None, inimage=None, center_ra=None, center_dec=None, position_angle=None):
        QtGui.QWidget.__init__(self, parent)

        # set up the main UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #        OptimizeTab.__init__(self,self.ui)
        # set up the slitmask
        self.slitmask = SlitMask(center_ra=center_ra, center_dec=center_dec, position_angle=position_angle)
        self.slitlets = self.slitmask.slitlets

        # setup the image interaction
        self.imagedisplay = ImageDisplay(target="pySlitMask:5909")
        self.position_angle = position_angle
        if inimage:
            self.loadimage(inimage)
        # set up some variables that will be needed later
        self.xmlfile = None
        self.fcfile = None

        # read in the input data if available
        self.infile = infile
        if infile:
            self.ui.radioButtonInfo_Catalogue.setChecked(True)
            self.setmode2cat()
            self.entercatalog(infile)
            print self.slitmask.center_ra, self.slitmask.center_dec
            if self.slitmask.center_ra is None and self.slitmask.center_dec is None:
                self.slitmask.set_MaskPosition()
                self.displayfootprint()

            # if self.slitmask.center_ra and self.slitmask.center_dec:
            # self.imagedisplay.rssregion(self.slitmask.center_ra, self.slitmask.center_dec)

            self.ui.lineEditMain_CenRA.setText(str(self.slitmask.center_ra))
            self.ui.lineEditMain_CenDEC.setText(str(self.slitmask.center_dec))
            self.ui.lineEditMain_PA.setText(str(self.slitmask.position_angle))
            self.ui.lineEditMain_Equinox.setText(str(self.slitmask.equinox))

            self.ui.lineEditMain_TargetName.setText(self.slitmask.target_name)
            self.ui.lineEditMain_MaskName.setText(self.slitmask.mask_name)
            self.ui.lineEditInfo_Creator.setText(self.slitmask.creator)
            self.ui.lineEditInfo_Proposer.setText(self.slitmask.proposer)
            self.ui.lineEditInfo_ProposalCode.setText(self.slitmask.proposal_code)
        else:
            self.ui.radioButtonInfo_Catalogue.setChecked(False)
            self.ui.radioButtonInfo_Manual.setChecked(True)
            self.setmode2manual()
            self.ui.toolButtonCat_Load.setEnabled(True)

            # self.displayfootprint()

        #        self.opttab = OptimizeTab()
        # setup default values for the optimizer
        self.opt_yspacing = 1.0
        self.opt_iter = 10
        self.ui.lineEditOpt_Yspacing.setText(str(self.opt_yspacing))
        self.ui.lineEditOpt_Niter.setText(str(self.opt_iter))

        #        self.slitmask.outFoV()
        #        print self.slitlets.data['fov_flag']
        #        self.updatetabs()
        # Listen to different signals

        # menu items
        QtCore.QObject.connect(self.ui.actionLoad_Catalogue, QtCore.SIGNAL("triggered()"), self.loadcatalog)
        QtCore.QObject.connect(self.ui.actionLoad_Image, QtCore.SIGNAL("triggered()"), self.loadimage)

        # main tabs
        QtCore.QObject.connect(self.ui.lineEditMain_CenRA, QtCore.SIGNAL("editingFinished()"), self.loadCenRA)
        QtCore.QObject.connect(self.ui.lineEditMain_CenDEC, QtCore.SIGNAL("editingFinished()"), self.loadCenDEC)
        QtCore.QObject.connect(self.ui.lineEditMain_PA, QtCore.SIGNAL("editingFinished()"), self.loadpositionangle)
        QtCore.QObject.connect(self.ui.lineEditMain_Equinox, QtCore.SIGNAL("editingFinished()"), self.loadequinox)
        QtCore.QObject.connect(self.ui.lineEditMain_TargetName, QtCore.SIGNAL("editingFinished()"), self.loadtargetname)
        QtCore.QObject.connect(self.ui.lineEditMain_MaskName, QtCore.SIGNAL("editingFinished()"), self.loadmaskname)

        # info tabs
        QtCore.QObject.connect(
            self.ui.lineEditInfo_ProposalCode, QtCore.SIGNAL("editingFinished()"), self.loadproposalcode
        )
        QtCore.QObject.connect(self.ui.lineEditInfo_Proposer, QtCore.SIGNAL("editingFinished()"), self.loadproposer)
        QtCore.QObject.connect(self.ui.lineEditInfo_Creator, QtCore.SIGNAL("editingFinished()"), self.loadcreator)

        #        QtCore.QObject.connect(self.slitmask, SIGNAL('xmlloaded'), self.setcreator)

        QtCore.QObject.connect(self.ui.radioButtonInfo_Catalogue, QtCore.SIGNAL("clicked()"), self.setmode2cat)
        QtCore.QObject.connect(self.ui.radioButtonInfo_Manual, QtCore.SIGNAL("clicked()"), self.setmode2manual)
        QtCore.QObject.connect(self.ui.checkBoxInfo_CentroidOn, QtCore.SIGNAL("clicked()"), self.setmodecentroiding)

        # catalog tabs
        QtCore.QObject.connect(self.ui.toolButtonCat_Load, QtCore.SIGNAL("clicked(bool)"), self.loadcatalog)
        QtCore.QObject.connect(self.ui.pushButtonCat_AddSlits, QtCore.SIGNAL("clicked(bool)"), self.addslitfromcatalog)
        QtCore.QObject.connect(self.ui.pushButtonCat_Clear, QtCore.SIGNAL("clicked()"), self.clearContents)

        # slit tab
        QtCore.QObject.connect(self.ui.pushButtonSlit_ClearSlits, QtCore.SIGNAL("clicked()"), self.clearslittable)
        QtCore.QObject.connect(
            self.ui.pushButtonSlit_AddSlitImage, QtCore.SIGNAL("clicked()"), self.addslitletsfromimage
        )
        QtCore.QObject.connect(
            self.ui.pushButtonSlit_AddSlitfromCat, QtCore.SIGNAL("clicked()"), self.addslitletsfromcatalogue
        )
        QtCore.QObject.connect(self.ui.pushButtonSlit_AddSlit, QtCore.SIGNAL("clicked()"), self.addslitmanually)
        QtCore.QObject.connect(self.ui.pushButtonSlit_DeleteSlit, QtCore.SIGNAL("clicked()"), self.deleteslitmanually)
        QtCore.QObject.connect(
            self.ui.pushButtonSlit_DeleteSlitImage, QtCore.SIGNAL("clicked()"), self.deleteslitfromimage
        )
        QtCore.QObject.connect(self.ui.tableWidgetSlits, QtCore.SIGNAL("itemSelectionChanged()"), self.setposition)
        QtCore.QObject.connect(self.ui.tableWidgetSlits, QtCore.SIGNAL("cellChanged(int, int)"), self.slitchanged)

        # optimize tab
        QtCore.QObject.connect(self.ui.pushButtonOpt_Optimize, QtCore.SIGNAL("clicked()"), self.optimize)
        QtCore.QObject.connect(
            self.ui.lineEditOpt_Yspacing, QtCore.SIGNAL("editingFinished()"), self.setoptimizer_yspacing
        )
        QtCore.QObject.connect(self.ui.lineEditOpt_Niter, QtCore.SIGNAL("editingFinished()"), self.setoptimizer_iter)
        QtCore.QObject.connect(
            self.ui.checkBoxOpt_IncRefstars, QtCore.SIGNAL("stateChanged(int)"), self.includerefstars
        )
        QtCore.QObject.connect(self.ui.lineEditOpt_NumRefstars, QtCore.SIGNAL("editingFinished()"), self.setnumrefstars)

        # ref stars
        QtCore.QObject.connect(self.ui.pushButtonRef_ClearRefstars, QtCore.SIGNAL("clicked()"), self.clearrefstartable)
        QtCore.QObject.connect(
            self.ui.pushButtonRef_AddRefstarImage, QtCore.SIGNAL("clicked()"), self.addslitletsfromimage
        )
        QtCore.QObject.connect(
            self.ui.pushButtonRef_AddRefstarsfromCat, QtCore.SIGNAL("clicked()"), self.addrefstarsfromcatalogue
        )
        QtCore.QObject.connect(self.ui.pushButtonRef_AddRefstar, QtCore.SIGNAL("clicked()"), self.addrefstarmanually)
        QtCore.QObject.connect(
            self.ui.pushButtonRef_DeleteRefstar, QtCore.SIGNAL("clicked()"), self.deleterefstarmanually
        )
        QtCore.QObject.connect(
            self.ui.pushButtonRef_DeleteRefstar_2, QtCore.SIGNAL("clicked()"), self.deleteslitfromimage
        )
        QtCore.QObject.connect(
            self.ui.tableWidgetRefstars, QtCore.SIGNAL(" itemSelectionChanged()"), self.setrefposition
        )
        QtCore.QObject.connect(self.ui.tableWidgetRefstars, QtCore.SIGNAL("cellChanged(int, int)"), self.refchanged)

        # finalize tab
        QtCore.QObject.connect(self.ui.pushButtonFin_Validate, QtCore.SIGNAL("clicked(bool)"), self.validator)
        QtCore.QObject.connect(self.ui.pushButtonFin_WriteXML, QtCore.SIGNAL("clicked(bool)"), self.writexml)
        QtCore.QObject.connect(self.ui.toolButtonFin_WriteRSMT, QtCore.SIGNAL("clicked(bool)"), self.writersmt)
        QtCore.QObject.connect(
            self.ui.pushButtonFin_CreateFChart_Current, QtCore.SIGNAL("clicked(bool)"), self.writeFC_Current
        )
        QtCore.QObject.connect(self.ui.pushButtonFin_CreateFChart_DSS, QtCore.SIGNAL("clicked(bool)"), self.writeFC_DSS)

        self.ui.tabWidget.setCurrentIndex(0)
Exemplo n.º 9
0
class SlitMaskGui(QtGui.QMainWindow, InfoTab, CatalogTab, OptimizeTab, SlitTab, RefTab, FinalizeTab):
    def __init__(self, parent=None, infile=None, inimage=None, center_ra=None, center_dec=None, position_angle=None):
        QtGui.QWidget.__init__(self, parent)

        # set up the main UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #        OptimizeTab.__init__(self,self.ui)
        # set up the slitmask
        self.slitmask = SlitMask(center_ra=center_ra, center_dec=center_dec, position_angle=position_angle)
        self.slitlets = self.slitmask.slitlets

        # setup the image interaction
        self.imagedisplay = ImageDisplay(target="pySlitMask:5909")
        self.position_angle = position_angle
        if inimage:
            self.loadimage(inimage)
        # set up some variables that will be needed later
        self.xmlfile = None
        self.fcfile = None

        # read in the input data if available
        self.infile = infile
        if infile:
            self.ui.radioButtonInfo_Catalogue.setChecked(True)
            self.setmode2cat()
            self.entercatalog(infile)
            print self.slitmask.center_ra, self.slitmask.center_dec
            if self.slitmask.center_ra is None and self.slitmask.center_dec is None:
                self.slitmask.set_MaskPosition()
                self.displayfootprint()

            # if self.slitmask.center_ra and self.slitmask.center_dec:
            # self.imagedisplay.rssregion(self.slitmask.center_ra, self.slitmask.center_dec)

            self.ui.lineEditMain_CenRA.setText(str(self.slitmask.center_ra))
            self.ui.lineEditMain_CenDEC.setText(str(self.slitmask.center_dec))
            self.ui.lineEditMain_PA.setText(str(self.slitmask.position_angle))
            self.ui.lineEditMain_Equinox.setText(str(self.slitmask.equinox))

            self.ui.lineEditMain_TargetName.setText(self.slitmask.target_name)
            self.ui.lineEditMain_MaskName.setText(self.slitmask.mask_name)
            self.ui.lineEditInfo_Creator.setText(self.slitmask.creator)
            self.ui.lineEditInfo_Proposer.setText(self.slitmask.proposer)
            self.ui.lineEditInfo_ProposalCode.setText(self.slitmask.proposal_code)
        else:
            self.ui.radioButtonInfo_Catalogue.setChecked(False)
            self.ui.radioButtonInfo_Manual.setChecked(True)
            self.setmode2manual()
            self.ui.toolButtonCat_Load.setEnabled(True)

            # self.displayfootprint()

        #        self.opttab = OptimizeTab()
        # setup default values for the optimizer
        self.opt_yspacing = 1.0
        self.opt_iter = 10
        self.ui.lineEditOpt_Yspacing.setText(str(self.opt_yspacing))
        self.ui.lineEditOpt_Niter.setText(str(self.opt_iter))

        #        self.slitmask.outFoV()
        #        print self.slitlets.data['fov_flag']
        #        self.updatetabs()
        # Listen to different signals

        # menu items
        QtCore.QObject.connect(self.ui.actionLoad_Catalogue, QtCore.SIGNAL("triggered()"), self.loadcatalog)
        QtCore.QObject.connect(self.ui.actionLoad_Image, QtCore.SIGNAL("triggered()"), self.loadimage)

        # main tabs
        QtCore.QObject.connect(self.ui.lineEditMain_CenRA, QtCore.SIGNAL("editingFinished()"), self.loadCenRA)
        QtCore.QObject.connect(self.ui.lineEditMain_CenDEC, QtCore.SIGNAL("editingFinished()"), self.loadCenDEC)
        QtCore.QObject.connect(self.ui.lineEditMain_PA, QtCore.SIGNAL("editingFinished()"), self.loadpositionangle)
        QtCore.QObject.connect(self.ui.lineEditMain_Equinox, QtCore.SIGNAL("editingFinished()"), self.loadequinox)
        QtCore.QObject.connect(self.ui.lineEditMain_TargetName, QtCore.SIGNAL("editingFinished()"), self.loadtargetname)
        QtCore.QObject.connect(self.ui.lineEditMain_MaskName, QtCore.SIGNAL("editingFinished()"), self.loadmaskname)

        # info tabs
        QtCore.QObject.connect(
            self.ui.lineEditInfo_ProposalCode, QtCore.SIGNAL("editingFinished()"), self.loadproposalcode
        )
        QtCore.QObject.connect(self.ui.lineEditInfo_Proposer, QtCore.SIGNAL("editingFinished()"), self.loadproposer)
        QtCore.QObject.connect(self.ui.lineEditInfo_Creator, QtCore.SIGNAL("editingFinished()"), self.loadcreator)

        #        QtCore.QObject.connect(self.slitmask, SIGNAL('xmlloaded'), self.setcreator)

        QtCore.QObject.connect(self.ui.radioButtonInfo_Catalogue, QtCore.SIGNAL("clicked()"), self.setmode2cat)
        QtCore.QObject.connect(self.ui.radioButtonInfo_Manual, QtCore.SIGNAL("clicked()"), self.setmode2manual)
        QtCore.QObject.connect(self.ui.checkBoxInfo_CentroidOn, QtCore.SIGNAL("clicked()"), self.setmodecentroiding)

        # catalog tabs
        QtCore.QObject.connect(self.ui.toolButtonCat_Load, QtCore.SIGNAL("clicked(bool)"), self.loadcatalog)
        QtCore.QObject.connect(self.ui.pushButtonCat_AddSlits, QtCore.SIGNAL("clicked(bool)"), self.addslitfromcatalog)
        QtCore.QObject.connect(self.ui.pushButtonCat_Clear, QtCore.SIGNAL("clicked()"), self.clearContents)

        # slit tab
        QtCore.QObject.connect(self.ui.pushButtonSlit_ClearSlits, QtCore.SIGNAL("clicked()"), self.clearslittable)
        QtCore.QObject.connect(
            self.ui.pushButtonSlit_AddSlitImage, QtCore.SIGNAL("clicked()"), self.addslitletsfromimage
        )
        QtCore.QObject.connect(
            self.ui.pushButtonSlit_AddSlitfromCat, QtCore.SIGNAL("clicked()"), self.addslitletsfromcatalogue
        )
        QtCore.QObject.connect(self.ui.pushButtonSlit_AddSlit, QtCore.SIGNAL("clicked()"), self.addslitmanually)
        QtCore.QObject.connect(self.ui.pushButtonSlit_DeleteSlit, QtCore.SIGNAL("clicked()"), self.deleteslitmanually)
        QtCore.QObject.connect(
            self.ui.pushButtonSlit_DeleteSlitImage, QtCore.SIGNAL("clicked()"), self.deleteslitfromimage
        )
        QtCore.QObject.connect(self.ui.tableWidgetSlits, QtCore.SIGNAL("itemSelectionChanged()"), self.setposition)
        QtCore.QObject.connect(self.ui.tableWidgetSlits, QtCore.SIGNAL("cellChanged(int, int)"), self.slitchanged)

        # optimize tab
        QtCore.QObject.connect(self.ui.pushButtonOpt_Optimize, QtCore.SIGNAL("clicked()"), self.optimize)
        QtCore.QObject.connect(
            self.ui.lineEditOpt_Yspacing, QtCore.SIGNAL("editingFinished()"), self.setoptimizer_yspacing
        )
        QtCore.QObject.connect(self.ui.lineEditOpt_Niter, QtCore.SIGNAL("editingFinished()"), self.setoptimizer_iter)
        QtCore.QObject.connect(
            self.ui.checkBoxOpt_IncRefstars, QtCore.SIGNAL("stateChanged(int)"), self.includerefstars
        )
        QtCore.QObject.connect(self.ui.lineEditOpt_NumRefstars, QtCore.SIGNAL("editingFinished()"), self.setnumrefstars)

        # ref stars
        QtCore.QObject.connect(self.ui.pushButtonRef_ClearRefstars, QtCore.SIGNAL("clicked()"), self.clearrefstartable)
        QtCore.QObject.connect(
            self.ui.pushButtonRef_AddRefstarImage, QtCore.SIGNAL("clicked()"), self.addslitletsfromimage
        )
        QtCore.QObject.connect(
            self.ui.pushButtonRef_AddRefstarsfromCat, QtCore.SIGNAL("clicked()"), self.addrefstarsfromcatalogue
        )
        QtCore.QObject.connect(self.ui.pushButtonRef_AddRefstar, QtCore.SIGNAL("clicked()"), self.addrefstarmanually)
        QtCore.QObject.connect(
            self.ui.pushButtonRef_DeleteRefstar, QtCore.SIGNAL("clicked()"), self.deleterefstarmanually
        )
        QtCore.QObject.connect(
            self.ui.pushButtonRef_DeleteRefstar_2, QtCore.SIGNAL("clicked()"), self.deleteslitfromimage
        )
        QtCore.QObject.connect(
            self.ui.tableWidgetRefstars, QtCore.SIGNAL(" itemSelectionChanged()"), self.setrefposition
        )
        QtCore.QObject.connect(self.ui.tableWidgetRefstars, QtCore.SIGNAL("cellChanged(int, int)"), self.refchanged)

        # finalize tab
        QtCore.QObject.connect(self.ui.pushButtonFin_Validate, QtCore.SIGNAL("clicked(bool)"), self.validator)
        QtCore.QObject.connect(self.ui.pushButtonFin_WriteXML, QtCore.SIGNAL("clicked(bool)"), self.writexml)
        QtCore.QObject.connect(self.ui.toolButtonFin_WriteRSMT, QtCore.SIGNAL("clicked(bool)"), self.writersmt)
        QtCore.QObject.connect(
            self.ui.pushButtonFin_CreateFChart_Current, QtCore.SIGNAL("clicked(bool)"), self.writeFC_Current
        )
        QtCore.QObject.connect(self.ui.pushButtonFin_CreateFChart_DSS, QtCore.SIGNAL("clicked(bool)"), self.writeFC_DSS)

        self.ui.tabWidget.setCurrentIndex(0)

    def clearContents(self):
        self.slitlets.data = None
        self.ui.tableWidgetCat.clearContents()
        self.ui.tableWidgetCat.setRowCount(0)
        # TODO: Set the number of rows to the current data length
        # print 'nope not doing it'

    # loads mask coordinates
    def loadCenRA(self):
        self.slitmask.validated = False
        self.slitmask.add_center_ra(ra_read(self.ui.lineEditMain_CenRA.text()))
        if self.slitmask.center_ra == None:
            palette = self.setPalette("error")
            self.ui.lineEditMain_CenRA.setPalette(palette)
        else:
            palette = self.setPalette("normal")
            self.ui.lineEditMain_CenRA.setPalette(palette)
            self.ui.lineEditMain_CenRA.setText(str(self.slitmask.center_ra))
            self.slitmask.outFoV()
            self.updatetabs()

    def loadCenDEC(self):
        self.slitmask.validated = False
        self.slitmask.add_center_dec(dec_read(self.ui.lineEditMain_CenDEC.text()))
        if self.slitmask.center_dec == None:
            palette = self.setPalette("error")
            self.ui.lineEditMain_CenDEC.setPalette(palette)
        else:
            palette = self.setPalette("normal")
            self.ui.lineEditMain_CenDEC.setPalette(palette)
            self.ui.lineEditMain_CenDEC.setText(str(self.slitmask.center_dec))
            self.slitmask.outFoV()
            self.updatetabs()

    def loadpositionangle(self):
        # print self.ui.lineEditMain_PA.text()
        self.slitmask.validated = False
        self.slitmask.add_position_angle(dec_read(self.ui.lineEditMain_PA.text()))
        if self.slitmask.position_angle == None:
            palette = self.setPalette("error")
            self.ui.lineEditMain_PA.setPalette(palette)
        else:
            palette = self.setPalette("normal")
            self.ui.lineEditMain_PA.setPalette(palette)
            self.ui.lineEditMain_PA.setText(str(self.slitmask.position_angle))
            self.slitmask.outFoV()
            self.imagedisplay.rotate(self.slitmask.position_angle)
            self.updatetabs()

    def loadequinox(self):
        self.slitmask.validated = False
        self.slitmask.add_equinox(dec_read(self.ui.lineEditMain_Equinox.text()))
        if self.slitmask.equinox == None:
            palette = self.setPalette("error")
            self.ui.lineEditMain_Equinox.setPalette(palette)
        else:
            palette = self.setPalette("normal")
            self.ui.lineEditMain_Equinox.setPalette(palette)
            self.ui.lineEditMain_Equinox.setText(str(self.slitmask.equinox))
            self.slitmask.outFoV()

    # load info from the main window
    def loadtargetname(self):
        self.slitmask.target_name = str(self.ui.lineEditMain_TargetName.text()).strip()
        if self.slitmask.validated:
            if len(self.slitmask.target_name) == 0:
                self.slitmask.validated = False

    def loadmaskname(self):
        self.slitmask.mask_name = str(self.ui.lineEditMain_MaskName.text()).strip()
        if self.slitmask.validated:
            if len(self.slitmask.mask_name) == 0:
                self.slitmask.validated = False

    def loadValue(self):
        self.updatetabs()

    def updatetabs(self):
        """Update all of the information after changes to the slitlet class"""
        print "Updating tabs"
        self.updatecatalogtable()
        self.updateslittable()
        self.updaterefstartable()
        self.imagedisplay.deleteregions()
        self.displayslits()

    #       self.displayfootprint()

    def displayslits(self):
        """Add the slits to the image """
        ids = np.where(self.slitlets.data["inmask_flag"] == 1)[0]
        fout = open("tmp.reg", "w")
        fout.write("# Region file format: DS9 version 4.1\n# Filename: sgpR.fits\n")

        fout.write(
            'global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\n'
        )
        fout.write("fk5\n")

        for i in ids:
            fout.write(self.slitlets.asregion(i, self.slitmask.position_angle) + "\n")
            # show spectral footprint:
            # fout.write(self.slitlets.asregionspec(i,self.slitmask.position_angle)+'\n')
        fout.close()

        self.imagedisplay.regionfromfile("tmp.reg")

    def displayall(self):
        """Add the slits to the image """
        ids = np.where(self.slitlets.data["inmask_flag"] == 1)[0]
        fout = open("oth.reg", "w")
        fout.write("# Region file format: DS9 version 4.1\n# Filename: sgpR.fits\n")

        fout.write(
            'global color=green dashlist=8 3 width=1 font="helvetica 10 normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\n'
        )
        fout.write("fk5\n")

        for i in ids:
            # fout.write(self.slitlets.asregion(i,self.slitmask.position_angle)+'\n')
            # show spectral footprint:
            fout.write(self.slitlets.asregionspec(i, self.slitmask.position_angle) + "\n")
            # **** also stars, need to be careful about shape
        fout.close()

        self.imagedisplay.regionfromfile("tmp.reg")

    def displayfootprint(self):
        """Add the RSS footprint to the image"""
        #       fout=open('tmpfp.reg', 'w')
        #       fout.write('# Region file format: DS9 version 4.1\n# Filename: sgpR.fits\n')
        #
        ##       fout.write('global color=yellow dashlist=8 3 width=2 font="helvetica 10 normal roman" select=0 highlite=0 dash=1 fixed=0 edit=0 move=0 delete=0 include=1 source=1\n')
        #       fout.write('fk5\n')
        #       fout.write('circle(%f,%f,4\') # color=yellow dashlist=8 3 width=2 select=0 highlite=0 dash=1 fixed=0 edit=0 move=1 delete=0 background include=1 source=0\n' % (self.slitmask.center_ra, self.slitmask.center_dec))
        #       fout.close()
        #       self.imagedisplay.regionfromfile('tmpfp.reg')
        self.imagedisplay.rssregion(self.slitmask.center_ra, self.slitmask.center_dec)

    def loadimage(self, inimage=None):
        if not inimage:
            # launch a file IO dialog
            ldir = os.getcwd()
            inimage = QtGui.QFileDialog.getOpenFileName(caption="Open Catalog", directory=ldir)

        self.inimage = str(inimage)
        self.imagedisplay.display(inimage, pa=self.position_angle)

    def deleteslitfromimage(self):
        # download the slits in the image
        newslits = self.imagedisplay.getregions()

        # loop through the list and see which one is missing
        try:
            index = np.where(self.slitlets.data["inmask_flag"] == 1)[0]
        except:
            return

        # check to see if it is in the mask
        for i in index:
            sra = self.slitlets.data["targ_ra"][i]
            sdec = self.slitlets.data["targ_dec"][i]
            found = False
            for k in newslits.keys():
                ra = float(newslits[k][0][0])
                dec = float(newslits[k][0][1])
                if abs(sra - ra) < 0.0003 and abs(sdec - dec) < 0.0003:
                    found = True
            if not found:
                self.slitlets.data["inmask_flag"][i] = 0

        # update the tabs
        self.updatetabs()

    def addslitletsfromimage(self):
        """Download the slits from the image and add them to the slitlet or catalog

          If catalog is selected, it will search the catalog for a corresponding object and center the slit on that object

          **TODO**
          If manual centroided is selected, it will centroid around that value in the image and use that position
          If manual uncentroided is selected, it will just use the slit position

        """
        # download the slits in the image
        newslits = self.imagedisplay.getregions()
        # loop through the objects--if they are already in the catalog check to see if they
        # need updating.  If not, then add them to the catalog

        # print "Sorting through regions"

        for i in newslits:
            if newslits[i][1]:
                # if it is tagged we assume it is already in the slitmask
                # print newslits[i]
                pass
            else:
                ra = float(newslits[i][0][0])
                dec = float(newslits[i][0][1])
                # print i,ra,dec
                # width=str(newslits[i][0])
                # height=str(newslits[i][0])
                # tilt=str(newslits[i][0])
                # TODO: This searches that catalog and adds the target that matches the slit drawn
                sid = self.slitlets.findtarget(ra, dec)
                self.slitlets.addtomask(sid)

        self.updatetabs()

    def setPalette(self, mode):
        palette = QtGui.QPalette()

        if mode == "error":
            brush = QtGui.QBrush(QtGui.QColor(255, 148, 148))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
            palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)

            return palette

        if mode == "normal":
            brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
            palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)

            return palette