idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
24,800
def set_suffix ( self ) : self . suffix = self . w . suffix . get_text ( ) self . logger . debug ( 'Output suffix set to {0}' . format ( self . suffix ) )
Set output suffix .
47
4
24,801
def _write_history ( self , pfx , hdu , linechar = 60 , indentchar = 2 ) : channel = self . fv . get_channel ( self . chname ) if channel is None : return history_plgname = 'ChangeHistory' try : history_obj = self . fv . gpmon . getPlugin ( history_plgname ) except Exception : self . logger . error ( '{0} plugin is not loaded. No HISTORY will be written to ' '{1}.' . format ( history_plgname , pfx ) ) return if channel . name not in history_obj . name_dict : self . logger . error ( '{0} channel not found in {1}. No HISTORY will be written to ' '{2}.' . format ( channel . name , history_plgname , pfx ) ) return file_dict = history_obj . name_dict [ channel . name ] chistory = [ ] ind = ' ' * indentchar # NOTE: List comprehension too slow! for key in file_dict : if not key . startswith ( pfx ) : continue for bnch in file_dict [ key ] . values ( ) : chistory . append ( '{0} {1}' . format ( bnch . MODIFIED , bnch . DESCRIP ) ) # Add each HISTORY prettily into header, sorted by timestamp for s in sorted ( chistory ) : for i in range ( 0 , len ( s ) , linechar ) : subs = s [ i : i + linechar ] if i > 0 : subs = ind + subs . lstrip ( ) hdu . header . add_history ( subs )
Write change history to given HDU header . Limit each HISTORY line to given number of characters . Subsequent lines of the same history will be indented .
368
32
24,802
def _write_header ( self , image , hdu ) : hduhdr = hdu . header # Ginga image header object for the given extension only. # Cannot use get_header() because that might also return PRI hdr. ghdr = image . metadata [ 'header' ] for key in ghdr : # Need this to avoid duplication because COMMENT is a weird field if key . upper ( ) == 'COMMENT' : continue bnch = ghdr . get_card ( key ) # Insert new keyword if key not in hduhdr : hduhdr [ key ] = ( bnch . value , bnch . comment ) # Update existing keyword elif hduhdr [ key ] != bnch . value : hduhdr [ key ] = bnch . value
Write header from image object to given HDU .
175
10
24,803
def _write_mef ( self , key , extlist , outfile ) : channel = self . fv . get_channel ( self . chname ) with fits . open ( outfile , mode = 'update' ) as pf : # Process each modified data extension for idx in extlist : k = '{0}[{1}]' . format ( key , self . _format_extname ( idx ) ) image = channel . datasrc [ k ] # Insert data and header into output HDU pf [ idx ] . data = image . get_data ( ) self . _write_header ( image , pf [ idx ] ) # Write history to PRIMARY self . _write_history ( key , pf [ 'PRIMARY' ] )
Write out regular multi - extension FITS data .
169
10
24,804
def toggle_save_cb ( self , w , res_dict ) : if len ( res_dict ) > 0 : self . w . save . set_enabled ( True ) else : self . w . save . set_enabled ( False )
Only enable saving if something is selected .
52
8
24,805
def save_images ( self ) : res_dict = self . treeview . get_selected ( ) clobber = self . settings . get ( 'clobber' , False ) self . treeview . clear_selection ( ) # Automatically disables Save button # If user gives empty string, no suffix. if self . suffix : sfx = '_' + self . suffix else : sfx = '' # Also include channel name in suffix. This is useful if user likes to # open the same image in multiple channels. if self . settings . get ( 'include_chname' , True ) : sfx += '_' + self . chname # Process each selected file. Each can have multiple edited extensions. for infile in res_dict : f_pfx = os . path . splitext ( infile ) [ 0 ] # prefix f_ext = '.fits' # Only FITS supported oname = f_pfx + sfx + f_ext outfile = os . path . join ( self . outdir , oname ) self . w . status . set_text ( 'Writing out {0} to {1} ...' . format ( shorten_name ( infile , 10 ) , shorten_name ( oname , 10 ) ) ) self . logger . debug ( 'Writing out {0} to {1} ...' . format ( infile , oname ) ) if os . path . exists ( outfile ) and not clobber : self . logger . error ( '{0} already exists' . format ( outfile ) ) continue bnch = res_dict [ infile ] if bnch . path is None or not os . path . isfile ( bnch . path ) : self . _write_mosaic ( f_pfx , outfile ) else : shutil . copyfile ( bnch . path , outfile ) self . _write_mef ( f_pfx , bnch . extlist , outfile ) self . logger . info ( '{0} written' . format ( outfile ) ) self . w . status . set_text ( 'Saving done, see log' )
Save selected images .
466
4
24,806
def font_info ( font_str ) : vals = font_str . split ( ';' ) point_size , style , weight = 8 , 'normal' , 'normal' family = vals [ 0 ] if len ( vals ) > 1 : style = vals [ 1 ] if len ( vals ) > 2 : weight = vals [ 2 ] match = font_regex . match ( family ) if match : family , point_size = match . groups ( ) point_size = int ( point_size ) return Bunch . Bunch ( family = family , point_size = point_size , style = style , weight = weight )
Extract font information from a font string such as supplied to the font argument to a widget .
141
19
24,807
def get_points ( self ) : if hasattr ( self , 'points' ) : points = self . crdmap . to_data ( self . points ) else : points = [ ] return points
Get the set of points that is used to draw the object .
43
13
24,808
def get_data_points ( self , points = None ) : if points is None : points = self . points points = self . crdmap . to_data ( points ) return points
Points returned are in data coordinates .
40
7
24,809
def set_data_points ( self , points ) : self . points = np . asarray ( self . crdmap . data_to ( points ) )
Input points must be in data coordinates will be converted to the coordinate space of the object and stored .
34
20
24,810
def convert_mapper ( self , tomap ) : frommap = self . crdmap if frommap == tomap : return # mild hack to convert radii on objects that have them if hasattr ( self , 'radius' ) : # get coordinates of a point radius away from center # under current coordmap x0 , y0 = frommap . offset_pt ( ( self . x , self . y ) , ( self . radius , 0 ) ) pts = frommap . to_data ( ( ( self . x , self . y ) , ( x0 , y0 ) ) ) pts = tomap . data_to ( pts ) self . radius = np . fabs ( pts [ 1 ] [ 0 ] - pts [ 0 ] [ 0 ] ) elif hasattr ( self , 'xradius' ) : # similar to above case, but there are 2 radii x0 , y0 = frommap . offset_pt ( ( self . x , self . y ) , ( self . xradius , self . yradius ) ) pts = frommap . to_data ( ( ( self . x , self . y ) , ( x0 , y0 ) ) ) pts = tomap . data_to ( pts ) self . xradius = np . fabs ( pts [ 1 ] [ 0 ] - pts [ 0 ] [ 0 ] ) self . yradius = np . fabs ( pts [ 1 ] [ 1 ] - pts [ 0 ] [ 1 ] ) data_pts = self . get_data_points ( ) # set our map to the new map self . crdmap = tomap self . set_data_points ( data_pts )
Converts our object from using one coordinate map to another .
357
12
24,811
def point_within_radius ( self , points , pt , canvas_radius , scales = ( 1.0 , 1.0 ) ) : scale_x , scale_y = scales x , y = pt a_arr , b_arr = np . asarray ( points ) . T dx = np . fabs ( x - a_arr ) * scale_x dy = np . fabs ( y - b_arr ) * scale_y new_radius = np . sqrt ( dx ** 2 + dy ** 2 ) res = ( new_radius <= canvas_radius ) return res
Points points and point pt are in data coordinates . Return True for points within the circle defined by a center at point pt and within canvas_radius .
125
30
24,812
def within_radius ( self , viewer , points , pt , canvas_radius ) : scales = viewer . get_scale_xy ( ) return self . point_within_radius ( points , pt , canvas_radius , scales )
Points points and point pt are in data coordinates . Return True for points within the circle defined by a center at point pt and within canvas_radius . The distance between points is scaled by the canvas scale .
48
41
24,813
def get_pt ( self , viewer , points , pt , canvas_radius = None ) : if canvas_radius is None : canvas_radius = self . cap_radius if hasattr ( self , 'rot_deg' ) : # rotate point back to cartesian alignment for test ctr_pt = self . get_center_pt ( ) pt = trcalc . rotate_coord ( pt , [ - self . rot_deg ] , ctr_pt ) res = self . within_radius ( viewer , points , pt , canvas_radius ) return np . flatnonzero ( res )
Takes an array of points points and a target point pt . Returns the first index of the point that is within the radius of the target point . If none of the points are within the radius returns None .
126
42
24,814
def within_line ( self , viewer , points , p_start , p_stop , canvas_radius ) : scale_x , scale_y = viewer . get_scale_xy ( ) new_radius = canvas_radius * 1.0 / min ( scale_x , scale_y ) return self . point_within_line ( points , p_start , p_stop , new_radius )
Points points and line endpoints p_start p_stop are in data coordinates . Return True for points within the line defined by a line from p_start to p_end and within canvas_radius . The distance between points is scaled by the viewer s canvas scale .
86
55
24,815
def get_bbox ( self , points = None ) : if points is None : x1 , y1 , x2 , y2 = self . get_llur ( ) return ( ( x1 , y1 ) , ( x1 , y2 ) , ( x2 , y2 ) , ( x2 , y1 ) ) else : return trcalc . strip_z ( trcalc . get_bounds ( points ) )
Get bounding box of this object .
95
8
24,816
def set ( self , time_sec , callback_fn , * args , * * kwdargs ) : timer = self . timer ( ) timer . set_callback ( 'expired' , callback_fn , * args , * * kwdargs ) timer . set ( time_sec ) return timer
Convenience function to create and set a timer .
64
11
24,817
def set_window_size ( self , width , height ) : self . _imgwin_wd = int ( width ) self . _imgwin_ht = int ( height ) self . _ctr_x = width // 2 self . _ctr_y = height // 2 self . logger . debug ( "widget resized to %dx%d" % ( width , height ) ) self . make_callback ( 'configure' , width , height ) self . redraw ( whence = 0 )
Report the size of the window to display the image .
105
11
24,818
def set_renderer ( self , renderer ) : self . renderer = renderer width , height = self . get_window_size ( ) if width > 0 and height > 0 : renderer . resize ( ( width , height ) )
Set and initialize the renderer used by this instance .
52
11
24,819
def set_canvas ( self , canvas , private_canvas = None ) : self . canvas = canvas canvas . initialize ( None , self , self . logger ) canvas . add_callback ( 'modified' , self . canvas_changed_cb ) canvas . set_surface ( self ) canvas . ui_set_active ( True ) self . _imgobj = None # private canvas set? if private_canvas is not None : self . private_canvas = private_canvas if private_canvas != canvas : private_canvas . set_surface ( self ) private_canvas . ui_set_active ( True ) private_canvas . add_callback ( 'modified' , self . canvas_changed_cb ) # sanity check that we have a private canvas, and if not, # set it to the "advertised" canvas if self . private_canvas is None : self . private_canvas = canvas # make sure private canvas has our non-private one added if ( self . private_canvas != self . canvas ) and ( not self . private_canvas . has_object ( canvas ) ) : self . private_canvas . add ( canvas ) self . initialize_private_canvas ( self . private_canvas )
Set the canvas object .
270
5
24,820
def initialize_private_canvas ( self , private_canvas ) : if self . t_ . get ( 'show_pan_position' , False ) : self . show_pan_mark ( True ) if self . t_ . get ( 'show_focus_indicator' , False ) : self . show_focus_indicator ( True )
Initialize the private canvas used by this instance .
76
10
24,821
def set_rgbmap ( self , rgbmap ) : self . rgbmap = rgbmap t_ = rgbmap . get_settings ( ) t_ . share_settings ( self . t_ , keylist = rgbmap . settings_keys ) rgbmap . add_callback ( 'changed' , self . rgbmap_cb ) self . redraw ( whence = 2 )
Set RGB map object used by this instance . It controls how the values in the image are mapped to color .
80
22
24,822
def get_image ( self ) : if self . _imgobj is not None : # quick optomization return self . _imgobj . get_image ( ) canvas_img = self . get_canvas_image ( ) return canvas_img . get_image ( )
Get the image currently being displayed .
59
7
24,823
def get_canvas_image ( self ) : if self . _imgobj is not None : return self . _imgobj try : # See if there is an image on the canvas self . _imgobj = self . canvas . get_object_by_tag ( self . _canvas_img_tag ) self . _imgobj . add_callback ( 'image-set' , self . _image_set_cb ) except KeyError : # add a normalized image item to this canvas if we don't # have one already--then just keep reusing it NormImage = self . canvas . getDrawClass ( 'normimage' ) interp = self . t_ . get ( 'interpolation' , 'basic' ) # previous choice might not be available if preferences # were saved when opencv was being used (and not used now) # --if so, default to "basic" if interp not in trcalc . interpolation_methods : interp = 'basic' self . _imgobj = NormImage ( 0 , 0 , None , alpha = 1.0 , interpolation = interp ) self . _imgobj . add_callback ( 'image-set' , self . _image_set_cb ) return self . _imgobj
Get canvas image object .
269
5
24,824
def set_image ( self , image , add_to_canvas = True ) : if not isinstance ( image , BaseImage . BaseImage ) : raise ValueError ( "Wrong type of object to load: %s" % ( str ( type ( image ) ) ) ) canvas_img = self . get_canvas_image ( ) old_image = canvas_img . get_image ( ) self . make_callback ( 'image-unset' , old_image ) with self . suppress_redraw : # this line should force the callback of _image_set_cb() canvas_img . set_image ( image ) if add_to_canvas : try : self . canvas . get_object_by_tag ( self . _canvas_img_tag ) except KeyError : self . canvas . add ( canvas_img , tag = self . _canvas_img_tag ) #self.logger.debug("adding image to canvas %s" % self.canvas) # move image to bottom of layers self . canvas . lower_object ( canvas_img )
Set an image to be displayed .
235
7
24,825
def save_profile ( self , * * params ) : image = self . get_image ( ) if ( image is None ) : return profile = image . get ( 'profile' , None ) if profile is None : # If image has no profile then create one profile = Settings . SettingGroup ( ) image . set ( profile = profile ) self . logger . debug ( "saving to image profile: params=%s" % ( str ( params ) ) ) profile . set ( * * params ) return profile
Save the given parameters into profile settings .
106
8
24,826
def set_data ( self , data , metadata = None ) : image = AstroImage . AstroImage ( data , metadata = metadata , logger = self . logger ) self . set_image ( image )
Set an image to be displayed by providing raw data .
42
11
24,827
def clear ( self ) : self . _imgobj = None try : # See if there is an image on the canvas self . canvas . delete_object_by_tag ( self . _canvas_img_tag ) self . redraw ( ) except KeyError : pass
Clear the displayed image .
58
5
24,828
def redraw ( self , whence = 0 ) : with self . _defer_lock : whence = min ( self . _defer_whence , whence ) if not self . defer_redraw : if self . _hold_redraw_cnt == 0 : self . _defer_whence = self . _defer_whence_reset self . redraw_now ( whence = whence ) else : self . _defer_whence = whence return elapsed = time . time ( ) - self . time_last_redraw # If there is no redraw scheduled, or we are overdue for one: if ( not self . _defer_flag ) or ( elapsed > self . defer_lagtime ) : # If more time than defer_lagtime has passed since the # last redraw then just do the redraw immediately if elapsed > self . defer_lagtime : if self . _hold_redraw_cnt > 0 : #self._defer_flag = True self . _defer_whence = whence return self . _defer_whence = self . _defer_whence_reset self . logger . debug ( "lagtime expired--forced redraw" ) self . redraw_now ( whence = whence ) return # Indicate that a redraw is necessary and record whence self . _defer_flag = True self . _defer_whence = whence # schedule a redraw by the end of the defer_lagtime secs = self . defer_lagtime - elapsed self . logger . debug ( "defer redraw (whence=%.2f) in %.f sec" % ( whence , secs ) ) self . reschedule_redraw ( secs ) else : # A redraw is already scheduled. Just record whence. self . _defer_whence = whence self . logger . debug ( "update whence=%.2f" % ( whence ) )
Redraw the canvas .
415
5
24,829
def canvas_changed_cb ( self , canvas , whence ) : self . logger . debug ( "root canvas changed, whence=%d" % ( whence ) ) # special check for whether image changed out from under us in # a shared canvas scenario try : # See if there is an image on the canvas canvas_img = self . canvas . get_object_by_tag ( self . _canvas_img_tag ) if self . _imgobj is not canvas_img : self . _imgobj = canvas_img self . _imgobj . add_callback ( 'image-set' , self . _image_set_cb ) self . _image_set_cb ( canvas_img , canvas_img . get_image ( ) ) except KeyError : self . _imgobj = None self . redraw ( whence = whence )
Handle callback for when canvas has changed .
179
8
24,830
def delayed_redraw ( self ) : # This is the optimized redraw method with self . _defer_lock : # pick up the lowest necessary level of redrawing whence = self . _defer_whence self . _defer_whence = self . _defer_whence_reset flag = self . _defer_flag self . _defer_flag = False if flag : # If a redraw was scheduled, do it now self . redraw_now ( whence = whence )
Handle delayed redrawing of the canvas .
109
9
24,831
def set_redraw_lag ( self , lag_sec ) : self . defer_redraw = ( lag_sec > 0.0 ) if self . defer_redraw : self . defer_lagtime = lag_sec
Set lag time for redrawing the canvas .
49
10
24,832
def set_refresh_rate ( self , fps ) : self . rf_fps = fps self . rf_rate = 1.0 / self . rf_fps #self.set_redraw_lag(self.rf_rate) self . logger . info ( "set a refresh rate of %.2f fps" % ( self . rf_fps ) )
Set the refresh rate for redrawing the canvas at a timed interval .
82
15
24,833
def start_refresh ( self ) : self . logger . debug ( "starting timed refresh interval" ) self . rf_flags [ 'done' ] = False self . rf_draw_count = 0 self . rf_timer_count = 0 self . rf_late_count = 0 self . rf_late_total = 0.0 self . rf_early_count = 0 self . rf_early_total = 0.0 self . rf_delta_total = 0.0 self . rf_skip_total = 0.0 self . rf_start_time = time . time ( ) self . rf_deadline = self . rf_start_time self . refresh_timer_cb ( self . rf_timer , self . rf_flags )
Start redrawing the canvas at the previously set timed interval .
176
13
24,834
def stop_refresh ( self ) : self . logger . debug ( "stopping timed refresh" ) self . rf_flags [ 'done' ] = True self . rf_timer . clear ( )
Stop redrawing the canvas at the previously set timed interval .
45
13
24,835
def get_refresh_stats ( self ) : if self . rf_draw_count == 0 : fps = 0.0 else : interval = time . time ( ) - self . rf_start_time fps = self . rf_draw_count / interval jitter = self . rf_delta_total / max ( 1 , self . rf_timer_count ) late_avg = self . rf_late_total / max ( 1 , self . rf_late_count ) late_pct = self . rf_late_count / max ( 1.0 , float ( self . rf_timer_count ) ) * 100 early_avg = self . rf_early_total / max ( 1 , self . rf_early_count ) early_pct = self . rf_early_count / max ( 1.0 , float ( self . rf_timer_count ) ) * 100 balance = self . rf_late_total - self . rf_early_total stats = dict ( fps = fps , jitter = jitter , early_avg = early_avg , early_pct = early_pct , late_avg = late_avg , late_pct = late_pct , balance = balance ) return stats
Return the measured statistics for timed refresh intervals .
285
9
24,836
def refresh_timer_cb ( self , timer , flags ) : # this is the timer call back, from the GUI thread start_time = time . time ( ) if flags . get ( 'done' , False ) : return # calculate next deadline deadline = self . rf_deadline self . rf_deadline += self . rf_rate self . rf_timer_count += 1 delta = abs ( start_time - deadline ) self . rf_delta_total += delta adjust = 0.0 if start_time > deadline : # we are late self . rf_late_total += delta self . rf_late_count += 1 late_avg = self . rf_late_total / self . rf_late_count adjust = - ( late_avg / 2.0 ) self . rf_skip_total += delta if self . rf_skip_total < self . rf_rate : self . rf_draw_count += 1 # TODO: can we optimize whence? self . redraw_now ( whence = 0 ) else : # <-- we are behind by amount of time equal to one frame. # skip a redraw and attempt to catch up some time self . rf_skip_total = 0 else : if start_time < deadline : # we are early self . rf_early_total += delta self . rf_early_count += 1 self . rf_skip_total = max ( 0.0 , self . rf_skip_total - delta ) early_avg = self . rf_early_total / self . rf_early_count adjust = early_avg / 4.0 self . rf_draw_count += 1 # TODO: can we optimize whence? self . redraw_now ( whence = 0 ) delay = max ( 0.0 , self . rf_deadline - time . time ( ) + adjust ) timer . start ( delay )
Refresh timer callback . This callback will normally only be called internally .
424
14
24,837
def redraw_now ( self , whence = 0 ) : try : time_start = time . time ( ) self . redraw_data ( whence = whence ) # finally update the window drawable from the offscreen surface self . update_image ( ) time_done = time . time ( ) time_delta = time_start - self . time_last_redraw time_elapsed = time_done - time_start self . time_last_redraw = time_done self . logger . debug ( "widget '%s' redraw (whence=%d) delta=%.4f elapsed=%.4f sec" % ( self . name , whence , time_delta , time_elapsed ) ) except Exception as e : self . logger . error ( "Error redrawing image: %s" % ( str ( e ) ) ) try : # log traceback, if possible ( type , value , tb ) = sys . exc_info ( ) tb_str = "" . join ( traceback . format_tb ( tb ) ) self . logger . error ( "Traceback:\n%s" % ( tb_str ) ) except Exception : tb_str = "Traceback information unavailable." self . logger . error ( tb_str )
Redraw the displayed image .
280
6
24,838
def redraw_data ( self , whence = 0 ) : if not self . _imgwin_set : # window has not been realized yet return if not self . _self_scaling : rgbobj = self . get_rgb_object ( whence = whence ) self . renderer . render_image ( rgbobj , self . _dst_x , self . _dst_y ) self . private_canvas . draw ( self ) self . make_callback ( 'redraw' , whence ) if whence < 2 : self . check_cursor_location ( )
Render image from RGB map and redraw private canvas .
124
11
24,839
def check_cursor_location ( self ) : # Check whether cursor data position has changed relative # to previous value data_x , data_y = self . get_data_xy ( self . last_win_x , self . last_win_y ) if ( data_x != self . last_data_x or data_y != self . last_data_y ) : self . last_data_x , self . last_data_y = data_x , data_y self . logger . debug ( "cursor location changed %.4f,%.4f => %.4f,%.4f" % ( self . last_data_x , self . last_data_y , data_x , data_y ) ) # we make this call compatible with the motion callback # for now, but there is no concept of a button here button = 0 self . make_ui_callback ( 'cursor-changed' , button , data_x , data_y ) return data_x , data_y
Check whether the data location of the last known position of the cursor has changed . If so issue a callback .
221
22
24,840
def getwin_array ( self , order = 'RGB' , alpha = 1.0 , dtype = None ) : order = order . upper ( ) depth = len ( order ) if dtype is None : rgbmap = self . get_rgbmap ( ) dtype = rgbmap . dtype # Prepare data array for rendering data = self . _rgbobj . get_array ( order , dtype = dtype ) # NOTE [A] height , width , depth = data . shape imgwin_wd , imgwin_ht = self . get_window_size ( ) # create RGBA image array with the background color for output r , g , b = self . img_bg outarr = trcalc . make_filled_array ( ( imgwin_ht , imgwin_wd , len ( order ) ) , dtype , order , r , g , b , alpha ) # overlay our data trcalc . overlay_image ( outarr , ( self . _dst_x , self . _dst_y ) , data , dst_order = order , src_order = order , flipy = False , fill = False , copy = False ) return outarr
Get Numpy data array for display window .
254
9
24,841
def get_datarect ( self ) : x1 , y1 , x2 , y2 = self . _org_x1 , self . _org_y1 , self . _org_x2 , self . _org_y2 return ( x1 , y1 , x2 , y2 )
Get the approximate bounding box of the displayed image .
67
11
24,842
def get_limits ( self , coord = 'data' ) : limits = self . t_ [ 'limits' ] if limits is None : # No user defined limits. If there is an image loaded # use its dimensions as the limits image = self . get_image ( ) if image is not None : wd , ht = image . get_size ( ) limits = ( ( self . data_off , self . data_off ) , ( float ( wd - 1 + self . data_off ) , float ( ht - 1 + self . data_off ) ) ) else : # Calculate limits based on plotted points, if any canvas = self . get_canvas ( ) pts = canvas . get_points ( ) if len ( pts ) > 0 : limits = trcalc . get_bounds ( pts ) else : # No limits found, go to default limits = ( ( 0.0 , 0.0 ) , ( 0.0 , 0.0 ) ) # convert to desired coordinates crdmap = self . get_coordmap ( coord ) limits = crdmap . data_to ( limits ) return limits
Get the bounding box of the viewer extents .
242
11
24,843
def set_limits ( self , limits , coord = 'data' ) : if limits is not None : if len ( limits ) != 2 : raise ValueError ( "limits takes a 2 tuple, or None" ) # convert to data coordinates crdmap = self . get_coordmap ( coord ) limits = crdmap . to_data ( limits ) self . t_ . set ( limits = limits )
Set the bounding box of the viewer extents .
86
11
24,844
def get_rgb_object ( self , whence = 0 ) : time_start = t2 = t3 = time . time ( ) win_wd , win_ht = self . get_window_size ( ) order = self . get_rgb_order ( ) if ( whence <= 0.0 ) or ( self . _rgbarr is None ) : # calculate dimensions of window RGB backing image pan_x , pan_y = self . get_pan ( coord = 'data' ) [ : 2 ] scale_x , scale_y = self . get_scale_xy ( ) wd , ht = self . _calc_bg_dimensions ( scale_x , scale_y , pan_x , pan_y , win_wd , win_ht ) # create backing image depth = len ( order ) rgbmap = self . get_rgbmap ( ) # make backing image with the background color r , g , b = self . img_bg rgba = trcalc . make_filled_array ( ( ht , wd , depth ) , rgbmap . dtype , order , r , g , b , 1.0 ) self . _rgbarr = rgba t2 = time . time ( ) if ( whence <= 2.0 ) or ( self . _rgbarr2 is None ) : # Apply any RGB image overlays self . _rgbarr2 = np . copy ( self . _rgbarr ) self . overlay_images ( self . private_canvas , self . _rgbarr2 , whence = whence ) # convert to output ICC profile, if one is specified output_profile = self . t_ . get ( 'icc_output_profile' , None ) working_profile = rgb_cms . working_profile if ( working_profile is not None ) and ( output_profile is not None ) : self . convert_via_profile ( self . _rgbarr2 , order , working_profile , output_profile ) t3 = time . time ( ) if ( whence <= 2.5 ) or ( self . _rgbobj is None ) : rotimg = self . _rgbarr2 # Apply any viewing transformations or rotations # if not applied earlier rotimg = self . apply_transforms ( rotimg , self . t_ [ 'rot_deg' ] ) rotimg = np . ascontiguousarray ( rotimg ) self . _rgbobj = RGBMap . RGBPlanes ( rotimg , order ) time_end = time . time ( ) ## self.logger.debug("times: total=%.4f" % ( ## (time_end - time_start))) self . logger . debug ( "times: t1=%.4f t2=%.4f t3=%.4f total=%.4f" % ( t2 - time_start , t3 - t2 , time_end - t3 , ( time_end - time_start ) ) ) return self . _rgbobj
Create and return RGB slices representing the data that should be rendered at the current zoom level and pan settings .
646
21
24,845
def _reset_bbox ( self ) : scale_x , scale_y = self . get_scale_xy ( ) pan_x , pan_y = self . get_pan ( coord = 'data' ) [ : 2 ] win_wd , win_ht = self . get_window_size ( ) # NOTE: need to set at least a minimum 1-pixel dimension on # the window or we get a scale calculation exception. See github # issue 431 win_wd , win_ht = max ( 1 , win_wd ) , max ( 1 , win_ht ) self . _calc_bg_dimensions ( scale_x , scale_y , pan_x , pan_y , win_wd , win_ht )
This function should only be called internally . It resets the viewers bounding box based on changes to pan or scale .
160
24
24,846
def overlay_images ( self , canvas , data , whence = 0.0 ) : #if not canvas.is_compound(): if not hasattr ( canvas , 'objects' ) : return for obj in canvas . get_objects ( ) : if hasattr ( obj , 'draw_image' ) : obj . draw_image ( self , data , whence = whence ) elif obj . is_compound ( ) and ( obj != canvas ) : self . overlay_images ( obj , data , whence = whence )
Overlay data from any canvas image objects .
110
9
24,847
def convert_via_profile ( self , data_np , order , inprof_name , outprof_name ) : # get rest of necessary conversion parameters to_intent = self . t_ . get ( 'icc_output_intent' , 'perceptual' ) proofprof_name = self . t_ . get ( 'icc_proof_profile' , None ) proof_intent = self . t_ . get ( 'icc_proof_intent' , 'perceptual' ) use_black_pt = self . t_ . get ( 'icc_black_point_compensation' , False ) try : rgbobj = RGBMap . RGBPlanes ( data_np , order ) arr_np = rgbobj . get_array ( 'RGB' ) arr = rgb_cms . convert_profile_fromto ( arr_np , inprof_name , outprof_name , to_intent = to_intent , proof_name = proofprof_name , proof_intent = proof_intent , use_black_pt = use_black_pt , logger = self . logger ) ri , gi , bi = rgbobj . get_order_indexes ( 'RGB' ) out = data_np out [ ... , ri ] = arr [ ... , 0 ] out [ ... , gi ] = arr [ ... , 1 ] out [ ... , bi ] = arr [ ... , 2 ] self . logger . debug ( "Converted from '%s' to '%s' profile" % ( inprof_name , outprof_name ) ) except Exception as e : self . logger . warning ( "Error converting output from working profile: %s" % ( str ( e ) ) ) # TODO: maybe should have a traceback here self . logger . info ( "Output left unprofiled" )
Convert the given RGB data from the working ICC profile to the output profile in - place .
391
19
24,848
def get_data_xy ( self , win_x , win_y , center = None ) : if center is not None : self . logger . warning ( "`center` keyword is ignored and will be deprecated" ) arr_pts = np . asarray ( ( win_x , win_y ) ) . T return self . tform [ 'data_to_native' ] . from_ ( arr_pts ) . T [ : 2 ]
Get the closest coordinates in the data array to those reported on the window .
98
15
24,849
def offset_to_window ( self , off_x , off_y ) : arr_pts = np . asarray ( ( off_x , off_y ) ) . T return self . tform [ 'cartesian_to_native' ] . to_ ( arr_pts ) . T [ : 2 ]
Convert data offset to window coordinates .
70
8
24,850
def get_pan_rect ( self ) : wd , ht = self . get_window_size ( ) #win_pts = np.asarray([(0, 0), (wd-1, 0), (wd-1, ht-1), (0, ht-1)]) win_pts = np . asarray ( [ ( 0 , 0 ) , ( wd , 0 ) , ( wd , ht ) , ( 0 , ht ) ] ) arr_pts = self . tform [ 'data_to_window' ] . from_ ( win_pts ) return arr_pts
Get the coordinates in the actual data corresponding to the area shown in the display for the current zoom level and pan .
139
23
24,851
def get_data ( self , data_x , data_y ) : image = self . get_image ( ) if image is not None : return image . get_data_xy ( data_x , data_y ) raise ImageViewNoDataError ( "No image found" )
Get the data value at the given position . Indices are zero - based as in Numpy .
61
20
24,852
def get_pixel_distance ( self , x1 , y1 , x2 , y2 ) : dx = abs ( x2 - x1 ) dy = abs ( y2 - y1 ) dist = np . sqrt ( dx * dx + dy * dy ) dist = np . round ( dist ) return dist
Calculate distance between the given pixel positions .
67
10
24,853
def _sanity_check_scale ( self , scale_x , scale_y ) : win_wd , win_ht = self . get_window_size ( ) if ( win_wd <= 0 ) or ( win_ht <= 0 ) : raise ImageViewError ( "window size undefined" ) # final sanity check on resulting output image size if ( win_wd * scale_x < 1 ) or ( win_ht * scale_y < 1 ) : raise ValueError ( "resulting scale (%f, %f) would result in image size of " "<1 in width or height" % ( scale_x , scale_y ) ) sx = float ( win_wd ) / scale_x sy = float ( win_ht ) / scale_y if ( sx < 1.0 ) or ( sy < 1.0 ) : raise ValueError ( "resulting scale (%f, %f) would result in pixel size " "approaching window size" % ( scale_x , scale_y ) )
Do a sanity check on the proposed scale vs . window size . Raises an exception if there will be a problem .
218
24
24,854
def scale_cb ( self , setting , value ) : zoomlevel = self . zoom . calc_level ( value ) self . t_ . set ( zoomlevel = zoomlevel ) self . redraw ( whence = 0 )
Handle callback related to image scaling .
47
7
24,855
def set_scale_base_xy ( self , scale_x_base , scale_y_base ) : self . t_ . set ( scale_x_base = scale_x_base , scale_y_base = scale_y_base )
Set stretch factors .
55
4
24,856
def get_scale_text ( self ) : scalefactor = self . get_scale_max ( ) if scalefactor >= 1.0 : text = '%.2fx' % ( scalefactor ) else : text = '1/%.2fx' % ( 1.0 / scalefactor ) return text
Report current scaling in human - readable format .
68
9
24,857
def set_zoom_algorithm ( self , name ) : name = name . lower ( ) alg_names = list ( zoom . get_zoom_alg_names ( ) ) if name not in alg_names : raise ImageViewError ( "Alg '%s' must be one of: %s" % ( name , ', ' . join ( alg_names ) ) ) self . t_ . set ( zoom_algorithm = name )
Set zoom algorithm .
100
4
24,858
def zoomsetting_change_cb ( self , setting , value ) : alg_name = self . t_ [ 'zoom_algorithm' ] self . zoom = zoom . get_zoom_alg ( alg_name ) ( self ) self . zoom_to ( self . get_zoom ( ) )
Handle callback related to changes in zoom .
69
8
24,859
def interpolation_change_cb ( self , setting , value ) : canvas_img = self . get_canvas_image ( ) canvas_img . interpolation = value canvas_img . reset_optimize ( ) self . redraw ( whence = 0 )
Handle callback related to changes in interpolation .
56
9
24,860
def set_scale_limits ( self , scale_min , scale_max ) : # TODO: force scale to within limits if already outside? self . t_ . set ( scale_min = scale_min , scale_max = scale_max )
Set scale limits .
54
4
24,861
def enable_autozoom ( self , option ) : option = option . lower ( ) assert ( option in self . autozoom_options ) , ImageViewError ( "Bad autozoom option '%s': must be one of %s" % ( str ( self . autozoom_options ) ) ) self . t_ . set ( autozoom = option )
Set autozoom behavior .
80
6
24,862
def set_pan ( self , pan_x , pan_y , coord = 'data' , no_reset = False ) : pan_pos = ( pan_x , pan_y ) with self . suppress_redraw : self . t_ . set ( pan = pan_pos , pan_coord = coord ) self . _reset_bbox ( ) # If user specified "override" or "once" for auto center, then turn off # auto center now that they have set the pan manually if ( not no_reset ) and ( self . t_ [ 'autocenter' ] in ( 'override' , 'once' ) ) : self . t_ . set ( autocenter = 'off' )
Set pan position .
155
4
24,863
def pan_cb ( self , setting , value ) : pan_x , pan_y = value [ : 2 ] self . logger . debug ( "pan set to %.2f,%.2f" % ( pan_x , pan_y ) ) self . redraw ( whence = 0 )
Handle callback related to changes in pan .
64
8
24,864
def get_pan ( self , coord = 'data' ) : pan_x , pan_y = self . t_ [ 'pan' ] [ : 2 ] if coord == 'wcs' : if self . t_ [ 'pan_coord' ] == 'data' : image = self . get_image ( ) if image is not None : try : return image . pixtoradec ( pan_x , pan_y ) except Exception as e : pass # <-- data already in coordinates form return ( pan_x , pan_y ) # <-- requesting data coords if self . t_ [ 'pan_coord' ] == 'data' : return ( pan_x , pan_y ) image = self . get_image ( ) if image is not None : try : return image . radectopix ( pan_x , pan_y ) except Exception as e : pass return ( pan_x , pan_y )
Get pan positions .
200
4
24,865
def center_image ( self , no_reset = True ) : try : xy_mn , xy_mx = self . get_limits ( ) data_x = float ( xy_mn [ 0 ] + xy_mx [ 0 ] ) / 2.0 data_y = float ( xy_mn [ 1 ] + xy_mx [ 1 ] ) / 2.0 except ImageViewNoDataError : # No data, so try to get center of any plotted objects canvas = self . get_canvas ( ) try : data_x , data_y = canvas . get_center_pt ( ) [ : 2 ] except Exception as e : self . logger . error ( "Can't compute center point: %s" % ( str ( e ) ) ) return self . panset_xy ( data_x , data_y , no_reset = no_reset ) if self . t_ [ 'autocenter' ] == 'once' : self . t_ . set ( autocenter = 'off' )
Pan to the center of the image .
223
8
24,866
def enable_autocenter ( self , option ) : option = option . lower ( ) assert ( option in self . autocenter_options ) , ImageViewError ( "Bad autocenter option '%s': must be one of %s" % ( str ( self . autocenter_options ) ) ) self . t_ . set ( autocenter = option )
Set autocenter behavior .
80
6
24,867
def cut_levels ( self , loval , hival , no_reset = False ) : self . t_ . set ( cuts = ( loval , hival ) ) # If user specified "override" or "once" for auto levels, # then turn off auto levels now that they have set the levels # manually if ( not no_reset ) and ( self . t_ [ 'autocuts' ] in ( 'once' , 'override' ) ) : self . t_ . set ( autocuts = 'off' )
Apply cut levels on the image view .
116
8
24,868
def auto_levels ( self , autocuts = None ) : if autocuts is None : autocuts = self . autocuts image = self . get_image ( ) if image is None : return loval , hival = autocuts . calc_cut_levels ( image ) # this will invoke cut_levels_cb() self . t_ . set ( cuts = ( loval , hival ) ) # If user specified "once" for auto levels, then turn off # auto levels now that we have cut levels established if self . t_ [ 'autocuts' ] == 'once' : self . t_ . set ( autocuts = 'off' )
Apply auto - cut levels on the image view .
146
10
24,869
def auto_levels_cb ( self , setting , value ) : # Did we change the method? method = self . t_ [ 'autocut_method' ] params = self . t_ . get ( 'autocut_params' , [ ] ) params = dict ( params ) if method != str ( self . autocuts ) : ac_class = AutoCuts . get_autocuts ( method ) self . autocuts = ac_class ( self . logger , * * params ) else : self . autocuts . update_params ( * * params ) # Redo the auto levels #if self.t_['autocuts'] != 'off': # NOTE: users seems to expect that when the auto cuts parameters # are changed that the cuts should be immediately recalculated self . auto_levels ( )
Handle callback related to changes in auto - cut levels .
176
11
24,870
def enable_autocuts ( self , option ) : option = option . lower ( ) assert ( option in self . autocuts_options ) , ImageViewError ( "Bad autocuts option '%s': must be one of %s" % ( str ( self . autocuts_options ) ) ) self . t_ . set ( autocuts = option )
Set autocuts behavior .
80
6
24,871
def set_autocut_params ( self , method , * * params ) : self . logger . debug ( "Setting autocut params method=%s params=%s" % ( method , str ( params ) ) ) params = list ( params . items ( ) ) self . t_ . set ( autocut_method = method , autocut_params = params )
Set auto - cut parameters .
82
6
24,872
def transform ( self , flip_x , flip_y , swap_xy ) : self . logger . debug ( "flip_x=%s flip_y=%s swap_xy=%s" % ( flip_x , flip_y , swap_xy ) ) with self . suppress_redraw : self . t_ . set ( flip_x = flip_x , flip_y = flip_y , swap_xy = swap_xy )
Transform view of the image .
99
6
24,873
def transform_cb ( self , setting , value ) : self . make_callback ( 'transform' ) # whence=0 because need to calculate new extents for proper # cutout for rotation (TODO: always make extents consider # room for rotation) whence = 0 self . redraw ( whence = whence )
Handle callback related to changes in transformations .
67
8
24,874
def copy_attributes ( self , dst_fi , attrlist , share = False ) : # TODO: change API to just go with settings names? keylist = [ ] if 'transforms' in attrlist : keylist . extend ( [ 'flip_x' , 'flip_y' , 'swap_xy' ] ) if 'rotation' in attrlist : keylist . extend ( [ 'rot_deg' ] ) if 'autocuts' in attrlist : keylist . extend ( [ 'autocut_method' , 'autocut_params' ] ) if 'cutlevels' in attrlist : keylist . extend ( [ 'cuts' ] ) if 'rgbmap' in attrlist : keylist . extend ( [ 'color_algorithm' , 'color_hashsize' , 'color_map' , 'intensity_map' , 'color_array' , 'shift_array' ] ) if 'zoom' in attrlist : keylist . extend ( [ 'scale' ] ) if 'pan' in attrlist : keylist . extend ( [ 'pan' ] ) with dst_fi . suppress_redraw : if share : self . t_ . share_settings ( dst_fi . get_settings ( ) , keylist = keylist ) else : self . t_ . copy_settings ( dst_fi . get_settings ( ) , keylist = keylist ) dst_fi . redraw ( whence = 0 )
Copy interesting attributes of our configuration to another image view .
328
11
24,875
def auto_orient ( self ) : image = self . get_image ( ) if image is None : return invert_y = not isinstance ( image , AstroImage . AstroImage ) # Check for various things to set based on metadata header = image . get_header ( ) if header : # Auto-orientation orient = header . get ( 'Orientation' , None ) if orient is None : orient = header . get ( 'Image Orientation' , None ) if orient is not None : self . logger . debug ( "orientation [%s]" % orient ) try : orient = int ( str ( orient ) ) self . logger . info ( "setting orientation from metadata [%d]" % ( orient ) ) flip_x , flip_y , swap_xy = self . orient_map [ orient ] self . transform ( flip_x , flip_y , swap_xy ) invert_y = False except Exception as e : # problems figuring out orientation--let it be self . logger . error ( "orientation error: %s" % str ( e ) ) if invert_y : flip_x , flip_y , swap_xy = self . get_transforms ( ) #flip_y = not flip_y flip_y = True self . transform ( flip_x , flip_y , swap_xy )
Set the orientation for the image to a reasonable default .
286
11
24,876
def get_image_as_buffer ( self , output = None ) : obuf = output if obuf is None : obuf = BytesIO ( ) arr8 = self . get_image_as_array ( ) if not hasattr ( arr8 , 'tobytes' ) : # older versions of numpy obuf . write ( arr8 . tostring ( order = 'C' ) ) else : obuf . write ( arr8 . tobytes ( order = 'C' ) ) ## if output is not None: ## return None return obuf
Get the current image shown in the viewer with any overlaid graphics in a IO buffer with channels as needed and ordered by the back end widget .
120
29
24,877
def get_rgb_image_as_bytes ( self , format = 'png' , quality = 90 ) : obuf = self . get_rgb_image_as_buffer ( format = format , quality = quality ) return bytes ( obuf . getvalue ( ) )
Get the current image shown in the viewer with any overlaid graphics in the form of a buffer in the form of bytes .
60
25
24,878
def save_rgb_image_as_file ( self , filepath , format = 'png' , quality = 90 ) : with open ( filepath , 'wb' ) as out_f : self . get_rgb_image_as_buffer ( output = out_f , format = format , quality = quality ) self . logger . debug ( "wrote %s file '%s'" % ( format , filepath ) )
Save the current image shown in the viewer with any overlaid graphics in a file with the specified format and quality . This can be overridden by subclasses .
93
32
24,879
def set_onscreen_message ( self , text , redraw = True ) : width , height = self . get_window_size ( ) font = self . t_ . get ( 'onscreen_font' , 'sans serif' ) font_size = self . t_ . get ( 'onscreen_font_size' , None ) if font_size is None : font_size = self . _calc_font_size ( width ) # TODO: need some way to accurately estimate text extents # without actually putting text on the canvas ht , wd = font_size , font_size if text is not None : wd = len ( text ) * font_size * 1.1 x = ( width // 2 ) - ( wd // 2 ) y = ( ( height // 3 ) * 2 ) - ( ht // 2 ) tag = '_$onscreen_msg' canvas = self . get_private_canvas ( ) try : message = canvas . get_object_by_tag ( tag ) if text is None : message . text = '' else : message . x = x message . y = y message . text = text message . fontsize = font_size except KeyError : if text is None : text = '' Text = canvas . get_draw_class ( 'text' ) canvas . add ( Text ( x , y , text = text , font = font , fontsize = font_size , color = self . img_fg , coord = 'window' ) , tag = tag , redraw = False ) if redraw : canvas . update_canvas ( whence = 3 )
Called by a subclass to update the onscreen message .
349
12
24,880
def _calc_font_size ( self , win_wd ) : font_size = 4 if win_wd >= 1600 : font_size = 24 elif win_wd >= 1000 : font_size = 18 elif win_wd >= 800 : font_size = 16 elif win_wd >= 600 : font_size = 14 elif win_wd >= 500 : font_size = 12 elif win_wd >= 400 : font_size = 11 elif win_wd >= 300 : font_size = 10 elif win_wd >= 250 : font_size = 8 elif win_wd >= 200 : font_size = 6 return font_size
Heuristic to calculate an appropriate font size based on the width of the viewer window .
141
17
24,881
def popup ( self , title , callfn , initialdir = None , filename = None ) : self . cb = callfn self . filew . set_title ( title ) if initialdir : self . filew . set_current_folder ( initialdir ) if filename : #self.filew.set_filename(filename) self . filew . set_current_name ( filename ) self . filew . show ( )
Let user select and load file .
92
7
24,882
def get_fileinfo ( self , filespec , dldir = None ) : if dldir is None : dldir = self . tmpdir # Get information about this file/URL info = iohelper . get_fileinfo ( filespec , cache_dir = dldir )
Break down a file specification into its components .
63
9
24,883
def zoomset_cb ( self , setting , zoomlevel , fitsimage ) : if not self . gui_up : return fac_x , fac_y = fitsimage . get_scale_base_xy ( ) fac_x_me , fac_y_me = self . zoomimage . get_scale_base_xy ( ) if ( fac_x != fac_x_me ) or ( fac_y != fac_y_me ) : alg = fitsimage . get_zoom_algorithm ( ) self . zoomimage . set_zoom_algorithm ( alg ) self . zoomimage . set_scale_base_xy ( fac_x , fac_y ) return self . _zoomset ( self . fitsimage_focus , zoomlevel )
This method is called when a main FITS widget changes zoom level .
167
14
24,884
def set_amount_cb ( self , widget , val ) : self . zoom_amount = val zoomlevel = self . fitsimage_focus . get_zoom ( ) self . _zoomset ( self . fitsimage_focus , zoomlevel )
This method is called when Zoom Amount control is adjusted .
54
11
24,885
def _slice ( self , view ) : if self . _data is not None : return self . _data [ view ] return self . _proxy . get_view ( self . id , view )
Send view to remote server and do slicing there .
42
10
24,886
def build_gui ( self , container ) : top = Widgets . VBox ( ) top . set_border_width ( 4 ) # this is a little trick for making plugins that work either in # a vertical or horizontal orientation. It returns a box container, # a scroll widget and an orientation ('vertical', 'horizontal') vbox , sw , orientation = Widgets . get_oriented_box ( container ) vbox . set_border_width ( 4 ) vbox . set_spacing ( 2 ) # Take a text widget to show some instructions self . msg_font = self . fv . get_font ( "sans" , 12 ) tw = Widgets . TextArea ( wrap = True , editable = False ) tw . set_font ( self . msg_font ) self . tw = tw # Frame for instructions and add the text widget with another # blank widget to stretch as needed to fill emp fr = Widgets . Frame ( "Status" ) fr . set_widget ( tw ) vbox . add_widget ( fr , stretch = 0 ) # Add a spacer to stretch the rest of the way to the end of the # plugin space spacer = Widgets . Label ( '' ) vbox . add_widget ( spacer , stretch = 1 ) # scroll bars will allow lots of content to be accessed top . add_widget ( sw , stretch = 1 ) # A button box that is always visible at the bottom btns = Widgets . HBox ( ) btns . set_spacing ( 3 ) # Add a close button for the convenience of the user btn = Widgets . Button ( "Close" ) btn . add_callback ( 'activated' , lambda w : self . close ( ) ) btns . add_widget ( btn , stretch = 0 ) btns . add_widget ( Widgets . Label ( '' ) , stretch = 1 ) top . add_widget ( btns , stretch = 0 ) # Add our GUI to the container container . add_widget ( top , stretch = 1 ) # NOTE: if you are building a GUI using a specific widget toolkit # (e.g. Qt) GUI calls, you need to extract the widget or layout # from the non-toolkit specific container wrapper and call on that # to pack your widget, e.g.: #cw = container.get_widget() #cw.addWidget(widget, stretch=1) self . gui_up = True
This method is called when the plugin is invoked . It builds the GUI used by the plugin into the widget layout passed as container . This method could be called several times if the plugin is opened and closed . The method may be omitted if there is no GUI for the plugin .
527
55
24,887
def focus_cb ( self , viewer , channel ) : chname = channel . name if self . active != chname : # focus has shifted to a different channel than our idea # of the active one self . active = chname self . set_info ( "Focus is now in channel '%s'" % ( self . active ) ) return True
Callback from the reference viewer shell when the focus changes between channels .
73
13
24,888
def redo ( self , channel , image ) : chname = channel . name # Only update our GUI if the activity is in the focused # channel if self . active == chname : imname = image . get ( 'name' , 'NONAME' ) self . set_info ( "A new image '%s' has been added to channel %s" % ( imname , chname ) ) return True
Called from the reference viewer shell when a new image has been added to a channel .
89
18
24,889
def _main ( ) : usage = "usage: %prog [options] cmd [arg] ..." optprs = OptionParser ( usage = usage , version = version ) optprs . add_option ( "--debug" , dest = "debug" , default = False , action = "store_true" , help = "Enter the pdb debugger on main()" ) optprs . add_option ( "--host" , dest = "host" , metavar = "HOST" , default = "localhost" , help = "Connect to server at HOST" ) optprs . add_option ( "--port" , dest = "port" , type = "int" , default = 9000 , metavar = "PORT" , help = "Connect to server at PORT" ) optprs . add_option ( "--profile" , dest = "profile" , action = "store_true" , default = False , help = "Run the profiler on main()" ) ( options , args ) = optprs . parse_args ( sys . argv [ 1 : ] ) # Are we debugging this? if options . debug : import pdb pdb . run ( 'main(options, args)' ) # Are we profiling this? elif options . profile : import profile print ( "%s profile:" % sys . argv [ 0 ] ) profile . run ( 'main(options, args)' ) else : main ( options , args )
Run from command line .
316
5
24,890
def _imload ( self , filepath , kwds ) : start_time = time . time ( ) typ , enc = mimetypes . guess_type ( filepath ) if not typ : typ = 'image/jpeg' typ , subtyp = typ . split ( '/' ) self . logger . debug ( "MIME type is %s/%s" % ( typ , subtyp ) ) data_loaded = False if have_opencv and subtyp not in [ 'gif' ] : # First choice is OpenCv, because it supports high-bit depth # multiband images means = 'opencv' data_np = cv2 . imread ( filepath , cv2 . IMREAD_ANYDEPTH + cv2 . IMREAD_ANYCOLOR ) if data_np is not None : data_loaded = True # funky indexing because opencv returns BGR images, # whereas PIL and others return RGB if len ( data_np . shape ) >= 3 and data_np . shape [ 2 ] >= 3 : data_np = data_np [ ... , : : - 1 ] # OpenCv doesn't "do" image metadata, so we punt to piexif # library (if installed) self . piexif_getexif ( filepath , kwds ) # OpenCv added a feature to do auto-orientation when loading # (see https://github.com/opencv/opencv/issues/4344) # So reset these values to prevent auto-orientation from # happening later kwds [ 'Orientation' ] = 1 kwds [ 'Image Orientation' ] = 1 # convert to working color profile, if can if self . clr_mgr . can_profile ( ) : data_np = self . clr_mgr . profile_to_working_numpy ( data_np , kwds ) if not data_loaded and have_pil : means = 'PIL' image = PILimage . open ( filepath ) try : if hasattr ( image , '_getexif' ) : info = image . _getexif ( ) if info is not None : for tag , value in info . items ( ) : kwd = TAGS . get ( tag , tag ) kwds [ kwd ] = value elif have_exif : self . piexif_getexif ( image . info [ "exif" ] , kwds ) else : self . logger . warning ( "Please install 'piexif' module to get image metadata" ) except Exception as e : self . logger . warning ( "Failed to get image metadata: %s" % ( str ( e ) ) ) # convert to working color profile, if can if self . clr_mgr . can_profile ( ) : image = self . clr_mgr . profile_to_working_pil ( image , kwds ) # convert from PIL to numpy data_np = np . array ( image ) if data_np is not None : data_loaded = True if ( not data_loaded and ( typ == 'image' ) and ( subtyp in ( 'x-portable-pixmap' , 'x-portable-greymap' ) ) ) : # Special opener for PPM files, preserves high bit depth means = 'built-in' data_np = open_ppm ( filepath ) if data_np is not None : data_loaded = True if not data_loaded : raise ImageError ( "No way to load image format '%s/%s'" % ( typ , subtyp ) ) end_time = time . time ( ) self . logger . debug ( "loading (%s) time %.4f sec" % ( means , end_time - start_time ) ) return data_np
Load an image file guessing the format and return a numpy array containing an RGB image . If EXIF keywords can be read they are returned in the dict _kwds_ .
829
36
24,891
def imresize ( self , data , new_wd , new_ht , method = 'bilinear' ) : old_ht , old_wd = data . shape [ : 2 ] start_time = time . time ( ) if have_pilutil : means = 'PIL' zoom_x = float ( new_wd ) / float ( old_wd ) zoom_y = float ( new_ht ) / float ( old_ht ) if ( old_wd >= new_wd ) or ( old_ht >= new_ht ) : # data size is bigger, skip pixels zoom = max ( zoom_x , zoom_y ) else : zoom = min ( zoom_x , zoom_y ) newdata = imresize ( data , zoom , interp = method ) else : raise ImageError ( "No way to scale image smoothly" ) end_time = time . time ( ) self . logger . debug ( "scaling (%s) time %.4f sec" % ( means , end_time - start_time ) ) return newdata
Scale an image in numpy array _data_ to the specified width and height . A smooth scaling is preferred .
227
23
24,892
def get_array ( self , order , dtype = None ) : if dtype is None : dtype = self . rgbarr . dtype order = order . upper ( ) if order == self . order : return self . rgbarr . astype ( dtype , copy = False ) res = trcalc . reorder_image ( order , self . rgbarr , self . order ) res = res . astype ( dtype , copy = False , casting = 'unsafe' ) return res
Get Numpy array that represents the RGB layers .
106
10
24,893
def set_cmap ( self , cmap , callback = True ) : self . cmap = cmap with self . suppress_changed : self . calc_cmap ( ) # TEMP: ignore passed callback parameter # callback=False in the following because we don't want to # recursively invoke set_cmap() self . t_ . set ( color_map = cmap . name , callback = False )
Set the color map used by this RGBMapper .
89
11
24,894
def set_imap ( self , imap , callback = True ) : self . imap = imap self . calc_imap ( ) with self . suppress_changed : # TEMP: ignore passed callback parameter self . recalc ( ) # callback=False in the following because we don't want to # recursively invoke set_imap() self . t_ . set ( intensity_map = imap . name , callback = False )
Set the intensity map used by this RGBMapper .
95
11
24,895
def stretch ( self , scale_factor , callback = True ) : self . scale_pct *= scale_factor self . scale_and_shift ( self . scale_pct , 0.0 , callback = callback )
Stretch the color map via altering the shift map .
48
10
24,896
def _set_reference_channel_cb ( self , w , idx ) : chname = self . chnames [ idx ] self . _set_reference_channel ( chname )
This is the GUI callback for the control that sets the reference channel .
41
14
24,897
def set_reference_channel ( self , chname ) : # change the GUI control to match idx = self . chnames . index ( str ( chname ) ) self . w . ref_channel . set_index ( idx ) return self . _set_reference_channel ( chname )
This is the API call to set the reference channel .
64
11
24,898
def zoomset_cb ( self , setting , value , chviewer , info ) : return self . zoomset ( chviewer , info . chinfo )
This callback is called when a channel window is zoomed .
34
12
24,899
def rotset_cb ( self , setting , value , chviewer , info ) : return self . rotset ( chviewer , info . chinfo )
This callback is called when a channel window is rotated .
36
11