rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
t = time.clock()
|
def parse_stream(self, stream): t = time.clock() self._setup_handlers() self._parser = expat.ParserCreate() self._parser.StartElementHandler = self._start_element_handler self._parser.EndElementHandler = self._end_element_handler self._stream = stream self._progress = util.ProgressFactory("Loading XML...", self._stream_length) try: try: self._parser.ParseFile(stream) except expat.ExpatError, e: raise finally: self._progress.kill() self._remove_handlers() self._parser.StartElementHandler = None self._parser.EndElementHandler = None del self._parser print "Time:", time.clock() - t return self
|
|
print "Time:", time.clock() - t
|
def parse_stream(self, stream): t = time.clock() self._setup_handlers() self._parser = expat.ParserCreate() self._parser.StartElementHandler = self._start_element_handler self._parser.EndElementHandler = self._end_element_handler self._stream = stream self._progress = util.ProgressFactory("Loading XML...", self._stream_length) try: try: self._parser.ParseFile(stream) except expat.ExpatError, e: raise finally: self._progress.kill() self._remove_handlers() self._parser.StartElementHandler = None self._parser.EndElementHandler = None del self._parser print "Time:", time.clock() - t return self
|
|
Py_DECREF(list);
|
[[def switch(layer, args)]] switch(get_image_combination([[images[layer].pyname]])) { [[for type in images[layer].pixel_types]] [[exec current = '*((' + type + '*)' + images[layer].name + ')']] case [[type.upper()]]: [[if layer == len(images) - 1]] [[if not function.return_type is None]] return_value = [[end]] [[function.__name__]] ( [[exec tmp_args = args + [current] ]] [[exec arg_string = tmp_args[0] ]] [[exec if len(function.args.list) > 0: arg_string += ', ']] [[exec current_image = 1]] [[for i in range(len(function.args.list))]] [[if isinstance(function.args.list[i], ImageType)]] [[exec arg_string += tmp_args[current_image] ]] [[exec current_image += 1]] [[else]]
|
|
k.load_settings("c:/Documents and Settings/Karl MacMillan/Desktop/default.xml") generate_features_list(glyphs, k.feature_functions) forest = distance.unique_distances(glyphs)
|
forest = k.unique_distances(glyphs)
|
def create_graph(glyphs, ratio): import gamera.knn k = gamera.knn.kNN() k.load_settings("c:/Documents and Settings/Karl MacMillan/Desktop/default.xml") generate_features_list(glyphs, k.feature_functions) forest = distance.unique_distances(glyphs) #forest = create_forest(glyphs) num_nodes = len(glyphs) next = 1 g = Graph() for i in range(len(glyphs)): glyphs[i].visited = 0 g.add_node(glyphs[i]) glyphs[i].cluster_name = str(i) g.add_edge(forest[0][1], forest[0][2], forest[0][0]) progress = util.ProgressFactory("Creating graph . . . ", num_nodes - 1) try: for i in range(num_nodes - 1): while(1): if g.add_edge(forest[next][1], forest[next][2], forest[next][0]): next += 1 else: next += 1 break progress.step() #print detect_cycle(g, g.keys()[0]) #check_connected(g) total_cost = 0.0 counted_edges = { } finally: progress.kill() print g.edges c = make_subtrees_stddev(g, ratio) return c
|
import traceback traceback.print_stack()
|
def _init_gamera(): import traceback traceback.print_stack() global _gamera_initialised if _gamera_initialised: return _gamera_initialised = True import plugin, gamera_xml, sys # Create the default functions for the menupl for method in ( plugin.PluginFactory( "load_image", "File", plugin.ImageType(ALL, "image"), plugin.ImageType(ALL), plugin.Args([plugin.FileOpen("filename")])), plugin.PluginFactory( "display", "Displaying", None, plugin.ImageType(ALL), None), plugin.PluginFactory( "display_ccs", "Displaying", None, plugin.ImageType([ONEBIT]), None), plugin.PluginFactory( "display_false_color", "Displaying", None, plugin.ImageType([GREYSCALE, FLOAT]), None), plugin.PluginFactory( "classify_manual", "Classification", None, plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])), plugin.PluginFactory( "classify_heuristic", "Classification", None, plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])), plugin.PluginFactory( "classify_automatic", "Classification", None, plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])), plugin.PluginFactory( "unclassify", "Classification", None, plugin.ImageType([ONEBIT]), None), plugin.PluginFactory( "to_xml", "XML", plugin.String('xml'), plugin.ImageType([ONEBIT]), None), plugin.PluginFactory( "to_xml_filename", "XML", None, plugin.ImageType([ONEBIT]), plugin.Args([ plugin.FileSave("filename", extension=gamera_xml.extensions)])) ): method.register() paths.import_directory(paths.plugins, globals(), locals(), 1) sys.path.append(".")
|
|
unions = []
|
def _pregroup(self, glyphs, function): from gamera import graph G = graph.Undirected() G.add_nodes(glyphs) progress = util.ProgressFactory("Pre-grouping glyphs...", len(glyphs)) try: equivalencies = {} group_no = 0 for i in range(len(glyphs)): gi = glyphs[i] for j in range(i + 1, len(glyphs)): gj = glyphs[j] if function(gi, gj): G.add_edge(gi, gj) progress.step() finally: progress.kill() return G
|
|
self.unions.append(union) union.properties.root_number = self.root_number
|
def _evaluate_subgroup(self, subgroup): import image_utilities if len(subgroup) > 1: union = image_utilities.union_images(subgroup) self.unions.append(union) ### union.properties.root_number = self.root_number ### classification = self.guess_glyph_automatic(union) classification_name = classification[0][1] if (classification_name.startswith("_split") or classification_name.startswith("skip")): return 0 else: return classification[0][0] classification = subgroup[0].id_name[0] if classification[1].startswith('_group._part'): return 0 return classification[0]
|
|
return 0
|
return 0.0
|
def _evaluate_subgroup(self, subgroup): import image_utilities if len(subgroup) > 1: union = image_utilities.union_images(subgroup) self.unions.append(union) ### union.properties.root_number = self.root_number ### classification = self.guess_glyph_automatic(union) classification_name = classification[0][1] if (classification_name.startswith("_split") or classification_name.startswith("skip")): return 0 else: return classification[0][0] classification = subgroup[0].id_name[0] if classification[1].startswith('_group._part'): return 0 return classification[0]
|
self.root_number = 0
|
def _find_group_unions(self, G, evaluate_function, max_parts_per_group=5): self.root_number = 0 ### import image_utilities progress = util.ProgressFactory("Grouping glyphs...", G.nsubgraphs) try: found_unions = [] for root in G.get_subgraph_roots(): self.root_number += 1 ### best_grouping = G.optimize_partitions( root, evaluate_function, max_parts_per_group) for subgroup in best_grouping: if len(subgroup) > 1: union = image_utilities.union_images(subgroup) found_unions.append(union) classification = self.guess_glyph_automatic(union) union.classify_heuristic(classification) part_name = "_group._part." + classification[0][1] for glyph in subgroup: glyph.classify_heuristic(part_name) progress.step() finally: progress.kill() print "Number of groups created: %d" % len(found_unions) return found_unions
|
|
self.root_number += 1
|
def _find_group_unions(self, G, evaluate_function, max_parts_per_group=5): self.root_number = 0 ### import image_utilities progress = util.ProgressFactory("Grouping glyphs...", G.nsubgraphs) try: found_unions = [] for root in G.get_subgraph_roots(): self.root_number += 1 ### best_grouping = G.optimize_partitions( root, evaluate_function, max_parts_per_group) for subgroup in best_grouping: if len(subgroup) > 1: union = image_utilities.union_images(subgroup) found_unions.append(union) classification = self.guess_glyph_automatic(union) union.classify_heuristic(classification) part_name = "_group._part." + classification[0][1] for glyph in subgroup: glyph.classify_heuristic(part_name) progress.step() finally: progress.kill() print "Number of groups created: %d" % len(found_unions) return found_unions
|
|
classification_state = image.classification_state
|
def Draw(self, grid, attr, dc, rect, row, col, isSelected): dc.BeginDrawing() dc.SetOptimization(True) view_start = grid.GetViewStart() view_units = grid.GetScrollPixelsPerUnit() view_size = grid.GetClientSize() if not rect.Intersects(wxRect( view_start[0] * view_units[0], view_start[1] * view_units[1], view_size[0], view_size[1])): return
|
|
version = [int(x) for x in docutils.__version__.split(".")]
|
version = tuple([int(x) for x in docutils.__version__.split(".")])
|
def do_docstring(obj, name): doc_string = inspect.getdoc(obj) if doc_string is None: text = "[Not documented]\n\n" else: text = doc_string + "\n\n" content = docutils.statemachine.string2lines(text, convert_whitespace=1) if not options.has_key('no_title'): title_text = "``%s``" % name textnodes, messages = state.inline_text(title_text, lineno) titles = [docutils.nodes.title(title_text, '', *textnodes)] + messages node = docutils.nodes.section(text, *titles) version = [int(x) for x in docutils.__version__.split(".")] if version >= (0, 3, 9): node['names'] = [name] # docutils 0.3.9 way else: node['name'] = name # docutils 0.3.7 way state_machine.document.note_implicit_target(node) else: node = docutils.nodes.paragraph(text) content = docutils.statemachine.StringList(initlist=content, parent=node) state.nested_parse(content, content_offset, node) return node
|
return unicodedata.lookup(id_name)
|
return unicodedata.lookup(name)
|
def name_lookup_unicode(id_name): name = id_name.replace(".", " ") name = name.upper() try: return unicodedata.lookup(id_name) except KeyError: print "ERROR: Name not found:", id_name return ""
|
print "ERROR: Name not found:", id_name
|
print "ERROR: Name not found:", name
|
def name_lookup_unicode(id_name): name = id_name.replace(".", " ") name = name.upper() try: return unicodedata.lookup(id_name) except KeyError: print "ERROR: Name not found:", id_name return ""
|
if (%(pysymbol)s_seq)
|
if (%(pysymbol)s_seq == NULL)
|
def from_python(self): return """ const char* type_error_%(name)s = "Argument '%(name)s' must be an iterable of images."; PyObject* %(pysymbol)s_seq = PySequence_Fast(%(pysymbol)s, type_error_%(name)s); if (%(pysymbol)s_seq) return 0; int %(symbol)s_size = PySequence_Fast_GET_SIZE(%(pysymbol)s_seq); %(symbol)s.resize(%(symbol)s_size); for (int i=0; i < %(symbol)s_size; ++i) { PyObject *element = PySequence_Fast_GET_ITEM(%(pysymbol)s_seq, i); if (!is_ImageObject(element)) { PyErr_SetString(PyExc_TypeError, type_error_%(name)s); return 0; } %(symbol)s[i] = std::pair<Image*, int>((Image*)(((RectObject*)element)->m_x), get_image_combination(element)); image_get_fv(element, &%(symbol)s[i].first->features, &%(symbol)s[i].first->features_len); } Py_DECREF(%(pysymbol)s_seq);""" % self
|
self._classifier.get_feature_functions()[0]]
|
ImageBase.get_feature_functions()[0]]
|
def _OnChangeSetOfFeatures(self, event): all_features = [x[0] for x in ImageBase.methods_flat_category("Features", ONEBIT)] all_features.sort() existing_features = [x[0] for x in self._classifier.get_feature_functions()[0]] feature_controls = [] for x in all_features: feature_controls.append( Check('', x, default=(x in existing_features))) dialog = Args( feature_controls, name='Feature selection', title='Select the features you want to use for classification') result = dialog.show(self._frame) if result is None: return selected_features = [name for check, name in zip(result, all_features) if check] self._classifier.change_feature_set(selected_features)
|
return Rect(int(o.ul_y - amount), int(o.ul_x - amount), int(o.nrows + amount * 2), int(o.ncols + amount * 2))
|
return Rect(Point(int(o.ul_x-amount), int(o.ul_y - amount)), Dim(int(o.ncols + amount * 2), int(o.nrows + amount * 2)))
|
def Fudge(o, amount = FUDGE_AMOUNT): # For rectangles, just return a new rectangle that is slightly larger if isinstance(o, Rect): return Rect(int(o.ul_y - amount), int(o.ul_x - amount), int(o.nrows + amount * 2), int(o.ncols + amount * 2)) # For integers, return one of our "fudge number proxies" elif isinstance(o, int): return FudgeInt(o, amount) elif isinstance(o, float): return FudgeFloat(o, amount)
|
font.SetPointSize(14)
|
pass
|
def __init__(self, toplevel, parent = None, id = -1, size = wxDefaultSize): self.toplevel = toplevel MultiImageWindow.__init__(self, parent, id, size)
|
self.titlebar_button = wxButton(self, -1, "+", size=(16, 16))
|
self.titlebar_button = wxButton(self, -1, "+")
|
def __init__(self, toplevel, parent = None, id = -1, size = wxDefaultSize): self.toplevel = toplevel MultiImageWindow.__init__(self, parent, id, size)
|
lc.right.SameAs(self, wxRight, 0)
|
lc.right.SameAs(self.titlebar_button, wxLeft, 0)
|
def __init__(self, toplevel, parent = None, id = -1, size = wxDefaultSize): self.toplevel = toplevel MultiImageWindow.__init__(self, parent, id, size)
|
lc.height.AsIs() lc.width.AsIs()
|
lc.height.SameAs(self.titlebar, wxHeight, 0) lc.width.SameAs(self.titlebar, wxHeight, 0)
|
def __init__(self, toplevel, parent = None, id = -1, size = wxDefaultSize): self.toplevel = toplevel MultiImageWindow.__init__(self, parent, id, size)
|
if gui_util.are_you_sure_dialog(self._frame,
|
if gui_util.are_you_sure_dialog(
|
def _OnClearClassifierCollection(self, event): if self._classifier.is_dirty: if gui_util.are_you_sure_dialog(self._frame, "Are you sure you want to clear all glyphs in the classifier?"): self._classifier.clear_glyphs() else: self._classifier.clear_glyphs() self._classifier.is_dirty = False
|
"Are you sure you want to quit without saving?", self._frame):
|
"Are you sure you want to quit without saving?"):
|
def _OnCloseWindow(self, event): if self.is_dirty: if not gui_util.are_you_sure_dialog( "Are you sure you want to quit without saving?", self._frame): event.Veto() return self._classifier.set_display(None) self.multi_iw.Destroy() self.single_iw.Destroy() self.splitterhr1.Destroy() self.splitterhr0.Destroy() self.splitterhl.Destroy() self.splitterv.Destroy() self._frame.Destroy() del self._frame
|
self.text = wxTextCtrl(self, txID, style=wxTE_PROCESS_ENTER)
|
self.text = wxTextCtrl(self, txID, style=wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB)
|
def __init__(self, symbol_table, toplevel, parent = None, id = -1): wxPanel.__init__( self, parent, id, style=wxWANTS_CHARS|wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) self.toplevel = toplevel self._symbol_table = symbol_table self.SetAutoLayout(true) self.box = wxBoxSizer(wxVERTICAL) txID = NewId() self.text = wxTextCtrl(self, txID, style=wxTE_PROCESS_ENTER) EVT_KEY_DOWN(self.text, self._OnKey) EVT_TEXT(self, txID, self._OnText) # On win32, the enter key is only caught by the EVT_TEXT_ENTER # On GTK, the enter key is sent directly to EVT_KEY_DOWN if platform == 'win32': EVT_TEXT_ENTER(self, txID, self._OnEnter) EVT_TEXT_TAB(self, txID, self._OnTab) self.box.Add(self.text, 0, wxEXPAND|wxBOTTOM, 5) tID = NewId() self.tree = SymbolTreeCtrl(self, self, tID, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS | wxTR_DEFAULT_STYLE) self.box.Add(self.tree, 1, wxEXPAND|wxALL) self.box.RecalcSizes() self.SetSizer(self.box)
|
EVT_TEXT_TAB(self, txID, self._OnTab)
|
def __init__(self, symbol_table, toplevel, parent = None, id = -1): wxPanel.__init__( self, parent, id, style=wxWANTS_CHARS|wxCLIP_CHILDREN|wxNO_FULL_REPAINT_ON_RESIZE) self.toplevel = toplevel self._symbol_table = symbol_table self.SetAutoLayout(true) self.box = wxBoxSizer(wxVERTICAL) txID = NewId() self.text = wxTextCtrl(self, txID, style=wxTE_PROCESS_ENTER) EVT_KEY_DOWN(self.text, self._OnKey) EVT_TEXT(self, txID, self._OnText) # On win32, the enter key is only caught by the EVT_TEXT_ENTER # On GTK, the enter key is sent directly to EVT_KEY_DOWN if platform == 'win32': EVT_TEXT_ENTER(self, txID, self._OnEnter) EVT_TEXT_TAB(self, txID, self._OnTab) self.box.Add(self.text, 0, wxEXPAND|wxBOTTOM, 5) tID = NewId() self.tree = SymbolTreeCtrl(self, self, tID, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS | wxTR_DEFAULT_STYLE) self.box.Add(self.tree, 1, wxEXPAND|wxALL) self.box.RecalcSizes() self.SetSizer(self.box)
|
|
def _OnTab(self, evt):
|
def _OnKey(self, evt): find = self.text.GetValue() if evt.KeyCode() == WXK_TAB:
|
def _OnTab(self, evt): find = self._symbol_table.autocomplete(find) self.text.SetValue(find) self.text.SetInsertionPointEnd()
|
def _OnKey(self, evt): find = self.text.GetValue() if evt.KeyCode() == WXK_TAB: self._OnTab(evt)
|
def _OnTab(self, evt): find = self._symbol_table.autocomplete(find) self.text.SetValue(find) self.text.SetInsertionPointEnd()
|
|
pkg = os.path.join(self.dist_dir, name + ".pkg") if os.path.exists(pkg): remove_tree(pkg)
|
def run (self): name = self.distribution.metadata.name version = self.distribution.metadata.version description = self.distribution.metadata.description self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.warn_dir = 0 log.info("installing to %s" % self.bdist_dir) self.run_command('install')
|
|
log.info("Building %s.pkg..." % name) pm = buildpkg.PackageMaker(name, version, description)
|
log.info("Building %s.pkg..." % fullname) pm = buildpkg.PackageMaker(fullname, version, description)
|
def run (self): name = self.distribution.metadata.name version = self.distribution.metadata.version description = self.distribution.metadata.description self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.warn_dir = 0 log.info("installing to %s" % self.bdist_dir) self.run_command('install')
|
readmes = ['README', 'readme.txt', 'LICENSE', 'ACKNOWLEDGEMENTS'] for readme in readmes: if os.path.exists(readme): copy_file(readme, pkg_dir)
|
def run (self): name = self.distribution.metadata.name version = self.distribution.metadata.version description = self.distribution.metadata.description self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.warn_dir = 0 log.info("installing to %s" % self.bdist_dir) self.run_command('install')
|
|
removals = [os.path.join(self.dist_dir, name + ".dmg"), os.path.join(self.dist_dir, "_%s.dmg" % name)]
|
removals = [os.path.join(self.dist_dir, fullname + ".dmg"), os.path.join(self.dist_dir, "_%s.dmg" % fullname)]
|
def run (self): name = self.distribution.metadata.name version = self.distribution.metadata.version description = self.distribution.metadata.description self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.warn_dir = 0 log.info("installing to %s" % self.bdist_dir) self.run_command('install')
|
log.info("Making %s.dmg..." % name) makedmg.make_dmg(pkg_dir, self.dist_dir, name)
|
log.info("Making %s.dmg..." % fullname) makedmg.make_dmg(pkg_dir, self.dist_dir, fullname)
|
def run (self): name = self.distribution.metadata.name version = self.distribution.metadata.version description = self.distribution.metadata.description self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.warn_dir = 0 log.info("installing to %s" % self.bdist_dir) self.run_command('install')
|
if wxIsBusy():
|
while wxIsBusy():
|
def OnBrowse(self, event): parent = self.text.GetParent() filename = gui_util.open_file_dialog(parent, self.extension) if filename: self.text.SetValue(filename) parent.Raise() if wxIsBusy(): wxEndBusyCursor()
|
if wxIsBusy():
|
while wxIsBusy():
|
def OnBrowse(self, event): parent = self.text.GetParent() filename = gui_util.save_file_dialog(parent, self.extension) if filename: self.text.SetValue(filename) parent.Raise() if wxIsBusy(): wxEndBusyCursor()
|
if wxIsBusy():
|
while wxIsBusy():
|
def OnBrowse(self, event): parent = self.text.GetParent() filename = gui_util.directory_dialog(self.text) if filename: self.text.SetValue(filename) parent.Raise() if wxIsBusy(): wxEndBusyCursor()
|
for x in self._members_for_menu
|
for x in _members_for_menu
|
def members_for_menu(self): return ["%s: %s" % (x, getattr(self, x)) for x in self._members_for_menu if hasattr(self, x)]
|
evaluate_function = _Classifier._evaluate_subgroup
|
evaluate_function = self._evaluate_subgroup
|
def group_list_automatic(self, glyphs, grouping_function=None, evaluate_function=None): if len(glyphs) == 0: return glyphs = [x for x in glyphs if x.classification_state != 3] splits, removed = self.classify_list_automatic(glyphs) glyphs = [x for x in glyphs if not x.get_main_id().startswith('split')] if grouping_function is None: grouping_function = _Classifier._default_grouping_function G = self._pregroup(glyphs, grouping_function) if evaluate_function is None: evaluate_function = _Classifier._evaluate_subgroup found_unions = self._find_group_unions(G, evaluate_function) return found_unions + splits, removed
|
def _evaluate_subgroup(subgroup):
|
def _evaluate_subgroup(self, subgroup):
|
def _evaluate_subgroup(subgroup): import image_utilities if len(subgroup) > 1: union = image_utilities.union_images(subgroup) classification = self.guess_glyph_automatic(union) if (classification[0][1].startswith("split") or classification[0][1].startswith("skip")): return 0 else: return classification[0][0] return subgroup[0].id_name[0][0]
|
_evaulate_subgroup = staticmethod(_evaluate_subgroup)
|
def _evaluate_subgroup(subgroup): import image_utilities if len(subgroup) > 1: union = image_utilities.union_images(subgroup) classification = self.guess_glyph_automatic(union) if (classification[0][1].startswith("split") or classification[0][1].startswith("skip")): return 0 else: return classification[0][0] return subgroup[0].id_name[0][0]
|
|
self.GetGridWindow().GetParent().Layout()
|
def resize_grid(self, do_auto_size=1): if not self.created: return wxBeginBusyCursor() self.BeginBatch() try: orig_rows = self.rows rows = int(max(ceil(float(len(self.list) - 1) / float(GRID_NCOLS)), 1)) cols = GRID_NCOLS self.DeleteRows(0, self.rows) self.AppendRows(rows) self.rows = rows self.cols = cols row_size = 1 for row in range(rows - 1, -1, -1): for col in range(cols): self.SetCellRenderer(row, col, self.GetDefaultRenderer()) self.SetReadOnly(row, col, TRUE) width = self.set_labels() self.SetRowLabelSize(width + 20) self.SetColLabelSize(20) self.AutoSize() finally: self.EndBatch() self.GetGridWindow().GetParent().Layout() wxEndBusyCursor()
|
|
to_rle, from_rle]
|
to_rle, from_rle, iterate_black_horizontal_runs, iterate_black_vertical_runs, iterate_white_horizontal_runs, iterate_white_vertical_runs]
|
def __call__(self, length): warnings.warn("Use filter_wide_black_runs instead of filter_wide_runs.", DeprecationWarning) return _runlength.filter_wide_black_runs(self, length)
|
def add_highlight_cc(self, cc): self._iw.id.add_highlight_cc(cc)
|
def add_highlight_cc(self, cc, color): self._iw.id.add_highlight_cc(cc, color)
|
def add_highlight_cc(self, cc): self._iw.id.add_highlight_cc(cc)
|
font.SetPointSize(14)
|
if wxPlatform == '__WXMSW__': font.SetPointSize(10) else: font.SetPointSize(14)
|
def __init__(self, toplevel, parent = None, id = -1, size = wxDefaultSize): self.toplevel = toplevel MultiImageWindow.__init__(self, parent, id, size)
|
def _SaveClassifierCollection(self, filename): try: self._classifier.to_xml_filename(filename) except gamera_xml.XMLError, e: gui_util.message("Saving classifier glyphs: " + str(e)) def _OnClearClassifierCollection(self, event): if self._classifier.is_dirty: if gui_util.are_you_sure_dialog(self._frame, "Are you sure you want to clear all glyphs in the classifier?"): self._classifier.clear_glyphs() else: self._classifier.clear_glyphs() self._classifier.is_dirty = False def _OnOpenEditorCollection(self, event): if self.multi_iw.id.is_dirty: if not gui_util.are_you_sure_dialog("Editor glyphs have not been saved and will be replaced.\nAre you sure you want to load glyphs into the classifier?"): return filenames = gui_util.open_file_dialog(self._frame, gamera_xml.extensions, multiple=1) if not filenames is None: if len(filenames) == 1: self.editor_collection_filename = filenames[0] else: self.editor_collection_filename = None self._OpenEditorCollection(filenames) def _OpenEditorCollection(self, filenames): try: glyphs = gamera_xml.LoadXML().parse_filename(filenames[0]).glyphs if len(filenames) > 1: for f in filenames[1:]: glyphs.extend(gamera_xml.LoadXML().parse_filename(f).glyphs) except gamera_xml.XMLError, e: gui_util.message("Opening editor glyphs: " + str(e)) return self.set_multi_image(glyphs) self.multi_iw.id.is_dirty = False def _OnMergeEditorCollection(self, event): filenames = gui_util.open_file_dialog(self._frame, gamera_xml.extensions, multiple=1) if not filenames is None: glyphs = [] try: for f in filenames: glyphs.extend(gamera_xml.LoadXML().parse_filename(f).glyphs) except gamera_xml.XMLError, e: gui_util.message("Merging editor glyphs: " + str(e)) return self.multi_iw.id.append_glyphs(glyphs) def _OnSaveEditorCollection(self, event): if self.editor_collection_filename == None: self._OnSaveEditorCollectionAs(event) else: glyphs = self.multi_iw.id.GetAllItems() if gui_util.are_you_sure_dialog("There are %d glyphs in the editor.\nAre you sure you want to save?" % len(glyphs)): self._SaveEditorCollection(self.editor_collection_filename) def _OnSaveEditorCollectionAs(self, event): glyphs = self.multi_iw.id.GetAllItems() if gui_util.are_you_sure_dialog("There are %d glyphs in the editor.\nAre you sure you want to save?" % len(glyphs)): filename = gui_util.save_file_dialog(self._frame, gamera_xml.extensions) if filename: self.editor_collection_filename = filename self._SaveEditorCollection(self.editor_collection_filename) def _SaveEditorCollection(self, filename, force=False): glyphs = self.multi_iw.id.GetAllItems() self._classifier.generate_features(glyphs) try: gamera_xml.WriteXMLFile( glyphs=glyphs, symbol_table=self._symbol_table).write_filename( filename) except gamera_xml.XMLError, e: gui_util.message("Saving editor glyphs: " + str(e)) def _OnSaveSelectedGlyphsAs(self, event): filename = gui_util.save_file_dialog(self._frame, gamera_xml.extensions) if filename: glyphs = self.multi_iw.id.GetSelectedItems() self._classifier.generate_features(glyphs) try: gamera_xml.WriteXMLFile( glyphs=glyphs, symbol_table=self._symbol_table).write_filename( filename) except gamera_xml.XMLError, e: gui_util.message("Saving selected glyphs: " + str(e)) def _OnImportSymbolTable(self, event): filename = gui_util.open_file_dialog(self._frame, gamera_xml.extensions) if filename: self._ImportSymbolTable(filename) def _ImportSymbolTable(self, filename): wxBeginBusyCursor() try: try: symbol_table = gamera_xml.LoadXML( parts=['symbol_table']).parse_filename(filename).symbol_table except gamera_xml.XMLError, e: gui_util.message("Importing symbol table: " + str(e)) return for symbol in symbol_table.symbols.keys(): self._symbol_table.add(symbol) finally: wxEndBusyCursor() def _OnExportSymbolTable(self, event): filename = gui_util.save_file_dialog(self._frame, gamera_xml.extensions) if filename: self._ExportSymbolTable(filename) def _ExportSymbolTable(self, filename): wxBeginBusyCursor() try: try: gamera_xml.WriteXMLFile( symbol_table=self._symbol_table).write_filename(filename) except gamera_xml.XMLError, e: gui_util.message("Exporting symbol table: " + str(e)) finally: wxEndBusyCursor()
|
def _OnGenerateClassifierStats(self, event): from gamera import classifier_stats all_stats = [(x.title, x) for x in classifier_stats.all_stat_pages] all_stats.sort() stats_controls = [Check('', x[0], default=True) for x in all_stats] stats_controls.append(Directory('Stats directory')) dialog = Args( stats_controls, name='Select statistics', title='Select the statistics to generate and the directory to save them to.\n(Experimental feature).') result = dialog.show(self._frame) if result is None or result[-1] is None: return pages = [] for on, (name, page) in zip(result, all_stats): if on: pages.append(page) wxBeginBusyCursor() try: classifier_stats.make_stat_pages(self._classifier, result[-1], pages) except Exception, e: wxEndBusyCursor() gui_util.message(e) else: wxEndBusyCursor()
|
|
else len(args) == 2:
|
elif len(args) == 2:
|
def __call__(self, *args): if len(args) == 5: return _draw.draw_hollow_rect(self, *args) elif len(args) == 3: try: a = args[0] b = args[1] value = args[2] return _draw.draw_hollow_rect(self, a.y, a.x, b.y, b.x, value) except KeyError, AttributeError: pass else len(args) == 2: try: a = args[0] value = args[1] return _draw.draw_hollow_rect(self, a.ul_y, a.ul_x, a.lr_y, a.lr_x, value) except KeyError, AttributeError: pass raise ValueError("Arguments are incorrect.")
|
**draw_filled_rect** (Point(*x1*, *y1*), Point(*x2*, *y2))
|
**draw_filled_rect** (Point(*x1*, *y1*), Point(*x2*, *y2*))
|
def __doc_example1__(images): from random import randint from gamera.core import Image image = Image(0, 0, 100, 100, RGB, DENSE) for i in range(10): image.draw_hollow_rect(randint(0, 100), randint(0, 100), randint(0, 100), randint(0, 100), RGBPixel(randint(0, 255), randint(0,255), randint(0, 255))) return image
|
else len(args) == 2:
|
elif len(args) == 2:
|
def __call__(self, *args): if len(args) == 5: return _draw.draw_filled_rect(self, *args) elif len(args) == 3: try: a = args[0] b = args[1] value = args[2] return _draw.draw_filled_rect(self, a.y, a.x, b.y, b.x, value) except KeyError, AttributeError: pass else len(args) == 2: try: a = args[0] value = args[1] return _draw.draw_hollow_rect(self, a.ul_y, a.ul_x, a.lr_y, a.lr_x, value) except KeyError, AttributeError: pass raise ValueError("Arguments are incorrect.")
|
*accuracy*:
|
*accuracy* = ``0.1``:
|
def __doc_example1__(images): from random import randint from gamera.core import Image image = Image(0, 0, 100, 100, RGB, DENSE) for i in range(10): image.draw_filled_rect(randint(0, 100), randint(0, 100), randint(0, 100), randint(0, 100), RGBPixel(randint(0, 255), randint(0,255), randint(0, 255))) return image
|
print self.database
|
def change_feature_set(self, features): self.is_dirty = True if len(self.database): print self.database self.feature_functions = iter(self.database).next().get_feature_functions(features) self.generate_features(self.database) self.instantiate_from_images(self.database)
|
|
print name
|
def magic_import(name, globals_={}, locals_={}, fromlist=[]): if fromlist != None and "core" in fromlist: fromlist = list(fromlist) fromlist.remove("core") if (name[0] == '_' and name[1] != "_" and name != "_winreg") or name == "core" or name == "gamera.core": print name return None else: return std_import(name, globals_, locals_, fromlist)
|
|
printf(\"Could not load gamera.py - falling back to gameracore\n\");
|
printf(\"Could not load gamera.py - falling back to gameracore\\n\");
|
[[def switch(layer, args)]] switch(get_image_combination([[images[layer].name]], cc_type)) { [[for type in images[layer].pixel_types]] [[exec current = '*((' + type + '*)((RectObject*)' + images[layer].name + ')->m_x)']] case [[type.upper()]]: [[if layer == len(images) - 1]] [[if function.return_type != None]] return_value = [[end]] [[function.__class__.__name__]] ( [[exec tmp_args = args + [current] ]] [[exec arg_string = tmp_args[0] ]] [[exec if len(function.args.list) > 0: arg_string += ', ']] [[exec current_image = 1]] [[for i in range(len(function.args.list))]] [[if isinstance(function.args.list[i], ImageType)]] [[exec arg_string += tmp_args[current_image] ]] [[exec current_image += 1]] [[else]] [[exec arg_string += function.args.list[i].name + '_arg']] [[end]] [[if i < len(function.args.list) - 1]] [[exec arg_string += ', ']] [[end]] [[end]] [[arg_string]]
|
PyErr_SetString(PyExc_RuntimeError, \"Unable to load gameracore.\");
|
PyErr_SetString(PyExc_RuntimeError, \"Unable to load gameracore.\\n\");
|
[[def switch(layer, args)]] switch(get_image_combination([[images[layer].name]], cc_type)) { [[for type in images[layer].pixel_types]] [[exec current = '*((' + type + '*)((RectObject*)' + images[layer].name + ')->m_x)']] case [[type.upper()]]: [[if layer == len(images) - 1]] [[if function.return_type != None]] return_value = [[end]] [[function.__class__.__name__]] ( [[exec tmp_args = args + [current] ]] [[exec arg_string = tmp_args[0] ]] [[exec if len(function.args.list) > 0: arg_string += ', ']] [[exec current_image = 1]] [[for i in range(len(function.args.list))]] [[if isinstance(function.args.list[i], ImageType)]] [[exec arg_string += tmp_args[current_image] ]] [[exec current_image += 1]] [[else]] [[exec arg_string += function.args.list[i].name + '_arg']] [[end]] [[if i < len(function.args.list) - 1]] [[exec arg_string += ', ']] [[end]] [[end]] [[arg_string]]
|
PyErr_SetString(PyExc_RuntimeError, \"Unable to get module dictionary\");
|
PyErr_SetString(PyExc_RuntimeError, \"Unable to get module dictionary\\n\");
|
[[def switch(layer, args)]] switch(get_image_combination([[images[layer].name]], cc_type)) { [[for type in images[layer].pixel_types]] [[exec current = '*((' + type + '*)((RectObject*)' + images[layer].name + ')->m_x)']] case [[type.upper()]]: [[if layer == len(images) - 1]] [[if function.return_type != None]] return_value = [[end]] [[function.__class__.__name__]] ( [[exec tmp_args = args + [current] ]] [[exec arg_string = tmp_args[0] ]] [[exec if len(function.args.list) > 0: arg_string += ', ']] [[exec current_image = 1]] [[for i in range(len(function.args.list))]] [[if isinstance(function.args.list[i], ImageType)]] [[exec arg_string += tmp_args[current_image] ]] [[exec current_image += 1]] [[else]] [[exec arg_string += function.args.list[i].name + '_arg']] [[end]] [[if i < len(function.args.list) - 1]] [[exec arg_string += ', ']] [[end]] [[end]] [[arg_string]]
|
output_file.write('\n') output_file.close()
|
[[def switch(layer, args)]] switch(get_image_combination([[images[layer].name]], cc_type)) { [[for type in images[layer].pixel_types]] [[exec current = '*((' + type + '*)((RectObject*)' + images[layer].name + ')->m_x)']] case [[type.upper()]]: [[if layer == len(images) - 1]] [[if function.return_type != None]] return_value = [[end]] [[function.__class__.__name__]] ( [[exec tmp_args = args + [current] ]] [[exec arg_string = tmp_args[0] ]] [[exec if len(function.args.list) > 0: arg_string += ', ']] [[exec current_image = 1]] [[for i in range(len(function.args.list))]] [[if isinstance(function.args.list[i], ImageType)]] [[exec arg_string += tmp_args[current_image] ]] [[exec current_image += 1]] [[else]] [[exec arg_string += function.args.list[i].name + '_arg']] [[end]] [[if i < len(function.args.list) - 1]] [[exec arg_string += ', ']] [[end]] [[end]] [[arg_string]]
|
|
[[
|
def restore_import(): global std_import __builtins__['__import__'] = std_import
|
|
return 0;\
|
return 0;
|
#ifndef _MSC_VER void init[[module_name]](void);
|
return Cc(self, *args, **kwargs)
|
return Cc(self, self.label, *args, **kwargs)
|
def subimage(self, *args, **kwargs): """Creates a new view that is part of an existing image.
|
self.class_names.sort(lambda x, y: cmp(x.lower(), y.lower()))
|
self.class_names.sort(lambda x, y: cmp(x[0].lower(), y[0].lower()))
|
def table_of_contents(self, classes): s = open(os.path.join(self.docgen.src_path, "classes.txt"), "w") s.write("=======\nClasses\n=======\n\n") s.write("Alphabetical\n-------------\n") self.class_names.sort(lambda x, y: cmp(x.lower(), y.lower())) letter = '~' first = True links = [] for name, combined_name in self.class_names: if name[0].upper() != letter: letter = name[0].upper() s.write("\n\n**") s.write(letter) s.write("**\n\n") first = True if not first: s.write(", ") s.write("%s_ (%s)" % (name, combined_name)) first = False links.append(".. _%s: %s.html" % (name, combined_name)) s.write("\n\n") s.write("\n".join(links)) s.close()
|
return 1 return 0
|
return True return False
|
def has_id_name(self, name): for confidence, id_name in self.id_name: if name == id_name: return 1 return 0
|
cls.last_directory, "", extensions, self._flags)
|
cls.last_directory, "", str(extensions), self._flags)
|
def __init__(self, parent, extensions="*.*", multiple=0): cls = self.__class__ if cls.last_directory is None: cls.last_directory = config.get("default_dir") self._flags = False if multiple: self._flags |= wxMULTIPLE self._multiple = True else: self._multiple = False wxFileDialog.__init__( self, parent, "Choose a file", cls.last_directory, "", extensions, self._flags) self.extensions = extensions
|
tmp_dc = wxMemoryDC()
|
def Draw(self, grid, attr, dc, rect, row, col, isSelected): view_start = grid.GetViewStart() view_units = grid.GetScrollPixelsPerUnit() view_size = grid.GetClientSize() if not rect.Intersects(wxRect( view_start[0] * view_units[0], view_start[1] * view_units[1], view_size[0], view_size[1])): return
|
|
try: color = self._colors[classification_state] except KeyError: color = wxColor(200, 200, 200)
|
color = self._colors[classification_state]
|
def Draw(self, grid, attr, dc, rect, row, col, isSelected): view_start = grid.GetViewStart() view_units = grid.GetScrollPixelsPerUnit() view_size = grid.GetClientSize() if not rect.Intersects(wxRect( view_start[0] * view_units[0], view_start[1] * view_units[1], view_size[0], view_size[1])): return
|
x = int(rect.x + (rect.width - width) / 2) y = int(rect.y + (rect.height - height) / 2)
|
x = rect.x + (rect.width - width) / 2 y = rect.y + (rect.height - height) / 2
|
def Draw(self, grid, attr, dc, rect, row, col, isSelected): view_start = grid.GetViewStart() view_units = grid.GetScrollPixelsPerUnit() view_size = grid.GetClientSize() if not rect.Intersects(wxRect( view_start[0] * view_units[0], view_start[1] * view_units[1], view_size[0], view_size[1])): return
|
bmp = wxBitmapFromImage(wx_image)
|
bmp = wx_image.ConvertToBitmap()
|
def Draw(self, grid, attr, dc, rect, row, col, isSelected): view_start = grid.GetViewStart() view_units = grid.GetScrollPixelsPerUnit() view_size = grid.GetClientSize() if not rect.Intersects(wxRect( view_start[0] * view_units[0], view_start[1] * view_units[1], view_size[0], view_size[1])): return
|
tmp_dc = wxMemoryDC()
|
def Draw(self, grid, attr, dc, rect, row, col, isSelected): view_start = grid.GetViewStart() view_units = grid.GetScrollPixelsPerUnit() view_size = grid.GetClientSize() if not rect.Intersects(wxRect( view_start[0] * view_units[0], view_start[1] * view_units[1], view_size[0], view_size[1])): return
|
|
self._flags = False
|
def __init__(self, parent, extensions="*.*", multiple=0): cls = self.__class__ if cls.last_directory is None: cls.last_directory = config.get("default_dir") self._flags = False if multiple: self._flags |= wxMULTIPLE self._multiple = True else: self._multiple = False wxFileDialog.__init__( self, parent, "Choose a file", cls.last_directory, "", str(extensions), self._flags) self.extensions = extensions
|
|
subimage = self.image.subimage(y, x, h, w)
|
subimage = self.image.subimage(int(y), int(x), int(h), int(w))
|
def PaintArea(self, x, y, w, h, check=1, dc=None): if not self.image: return if dc == None: dc = wxClientDC(self) self.draw_rubber(dc) redraw_rubber = 1 else: redraw_rubber = 0 # This needs to be created every time we call Paint, since its # address can (but in practice usually doesn't) change. tmpdc = wxMemoryDC()
|
node['name'] = name state_machine.document.note_implicit_target(node, node)
|
version = [int(x) for x in docutils.__version__.split(".")] if version >= (0, 3, 9): node['names'] = [name] else: node['name'] = name state_machine.document.note_implicit_target(node)
|
def do_docstring(obj, name): doc_string = inspect.getdoc(obj) if doc_string is None: text = "[Not documented]\n\n" else: text = doc_string + "\n\n" content = docutils.statemachine.string2lines(text, convert_whitespace=1) if not options.has_key('no_title'): title_text = "``%s``" % name textnodes, messages = state.inline_text(title_text, lineno) titles = [docutils.nodes.title(title_text, '', *textnodes)] + messages node = docutils.nodes.section(text, *titles) node['name'] = name state_machine.document.note_implicit_target(node, node) else: node = docutils.nodes.paragraph(text) content = docutils.statemachine.StringList(initlist=content, parent=node) state.nested_parse(content, 0, node) return node
|
state.nested_parse(content, 0, node)
|
state.nested_parse(content, content_offset, node)
|
def do_docstring(obj, name): doc_string = inspect.getdoc(obj) if doc_string is None: text = "[Not documented]\n\n" else: text = doc_string + "\n\n" content = docutils.statemachine.string2lines(text, convert_whitespace=1) if not options.has_key('no_title'): title_text = "``%s``" % name textnodes, messages = state.inline_text(title_text, lineno) titles = [docutils.nodes.title(title_text, '', *textnodes)] + messages node = docutils.nodes.section(text, *titles) node['name'] = name state_machine.document.note_implicit_target(node, node) else: node = docutils.nodes.paragraph(text) content = docutils.statemachine.StringList(initlist=content, parent=node) state.nested_parse(content, 0, node) return node
|
y1, x1, y2, x1, value = args
|
y1, x1, y2, x2, value = args
|
def __call__(self, *args): if len(args) == 3: return _draw.draw_filled_rect(self, *args) elif len(args) == 2: try: a, value = args return _draw.draw_filled_rect(self, a.ul, a.lr, value) except KeyError, AttributeError: pass elif len(args) == 5: try: y1, x1, y2, x1, value = args result = _draw.draw_filled_rect(self, (x1, y1), (x2, y2), value) warn_deprecated("""draw_filled_rect(y1, x1, y2, x2, value) is deprecated.
|
origin = self.GetViewStart()
|
origin = [x * self.scroll_amount for x in self.GetViewStart()]
|
def focus(self, subimages): scroll_amount = self.scroll_amount if not util.is_sequence(subimages): subimages = (subimages,) x1 = y1 = maxint x2 = y2 = 0 # Get a combined rectangle of all images in the list for image in subimages: x1 = min(image.page_offset_x(), x1) y1 = min(image.page_offset_y(), y1) x2 = max(image.page_offset_x() + image.ncols, x2) y2 = max(image.page_offset_y() + image.nrows, y2) # Adjust for the scaling factor x1 = x1 * self.scaling y1 = y1 * self.scaling x2 = x2 * self.scaling y2 = y2 * self.scaling origin = self.GetViewStart() maxwidth = self.image.width * self.scaling maxheight = self.image.height * self.scaling need_to_scroll = 0 if (x1 < origin[0] or x2 > origin[0] + self.GetSize().x / self.scaling): set_x = max(0, min(maxwidth - self.GetSize()[0] / self.scaling, x1 - 25)) need_to_scroll = 1 else: set_x = origin[0] if (y1 < origin[1] or y2 > origin[1] + self.GetSize().y / self.scaling or need_to_scroll): set_y = max(0, min(maxheight - self.GetSize()[1] / self.scaling, y1 - 25)) need_to_scroll = 1 else: set_y = origin[1] if need_to_scroll or self.scaling > 1: self.SetScrollbars(scroll_amount, scroll_amount, floor(maxwidth / scroll_amount), floor(maxheight / scroll_amount), set_x, set_y) self.Refresh(0, rect=wxRect(0,0,self.GetSize().x,self.GetSize().y))
|
scale = self.scaling
|
scale = scaling
|
def scale(self, scale=None): scroll_amount = self.scroll_amount if scale == None: scale = self.scaling w = self.width * scale - 1 h = self.height * scale - 1 x = max(min(self.GetViewStart()[0] * scale / self.scaling + 1, w - self.GetSize().x) - 2, 0) y = max(min(self.GetViewStart()[1] * scale / self.scaling + 1, h - self.GetSize().y) - 2, 0) self.scaling = scale self.SetScrollbars(scroll_amount, scroll_amount, floor(w / scroll_amount), floor(h / scroll_amount), x, y) self.Refresh(0, rect=wxRect(0, 0, self.GetSize().x, self.GetSize().y))
|
x = max(min(self.GetViewStart()[0] * scale / self.scaling + 1,
|
origin = [x * self.scroll_amount for x in self.GetViewStart()] x = max(min(origin[0] * scale / scaling + 1,
|
def scale(self, scale=None): scroll_amount = self.scroll_amount if scale == None: scale = self.scaling w = self.width * scale - 1 h = self.height * scale - 1 x = max(min(self.GetViewStart()[0] * scale / self.scaling + 1, w - self.GetSize().x) - 2, 0) y = max(min(self.GetViewStart()[1] * scale / self.scaling + 1, h - self.GetSize().y) - 2, 0) self.scaling = scale self.SetScrollbars(scroll_amount, scroll_amount, floor(w / scroll_amount), floor(h / scroll_amount), x, y) self.Refresh(0, rect=wxRect(0, 0, self.GetSize().x, self.GetSize().y))
|
y = max(min(self.GetViewStart()[1] * scale / self.scaling + 1,
|
y = max(min(origin[1] * scale / scaling + 1,
|
def scale(self, scale=None): scroll_amount = self.scroll_amount if scale == None: scale = self.scaling w = self.width * scale - 1 h = self.height * scale - 1 x = max(min(self.GetViewStart()[0] * scale / self.scaling + 1, w - self.GetSize().x) - 2, 0) y = max(min(self.GetViewStart()[1] * scale / self.scaling + 1, h - self.GetSize().y) - 2, 0) self.scaling = scale self.SetScrollbars(scroll_amount, scroll_amount, floor(w / scroll_amount), floor(h / scroll_amount), x, y) self.Refresh(0, rect=wxRect(0, 0, self.GetSize().x, self.GetSize().y))
|
x, y)
|
floor(x / scroll_amount), floor(y / scroll_amount)) self.Clear()
|
def scale(self, scale=None): scroll_amount = self.scroll_amount if scale == None: scale = self.scaling w = self.width * scale - 1 h = self.height * scale - 1 x = max(min(self.GetViewStart()[0] * scale / self.scaling + 1, w - self.GetSize().x) - 2, 0) y = max(min(self.GetViewStart()[1] * scale / self.scaling + 1, h - self.GetSize().y) - 2, 0) self.scaling = scale self.SetScrollbars(scroll_amount, scroll_amount, floor(w / scroll_amount), floor(h / scroll_amount), x, y) self.Refresh(0, rect=wxRect(0, 0, self.GetSize().x, self.GetSize().y))
|
if hasattr(sys, 'winver'): def OnPaint(self, event): origin = [x * self.scroll_amount for x in self.GetViewStart()] if self.image: self.BeginDrawing() update_regions = self.GetUpdateRegion() rects = wxRegionIterator(update_regions) while rects.HaveRects(): ox = rects.GetX() / self.scaling oy = rects.GetY() / self.scaling x = (rects.GetX() + origin[0]) / self.scaling y = (rects.GetY() + origin[1]) / self.scaling if x > self.width or y > self.height: pass else: w = (max(min(int((rects.GetW() / self.scaling)), self.width - ox), 0)) h = (max(min(int((rects.GetH() / self.scaling)), self.height - oy), 0)) self.PaintArea(x, y, w, h, check=0) rects.Next() self.draw_rubber() self.EndDrawing() else: def OnPaint(self, event): if not self.image: return origin = [x * self.scroll_amount for x in self.GetViewStart()] origin_scaled = [x / self.scaling for x in origin] update_regions = self.GetUpdateRegion() rects = wxRegionIterator(update_regions) while rects.HaveRects(): ox = rects.GetX() / self.scaling oy = rects.GetY() / self.scaling x = ox + origin_scaled[0] y = oy + origin_scaled[1] if x > self.width or y > self.height: pass else: fudge = int(self.scaling / 2.0) w = (max(min(int((rects.GetW() / self.scaling) + fudge), self.width - ox), 0)) h = (max(min(int((rects.GetH() / self.scaling) + fudge), self.height - oy), 0)) self.PaintArea(x, y, w, h, check=0) rects.Next() self.draw_rubber()
|
def OnPaint(self, event): if not self.image: return scaling = self.scaling origin = [x * self.scroll_amount for x in self.GetViewStart()] origin_scaled = [x / scaling for x in origin] update_regions = self.GetUpdateRegion() rects = wxRegionIterator(update_regions) while rects.HaveRects(): ox = rects.GetX() / scaling oy = rects.GetY() / scaling x = ox + origin_scaled[0] y = oy + origin_scaled[1] if x > self.width or y > self.height: pass else: fudge = int(self.scaling / 2.0) w = (max(min(int((rects.GetW() / scaling) + fudge), self.width - ox), 0)) h = (max(min(int((rects.GetH() / scaling) + fudge), self.height - oy), 0)) self.PaintArea(x, y, w, h, check=0) rects.Next() self.draw_rubber()
|
def OnResize(self, event): size = self.GetSize() self.tmpDC.SelectObject(wxEmptyBitmap( size.GetWidth(), size.GetHeight())) self.tmpDC.SetPen(wxTRANSPARENT_PEN) event.Skip() self.scale()
|
origin_scaled = [a / self.scaling for a in origin] size_scaled = [a / self.scaling for a in self.GetSizeTuple()]
|
origin_scaled = [a / scaling for a in origin] size_scaled = [a / scaling for a in self.GetSizeTuple()]
|
def PaintArea(self, x, y, w, h, check=1): dc = wxPaintDC(self) dc.SetLogicalFunction(wxCOPY) origin = [a * self.scroll_amount for a in self.GetViewStart()] origin_scaled = [a / self.scaling for a in origin] size_scaled = [a / self.scaling for a in self.GetSizeTuple()] if check: if ((x + w < origin_scaled[0]) and (y + h < origin_scaled[1]) or (x > origin_scaled[0] + size_scaled[0] and y > origin_scaled[1] + size_scaled[1]) or (w == 0 or h == 0)): return self.tmpDC.SetUserScale(self.scaling, self.scaling) if (y + h > self.image.nrows): h = self.image.nrows - y - 2 if (x + w > self.image.ncols): w = self.image.ncols - x - 2 subimage = SubImage(self.image, y, x, h + 1, w + 1) image = wxEmptyImage(w + 1, h + 1) apply(self.to_string_function, (subimage, image.GetDataBuffer())) bmp = wxBitmapFromImage(image) self.tmpDC.DrawBitmap(bmp, 0, 0, 0)
|
self.tmpDC.SetUserScale(self.scaling, self.scaling) if (y + h > self.image.nrows):
|
self.tmpDC.SetUserScale(scaling, scaling) if (y + h >= self.height):
|
def PaintArea(self, x, y, w, h, check=1): dc = wxPaintDC(self) dc.SetLogicalFunction(wxCOPY) origin = [a * self.scroll_amount for a in self.GetViewStart()] origin_scaled = [a / self.scaling for a in origin] size_scaled = [a / self.scaling for a in self.GetSizeTuple()] if check: if ((x + w < origin_scaled[0]) and (y + h < origin_scaled[1]) or (x > origin_scaled[0] + size_scaled[0] and y > origin_scaled[1] + size_scaled[1]) or (w == 0 or h == 0)): return self.tmpDC.SetUserScale(self.scaling, self.scaling) if (y + h > self.image.nrows): h = self.image.nrows - y - 2 if (x + w > self.image.ncols): w = self.image.ncols - x - 2 subimage = SubImage(self.image, y, x, h + 1, w + 1) image = wxEmptyImage(w + 1, h + 1) apply(self.to_string_function, (subimage, image.GetDataBuffer())) bmp = wxBitmapFromImage(image) self.tmpDC.DrawBitmap(bmp, 0, 0, 0)
|
if (x + w > self.image.ncols):
|
if (x + w >= self.width):
|
def PaintArea(self, x, y, w, h, check=1): dc = wxPaintDC(self) dc.SetLogicalFunction(wxCOPY) origin = [a * self.scroll_amount for a in self.GetViewStart()] origin_scaled = [a / self.scaling for a in origin] size_scaled = [a / self.scaling for a in self.GetSizeTuple()] if check: if ((x + w < origin_scaled[0]) and (y + h < origin_scaled[1]) or (x > origin_scaled[0] + size_scaled[0] and y > origin_scaled[1] + size_scaled[1]) or (w == 0 or h == 0)): return self.tmpDC.SetUserScale(self.scaling, self.scaling) if (y + h > self.image.nrows): h = self.image.nrows - y - 2 if (x + w > self.image.ncols): w = self.image.ncols - x - 2 subimage = SubImage(self.image, y, x, h + 1, w + 1) image = wxEmptyImage(w + 1, h + 1) apply(self.to_string_function, (subimage, image.GetDataBuffer())) bmp = wxBitmapFromImage(image) self.tmpDC.DrawBitmap(bmp, 0, 0, 0)
|
fudge = int(self.scaling / 2.0) if self.scaling == 1:
|
fudge = int(scaling / 2.0) if scaling == 1:
|
def PaintArea(self, x, y, w, h, check=1): dc = wxPaintDC(self) dc.SetLogicalFunction(wxCOPY) origin = [a * self.scroll_amount for a in self.GetViewStart()] origin_scaled = [a / self.scaling for a in origin] size_scaled = [a / self.scaling for a in self.GetSizeTuple()] if check: if ((x + w < origin_scaled[0]) and (y + h < origin_scaled[1]) or (x > origin_scaled[0] + size_scaled[0] and y > origin_scaled[1] + size_scaled[1]) or (w == 0 or h == 0)): return self.tmpDC.SetUserScale(self.scaling, self.scaling) if (y + h > self.image.nrows): h = self.image.nrows - y - 2 if (x + w > self.image.ncols): w = self.image.ncols - x - 2 subimage = SubImage(self.image, y, x, h + 1, w + 1) image = wxEmptyImage(w + 1, h + 1) apply(self.to_string_function, (subimage, image.GetDataBuffer())) bmp = wxBitmapFromImage(image) self.tmpDC.DrawBitmap(bmp, 0, 0, 0)
|
dc.Blit(x * self.scaling - origin[0], y * self.scaling - origin[1], w * self.scaling, h * self.scaling,
|
dc.Blit(x * scaling - origin[0], y * scaling - origin[1], w * scaling, h * scaling,
|
def PaintArea(self, x, y, w, h, check=1): dc = wxPaintDC(self) dc.SetLogicalFunction(wxCOPY) origin = [a * self.scroll_amount for a in self.GetViewStart()] origin_scaled = [a / self.scaling for a in origin] size_scaled = [a / self.scaling for a in self.GetSizeTuple()] if check: if ((x + w < origin_scaled[0]) and (y + h < origin_scaled[1]) or (x > origin_scaled[0] + size_scaled[0] and y > origin_scaled[1] + size_scaled[1]) or (w == 0 or h == 0)): return self.tmpDC.SetUserScale(self.scaling, self.scaling) if (y + h > self.image.nrows): h = self.image.nrows - y - 2 if (x + w > self.image.ncols): w = self.image.ncols - x - 2 subimage = SubImage(self.image, y, x, h + 1, w + 1) image = wxEmptyImage(w + 1, h + 1) apply(self.to_string_function, (subimage, image.GetDataBuffer())) bmp = wxBitmapFromImage(image) self.tmpDC.DrawBitmap(bmp, 0, 0, 0)
|
origin = self.GetViewStart()
|
origin = [x * self.scroll_amount for x in self.GetViewStart()]
|
def OnLeftDown(self, event): self.rubber_on = 1 self.draw_rubber() origin = self.GetViewStart() x = min((event.GetX() + origin[0]) / self.scaling, self.image.ncols - 1) y = min((event.GetY() + origin[1]) / self.scaling, self.image.nrows - 1) if (x > self.rubber_origin_x and x < self.rubber_origin_x + self.block_w): self.rubber_origin_x, self.rubber_x2 = \ self.rubber_x2, self.rubber_origin_x if (y > self.rubber_origin_y and y < self.rubber_origin_y + self.block_h): self.rubber_origin_y, self.rubber_y2 = \ self.rubber_y2, self.rubber_origin_y self.draw_rubber() return elif (y < self.rubber_y2 and y > self.rubber_y2 - self.block_h): self.draw_rubber() return elif (x < self.rubber_x2 and x > self.rubber_x2 - self.block_w): if (y > self.rubber_origin_y and y < self.rubber_origin_y + self.block_h): self.rubber_origin_y, self.rubber_y2 = \ self.rubber_y2, self.rubber_origin_y self.draw_rubber() return elif (y < self.rubber_y2 and y > self.rubber_y2 - self.block_h): self.draw_rubber() return self.rubber_origin_x = self.rubber_x2 = x self.rubber_origin_y = self.rubber_y2 = y
|
self.rubber_origin_x = self.rubber_x2 = x self.rubber_origin_y = self.rubber_y2 = y
|
self.rubber_origin_x = self.rubber_x2 = int(x) self.rubber_origin_y = self.rubber_y2 = int(y)
|
def OnLeftDown(self, event): self.rubber_on = 1 self.draw_rubber() origin = self.GetViewStart() x = min((event.GetX() + origin[0]) / self.scaling, self.image.ncols - 1) y = min((event.GetY() + origin[1]) / self.scaling, self.image.nrows - 1) if (x > self.rubber_origin_x and x < self.rubber_origin_x + self.block_w): self.rubber_origin_x, self.rubber_x2 = \ self.rubber_x2, self.rubber_origin_x if (y > self.rubber_origin_y and y < self.rubber_origin_y + self.block_h): self.rubber_origin_y, self.rubber_y2 = \ self.rubber_y2, self.rubber_origin_y self.draw_rubber() return elif (y < self.rubber_y2 and y > self.rubber_y2 - self.block_h): self.draw_rubber() return elif (x < self.rubber_x2 and x > self.rubber_x2 - self.block_w): if (y > self.rubber_origin_y and y < self.rubber_origin_y + self.block_h): self.rubber_origin_y, self.rubber_y2 = \ self.rubber_y2, self.rubber_origin_y self.draw_rubber() return elif (y < self.rubber_y2 and y > self.rubber_y2 - self.block_h): self.draw_rubber() return self.rubber_origin_x = self.rubber_x2 = x self.rubber_origin_y = self.rubber_y2 = y
|
origin = self.GetViewStart() self.rubber_x2 = min((event.GetX() + origin[0]) / self.scaling, self.image.ncols - 1) self.rubber_y2 = min((event.GetY() + origin[1]) / self.scaling, self.image.nrows - 1)
|
origin = [x * self.scroll_amount for x in self.GetViewStart()] self.rubber_x2 = int(min((event.GetX() + origin[0]) / self.scaling, self.image.ncols - 1)) self.rubber_y2 = int(min((event.GetY() + origin[1]) / self.scaling, self.image.nrows - 1))
|
def OnLeftUp(self, event): if self.rubber_on: self.draw_rubber() origin = self.GetViewStart() self.rubber_x2 = min((event.GetX() + origin[0]) / self.scaling, self.image.ncols - 1) self.rubber_y2 = min((event.GetY() + origin[1]) / self.scaling, self.image.nrows - 1) self.draw_rubber() for i in self.click_callbacks: try: i(self.rubber_y2, self.rubber_x2) except Exception, e: print e self.OnLeave(event)
|
origin = self.GetViewStart()
|
scaling = self.scaling origin = [x * self.scroll_amount for x in self.GetViewStart()]
|
def draw_rubber(self): dc = wxPaintDC(self) origin = self.GetViewStart() x = min(self.rubber_origin_x, self.rubber_x2) y = min(self.rubber_origin_y, self.rubber_y2) x2 = max(self.rubber_origin_x, self.rubber_x2) y2 = max(self.rubber_origin_y, self.rubber_y2) x = x * self.scaling - origin[0] y = y * self.scaling - origin[1] x2 = x2 * self.scaling - origin[0] y2 = y2 * self.scaling - origin[1] w = x2 - x h = y2 - y dc.SetLogicalFunction(wxXOR) pen = wxGREY_PEN pen.SetStyle(wxSHORT_DASH) dc.SetPen(pen) dc.SetBrush(wxTRANSPARENT_BRUSH) dc.DrawRectangle(x, y, w, h) dc.SetPen(wxTRANSPARENT_PEN) brush = wxBLUE_BRUSH brush.SetColour(wxColor(167, 105, 39)) dc.SetBrush(brush) self.block_w = block_w = min(w / 2, 8) self.block_h = block_h = min(h / 2, 8) dc.DrawRectangle(x + 1, y + 1, block_w, block_h) dc.DrawRectangle(x2 - block_w - 1, y + 1, block_w, block_h) dc.DrawRectangle(x + 1, y2 - block_h - 1, block_w, block_h) dc.DrawRectangle(x2 - block_w - 1, y2 - block_h - 1, block_w, block_h) dc.SetLogicalFunction(wxCOPY)
|
x = x * self.scaling - origin[0] y = y * self.scaling - origin[1] x2 = x2 * self.scaling - origin[0] y2 = y2 * self.scaling - origin[1]
|
x = x * scaling - origin[0] y = y * scaling - origin[1] x2 = x2 * scaling - origin[0] y2 = y2 * scaling - origin[1]
|
def draw_rubber(self): dc = wxPaintDC(self) origin = self.GetViewStart() x = min(self.rubber_origin_x, self.rubber_x2) y = min(self.rubber_origin_y, self.rubber_y2) x2 = max(self.rubber_origin_x, self.rubber_x2) y2 = max(self.rubber_origin_y, self.rubber_y2) x = x * self.scaling - origin[0] y = y * self.scaling - origin[1] x2 = x2 * self.scaling - origin[0] y2 = y2 * self.scaling - origin[1] w = x2 - x h = y2 - y dc.SetLogicalFunction(wxXOR) pen = wxGREY_PEN pen.SetStyle(wxSHORT_DASH) dc.SetPen(pen) dc.SetBrush(wxTRANSPARENT_BRUSH) dc.DrawRectangle(x, y, w, h) dc.SetPen(wxTRANSPARENT_PEN) brush = wxBLUE_BRUSH brush.SetColour(wxColor(167, 105, 39)) dc.SetBrush(brush) self.block_w = block_w = min(w / 2, 8) self.block_h = block_h = min(h / 2, 8) dc.DrawRectangle(x + 1, y + 1, block_w, block_h) dc.DrawRectangle(x2 - block_w - 1, y + 1, block_w, block_h) dc.DrawRectangle(x + 1, y2 - block_h - 1, block_w, block_h) dc.DrawRectangle(x2 - block_w - 1, y2 - block_h - 1, block_w, block_h) dc.SetLogicalFunction(wxCOPY)
|
origin = self.GetViewStart() self.rubber_x2 = min((event.GetX() + origin[0]) / self.scaling, self.image.ncols - 1) self.rubber_y2 = min((event.GetY() + origin[1]) / self.scaling, self.image.nrows - 1)
|
origin = [x * self.scroll_amount for x in self.GetViewStart()] self.rubber_x2 = int(min((event.GetX() + origin[0]) / self.scaling, self.image.ncols - 1)) self.rubber_y2 = int(min((event.GetY() + origin[1]) / self.scaling, self.image.nrows - 1))
|
def OnMotion(self, event): if self.rubber_on: self.draw_rubber() origin = self.GetViewStart() self.rubber_x2 = min((event.GetX() + origin[0]) / self.scaling, self.image.ncols - 1) self.rubber_y2 = min((event.GetY() + origin[1]) / self.scaling, self.image.nrows - 1) self.draw_rubber() if self.dragging: self.Scroll( (self.dragging_origin_x - (event.GetX() - self.dragging_x)) / self.scroll_amount, (self.dragging_origin_y - (event.GetY() - self.dragging_y)) / self.scroll_amount)
|
except IOError, e: print e
|
except: pass
|
def load_image(filename, compression = DENSE): """**load_image** (FileOpen *filename*, Choice *storage_format* = ``DENSE``)
|
*input_filename*: The input Gamera XML filename *output_filename*: The output Gamera XML filename"""
|
*input_filename* The input Gamera XML filename *output_filename* The output Gamera XML filename"""
|
def strip_features(input_filename, output_filename): """**strip_features** (FileOpen *input_filename*, FileSave *output_filename*)
|
faces = shell.faces style_face = config.options.shell.face for face in ('times', 'mono', 'helv', 'other'): faces[face] = style_face faces['lnsize'] = int(config.options.shell.size) - 2 faces['size'] = int(config.options.shell.size) self.setStyles(faces)
|
def __init__(self, main_win, parent, id, message):
|
|
self._database = util.CallbackList(database)
|
def __init__(self, database=[], features='all', perform_splits=True): """
|
|
if (recursion_level > max_recursion) or len(self.database) == 0:
|
if (recursion_level > max_recursion):
|
def _classify_list_automatic(self, glyphs, max_recursion=10, recursion_level=0, progress=None):
|
self._classifier.generate_features(glyphs)
|
for glyph in glyphs: self._classifier.generate_features(glyph)
|
def _SavePageCollection(self, filename, glyphs=None, with_features=True): if glyphs is None: glyphs = self.multi_iw.id.GetAllItems() self._classifier.generate_features(glyphs) try: gamera_xml.WriteXMLFile( glyphs=glyphs, symbol_table=self._symbol_table, with_features=with_features).write_filename(filename) except gamera_xml.XMLError, e: gui_util.message("Saving page glyphs: " + str(e))
|
self._classifier.generate_features(glyphs)
|
for glyph in glyphs: self._classifier.generate_features(glyph)
|
def _OnSaveSelectedGlyphs(self, event): glyphs = self.get_all_selected()[0] if len(glyphs) == 0: gui_util.message("There are no selected glyphs.") return if gui_util.are_you_sure_dialog( ("There are %d selected glyphs.\n" + "Are you sure you want to save?") % len(glyphs)): filename = gui_util.save_file_dialog(self._frame, gamera_xml.extensions) if filename: self._classifier.generate_features(glyphs) try: gamera_xml.WriteXMLFile( glyphs=glyphs, symbol_table=self._symbol_table).write_filename( filename) except gamera_xml.XMLError, e: gui_util.message("Saving selected glyphs: " + str(e))
|
if not gui_util.are_you_sure_dialog("Editing glyphs have not been saved. Are you sure you wish to proceed?"):
|
if not gui_util.are_you_sure_dialog("Page glyphs have not been saved. Are you sure you wish to proceed?"):
|
def _OnOpenAndSegmentImage(self, event): if self.multi_iw.id.is_dirty: if not gui_util.are_you_sure_dialog("Editing glyphs have not been saved. Are you sure you wish to proceed?"): return segmenters = [x[0] for x in ImageBase.methods_flat_category("Segmentation", ONEBIT)] if self.default_segmenter == -1: self.default_segmenter = segmenters.index("cc_analysis") dialog = Args( [FileOpen("Image file", "", "*.*"), Choice("Segmentation algorithm", segmenters, self.default_segmenter)], name="Open and segment image...") filename = None while filename is None: results = dialog.show(self._frame) if results is None: return filename, segmenter = results self.default_segmenter = segmenter if filename == None: gui_util.message("You must provide a filename to load.") wxBeginBusyCursor() try: image = load_image(filename) self._segment_image(image, segmenters[segmenter]) except Exception, e: gui_util.message(str(e)) wxEndBusyCursor() return self.multi_iw.id.is_dirty = False wxEndBusyCursor()
|
if not gui_util.are_you_sure_dialog("Editing glyphs have not been saved. Are you sure you wish to proceed?"):
|
if not gui_util.are_you_sure_dialog("Page glyphs have not been saved. Are you sure you wish to proceed?"):
|
def _OnSelectAndSegmentImage(self, event): if self.multi_iw.id.is_dirty: if not gui_util.are_you_sure_dialog("Editing glyphs have not been saved. Are you sure you wish to proceed?"): return segmenters = [x[0] for x in ImageBase.methods_flat_category("Segmentation", ONEBIT)] if self.default_segmenter == -1: self.default_segmenter = segmenters.index("cc_analysis") dialog = Args( [Class("Image", ImageBase), Choice("Segmentation algorithm", segmenters, self.default_segmenter)], name="Select and segment image...") results = dialog.show(self._frame, image_menu.shell.locals) if results is None: return image, segmenter = results wxBeginBusyCursor() try: self._segment_image(image, segmenters[segmenter]) except Exception, e: gui_util.message(str(e)) wxEndBusyCursor() return self.multi_iw.id.is_dirty = False wxEndBusyCursor()
|
self.progress_box.Update(min(100, int((float(num) / float(den)) * 100.0)))
|
def update(self, num, den): if not self.done: self.progress_box.Update(min(100, int((float(num) / float(den)) * 100.0))) if num >= den: self.done = 1 wxEndBusyCursor() self.progress_box.Destroy()
|
|
self.done = 1
|
self.done = True
|
def update(self, num, den): if not self.done: self.progress_box.Update(min(100, int((float(num) / float(den)) * 100.0))) if num >= den: self.done = 1 wxEndBusyCursor() self.progress_box.Destroy()
|
for col in xrange(self.cols, -1, -1): for row in xrange(self.rows, -1, -1):
|
for row in xrange(0, self.cols): for col in xrange(0, self.rows):
|
def do_auto_move(self, state): # if auto-moving is turned off, just return if state == []: return
|
Pixel("value")]) def __call__(self, *args): if len(args) == 9:
|
Pixel("value"), Float("accuracy", default=0.1)]) def __call__(self, *args): if len(args) == 10:
|
def __doc_example1__(): from random import randint from gamera.core import Image image = Image(0, 0, 100, 100, RGB, DENSE) for i in range(10): image.draw_filled_rect(randint(0, 100), randint(0, 100), randint(0, 100), randint(0, 100), RGBPixel(randint(0, 255), randint(0,255), randint(0, 255))) return image
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.