rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if options.ids_file is not None:
if read_id and options.ids_file is not None:
def main(): options = read_cmd_options() config = read_config() save_pattern = config.get('default', 'save-filename-pattern') if options.ex_data_filename is not None: solutions, dimensions, id_num_digits = \ process_exam_data(options.ex_data_filename) else: solutions = [] dimensions = [] if options.output_dir is not N...
if id_num_digits > 0:
if read_id:
def main(): options = read_cmd_options() config = read_config() save_pattern = config.get('default', 'save-filename-pattern') if options.ex_data_filename is not None: solutions, dimensions, id_num_digits = \ process_exam_data(options.ex_data_filename) else: solutions = [] dimensions = [] if options.output_dir is not N...
elif event.key == ord('i'):
elif event.key == ord('i') and read_id:
def main(): options = read_cmd_options() config = read_config() save_pattern = config.get('default', 'save-filename-pattern') if options.ex_data_filename is not None: solutions, dimensions, id_num_digits = \ process_exam_data(options.ex_data_filename) else: solutions = [] dimensions = [] if options.output_dir is not N...
elif event.key == 9 and options.ids_file is not None:
elif event.key == 9 and read_id \ and options.ids_file is not None:
def main(): options = read_cmd_options() config = read_config() save_pattern = config.get('default', 'save-filename-pattern') if options.ex_data_filename is not None: solutions, dimensions, id_num_digits = \ process_exam_data(options.ex_data_filename) else: solutions = [] dimensions = [] if options.output_dir is not N...
and options.ids_file is not None:
and read_id and options.ids_file is not None:
def main(): options = read_cmd_options() config = read_config() save_pattern = config.get('default', 'save-filename-pattern') if options.ex_data_filename is not None: solutions, dimensions, id_num_digits = \ process_exam_data(options.ex_data_filename) else: solutions = [] dimensions = [] if options.output_dir is not N...
file_ = open(output_file)
file_ = open(output_file, 'w')
def create_answer_sheet(template_file, output_file, variables, num_questions, num_answers, model, num_tables = 0): replacements = {} for var in variables: replacements[re.compile('{{' + var + '}}')] = variables[var] answer_table = create_answer_table(num_questions, num_answers, model, num_tables) id_box = create_id_box...
file.close()
file_.close()
def create_answer_sheet(template_file, output_file, variables, num_questions, num_answers, model, num_tables = 0): replacements = {} for var in variables: replacements[re.compile('{{' + var + '}}')] = variables[var] answer_table = create_answer_table(num_questions, num_answers, model, num_tables) id_box = create_id_box...
last_row = (num_tables - diff) * [num_answers] + diff * [-1]
last_row = diff * [num_answers] + (num_tables - diff) * [-1]
def __table_geometry(num_questions, num_answers, num_tables): """Returns the geometry of the answer tables. The result is a tuple (tables, question_numbers) where: - 'tables' is a bidimensional list such that table[row][column] represents the number of answers for the question in 'row' / 'column'. If 0, the question d...
1, 0.01, 230) return lines
1, 0.01, param_hough_threshold) if lines.total > 500: print "Too many lines in detect_directions:", lines.total return [] s_lines = sorted([(float(l[0]), float(l[1])) for l in lines], key = lambda x: x[1]) return s_lines
def detect_lines(image): st = opencv.cvCreateMemStorage() lines = opencv.cvHoughLines2(image, st, opencv.CV_HOUGH_STANDARD, 1, 0.01, 230) return lines
if lines.total < 2:
if len(lines) < 2:
def draw_lines(image_raw, image_proc, boxes_dim): lines = detect_lines(image_proc) if lines.total < 2: return axes = detect_boxes(lines, boxes_dim) if axes is not None: corner_matrixes = cell_corners(axes[1][1], axes[0][1], boxes_dim) for line in axes[0][1]: draw_tangent(image_raw, line[0], line[1], (255, 0, 0)) for li...
draw_corner(image_raw, c[0], c[1])
draw_corner(image_raw, c[0], c[1], (0, 0, 255))
def draw_lines(image_raw, image_proc, boxes_dim): lines = detect_lines(image_proc) if lines.total < 2: return axes = detect_boxes(lines, boxes_dim) if axes is not None: corner_matrixes = cell_corners(axes[1][1], axes[0][1], boxes_dim) for line in axes[0][1]: draw_tangent(image_raw, line[0], line[1], (255, 0, 0)) for li...
assert(lines.total >= 2) s_lines = sorted([(l[0], l[1]) for l in lines], key = lambda x: x[1])
assert(len(lines) >= 2)
def detect_directions(lines): assert(lines.total >= 2) s_lines = sorted([(l[0], l[1]) for l in lines], key = lambda x: x[1]) axes = [] rho, theta = s_lines[0] axes.append((theta, [(rho, theta)])) for rho, theta in s_lines[1:]: if abs(theta - axes[-1][0]) < param_directions_threshold: axes[-1][1].append((rho, theta)) el...
rho, theta = s_lines[0]
rho, theta = lines[0]
def detect_directions(lines): assert(lines.total >= 2) s_lines = sorted([(l[0], l[1]) for l in lines], key = lambda x: x[1]) axes = [] rho, theta = s_lines[0] axes.append((theta, [(rho, theta)])) for rho, theta in s_lines[1:]: if abs(theta - axes[-1][0]) < param_directions_threshold: axes[-1][1].append((rho, theta)) el...
for rho, theta in s_lines[1:]:
for rho, theta in lines[1:]:
def detect_directions(lines): assert(lines.total >= 2) s_lines = sorted([(l[0], l[1]) for l in lines], key = lambda x: x[1]) axes = [] rho, theta = s_lines[0] axes.append((theta, [(rho, theta)])) for rho, theta in s_lines[1:]: if abs(theta - axes[-1][0]) < param_directions_threshold: axes[-1][1].append((rho, theta)) el...
print "Angle:", lines[0][1]
def collapse_lines(lines, horizontal): if horizontal: print "Angle:", lines[0][1] threshold = max(param_collapse_threshold \ - abs(lines[0][1] - math.pi / 2) * 24, param_collapse_threshold / 2) else: threshold = param_collapse_threshold print "Threshold", threshold coll = [] first = 0 sum_rho = lines[0][0] sum_theta = ...
print "Threshold", threshold
def collapse_lines(lines, horizontal): if horizontal: print "Angle:", lines[0][1] threshold = max(param_collapse_threshold \ - abs(lines[0][1] - math.pi / 2) * 24, param_collapse_threshold / 2) else: threshold = param_collapse_threshold print "Threshold", threshold coll = [] first = 0 sum_rho = lines[0][0] sum_theta = ...
if len(hlines) != 1 + max([box[1] for box in boxes_dim]) \ or len(vlines) != 4 + sum([box[0] for box in boxes_dim]):
h_expected = 1 + max([box[1] for box in boxes_dim]) v_expected = 4 + sum([box[0] for box in boxes_dim]) if len(vlines) != v_expected:
def cell_corners(hlines, vlines, boxes_dim): if len(hlines) != 1 + max([box[1] for box in boxes_dim]) \ or len(vlines) != 4 + sum([box[0] for box in boxes_dim]): return [] corner_matrixes = [] vini = 1 for box_dim in boxes_dim: width, height = box_dim corners = [] for i in range(0, height + 1): cpart = [] corners.appen...
opencv.cvCircle(image, (x, y), 5, color, opencv.CV_FILLED)
if x >= 0 and x < image.width and y >= 0 and y < image.height: opencv.cvCircle(image, (x, y), 5, color, opencv.CV_FILLED) else: print "draw_corner: bad point (%d, %d)"%(x, y)
def draw_corner(image, x, y, color = (0, 0, 255, 0)): opencv.cvCircle(image, (x, y), 5, color, opencv.CV_FILLED)
threshold = 0.1
def detect_directions(lines): assert(lines.total >= 2) threshold = 0.1 s_lines = sorted([(l[0], l[1]) for l in lines], key = lambda x: x[1]) axes = [] rho, theta = s_lines[0] axes.append((theta, [(rho, theta)])) for rho, theta in s_lines[1:]: if abs(theta - axes[-1][0]) < 0.1: axes[-1][1].append((rho, theta)) else: axe...
if abs(theta - axes[-1][0]) < 0.1:
if abs(theta - axes[-1][0]) < param_directions_threshold:
def detect_directions(lines): assert(lines.total >= 2) threshold = 0.1 s_lines = sorted([(l[0], l[1]) for l in lines], key = lambda x: x[1]) axes = [] rho, theta = s_lines[0] axes.append((theta, [(rho, theta)])) for rho, theta in s_lines[1:]: if abs(theta - axes[-1][0]) < 0.1: axes[-1][1].append((rho, theta)) else: axe...
if abs(axes[0][0] - axes[-1][0] + math.pi) < 0.1:
if abs(axes[0][0] - axes[-1][0] + math.pi) < param_directions_threshold:
def detect_directions(lines): assert(lines.total >= 2) threshold = 0.1 s_lines = sorted([(l[0], l[1]) for l in lines], key = lambda x: x[1]) axes = [] rho, theta = s_lines[0] axes.append((theta, [(rho, theta)])) for rho, theta in s_lines[1:]: if abs(theta - axes[-1][0]) < 0.1: axes[-1][1].append((rho, theta)) else: axe...
axes[i] = (avg, axes[i][1])
axes[i] = (avg, sorted(axes[i][1], key = lambda x: abs(x[0]))) if abs(axes[-1][0] - math.pi) < abs(axes[0][0]): axes = axes[-1:] + axes[0:-1]
def detect_directions(lines): assert(lines.total >= 2) threshold = 0.1 s_lines = sorted([(l[0], l[1]) for l in lines], key = lambda x: x[1]) axes = [] rho, theta = s_lines[0] axes.append((theta, [(rho, theta)])) for rho, theta in s_lines[1:]: if abs(theta - axes[-1][0]) < 0.1: axes[-1][1].append((rho, theta)) else: axe...
if len(axes) == 2 and abs(axes[1][0] - axes[0][0] - math.pi / 2) < 0.1: axes[0] = (axes[0][0], collapse_lines(axes[0][1])) axes[1] = (axes[1][0], collapse_lines(axes[1][1])) return axes
if len(axes) == 2: perpendicular = abs(axes[1][0] - axes[0][0] - math.pi / 2) < 0.1 \ or abs(axes[1][0] - axes[0][0] + math.pi / 2) < 0.1 if perpendicular: axes[0] = (axes[0][0], collapse_lines(axes[0][1], False)) axes[1] = (axes[1][0], collapse_lines(axes[1][1], True)) return axes
def detect_boxes(lines, boxes_dim): expected_horiz = 1 + max([box[1] for box in boxes_dim]) expected_vert = 4 + sum([box[0] for box in boxes_dim]) axes = detect_directions(lines) axes = [axis for axis in axes if len(axis[1]) >= 5] if len(axes) == 2 and abs(axes[1][0] - axes[0][0] - math.pi / 2) < 0.1: axes[0] = (axes[0...
def collapse_lines(lines):
def collapse_lines(lines, horizontal): if horizontal: print "Angle:", lines[0][1] threshold = max(param_collapse_threshold \ - abs(lines[0][1] - math.pi / 2) * 24, param_collapse_threshold / 2) else: threshold = param_collapse_threshold print "Threshold", threshold
def collapse_lines(lines): coll = [] lines.sort() first = 0 sum_rho = lines[0][0] sum_theta = lines[0][1] for i in range(1, len(lines)): if lines[i][0] - lines[first][0] > param_collapse_diff: coll.append((sum_rho / (i - first), sum_theta / (i - first))) first = i sum_rho = lines[i][0] sum_theta = lines[i][1] else: sum...
lines.sort()
def collapse_lines(lines): coll = [] lines.sort() first = 0 sum_rho = lines[0][0] sum_theta = lines[0][1] for i in range(1, len(lines)): if lines[i][0] - lines[first][0] > param_collapse_diff: coll.append((sum_rho / (i - first), sum_theta / (i - first))) first = i sum_rho = lines[i][0] sum_theta = lines[i][1] else: sum...
if lines[i][0] - lines[first][0] > param_collapse_diff:
if abs(lines[i][0] - lines[first][0]) > threshold:
def collapse_lines(lines): coll = [] lines.sort() first = 0 sum_rho = lines[0][0] sum_theta = lines[0][1] for i in range(1, len(lines)): if lines[i][0] - lines[first][0] > param_collapse_diff: coll.append((sum_rho / (i - first), sum_theta / (i - first))) first = i sum_rho = lines[i][0] sum_theta = lines[i][1] else: sum...
bit_list[0] = not bit_list[0]
bit_list[2] = not bit_list[2]
def encode_model(model, num_tables, num_answers): """Given the letter of the model, returns the infobits pattern. It is formatted as an array of booleans string where the pos. 0 is the one that goes in the column of the table at the left. The length of the string is 'num_tables' * 'num_answers', where 'num_tables' is ...
print "Radius:", radius, "/ Mask pixels:", mask_pixels
def decide_infobit(image, mask, masked, center_up, dy): center_down = add_points(center_up, dy) radius = int(round(math.sqrt(dy[0] * dy[0] + dy[1] * dy[1]) \ * param_bit_mask_radius_multiplier)) if radius == 0: radius = 1 radius = int(round(math.sqrt(dy[0] * dy[0] + dy[1] * dy[1]) / 3)) cv.SetZero(mask) cv.Circle(mask,...
color_good = (0, 164, 0)
color_good = (0, 210, 0)
def draw_answers(self, frozen, solutions, model, correct, good, bad, undet, im_id = None): base = 0 color_good = (0, 164, 0) color_bad = (0, 0, 255) color_dot = (255, 0, 0) color = (255, 0, 0) if self.status['cells']: for corners in self.corner_matrixes: for i in range(0, len(corners) - 1): d = self.decisions[base + i]...
color_dot = (255, 0, 0) color = (255, 0, 0)
color_dot = (200, 50, 0)
def draw_answers(self, frozen, solutions, model, correct, good, bad, undet, im_id = None): base = 0 color_good = (0, 164, 0) color_bad = (0, 0, 255) color_dot = (255, 0, 0) color = (255, 0, 0) if self.status['cells']: for corners in self.corner_matrixes: for i in range(0, len(corners) - 1): d = self.decisions[base + i]...
color = (0, 0, 255)
color = color_bad
def draw_answers(self, frozen, solutions, model, correct, good, bad, undet, im_id = None): base = 0 color_good = (0, 164, 0) color_bad = (0, 0, 255) color_dot = (255, 0, 0) color = (255, 0, 0) if self.status['cells']: for corners in self.corner_matrixes: for i in range(0, len(corners) - 1): d = self.decisions[base + i]...
color = (255, 0, 0)
color = color_dot
def draw_answers(self, frozen, solutions, model, correct, good, bad, undet, im_id = None): base = 0 color_good = (0, 164, 0) color_bad = (0, 0, 255) color_dot = (255, 0, 0) color = (255, 0, 0) if self.status['cells']: for corners in self.corner_matrixes: for i in range(0, len(corners) - 1): d = self.decisions[base + i]...
rows = __table_top(num_tables, num_answers)
rows = __table_top(num_tables, num_answers, compact)
def create_answer_table(num_questions, num_answers, model, num_tables = 0): """Returns a string with the answer tables of the asnwer sheet. Tables are LaTeX-formatted. 'num_questions' specifies the number of questions of the exam. 'num_answers' specifies the number of answers per question. 'num_tables' (optional) spec...
rows.append(__horizontal_line(row_geometry, num_answers))
rows.append(__horizontal_line(row_geometry, num_answers, compact))
def create_answer_table(num_questions, num_answers, model, num_tables = 0): """Returns a string with the answer tables of the asnwer sheet. Tables are LaTeX-formatted. 'num_questions' specifies the number of questions of the exam. 'num_answers' specifies the number of answers per question. 'num_tables' (optional) spec...
num_answers, bits_rows))
num_answers, bits_rows, compact))
def create_answer_table(num_questions, num_answers, model, num_tables = 0): """Returns a string with the answer tables of the asnwer sheet. Tables are LaTeX-formatted. 'num_questions' specifies the number of questions of the exam. 'num_answers' specifies the number of answers per question. 'num_tables' (optional) spec...
tables.append((num_tables - diff) * [-1] + diff * [-2]) tables.append((num_tables - diff) * [-2] + diff * [0])
if diff == 0: diff = 3 tables.append(diff * [-1] + (num_tables - diff) * [-2]) tables.append(diff * [-2] + (num_tables - diff) * [-0])
def __table_geometry(num_questions, num_answers, num_tables): """Returns the geometry of the answer tables. The result is a tuple (tables, question_numbers) where: - 'tables' is a bidimensional list such that table[row][column] represents the number of answers for the question in 'row' / 'column'. If 0, the question d...
def __horizontal_line(row_geometry, num_answers):
def __horizontal_line(row_geometry, num_answers, compact):
def __horizontal_line(row_geometry, num_answers): parts = [] first = 2 for i, geometry in enumerate(row_geometry): if geometry > 0 or geometry == -1: parts.append('\\cline{%d-%d}'%(first, first + num_answers - 1)) first += 2 + num_answers return ' '.join(parts)
first += 2 + num_answers
first += 1 + num_empty_columns + num_answers
def __horizontal_line(row_geometry, num_answers): parts = [] first = 2 for i, geometry in enumerate(row_geometry): if geometry > 0 or geometry == -1: parts.append('\\cline{%d-%d}'%(first, first + num_answers - 1)) first += 2 + num_answers return ' '.join(parts)
def __table_top(num_tables, num_answers): l = 'p{3mm}'.join(num_tables * ['|'.join(['r'] + num_answers * ['c'] + [''])])
def __table_top(num_tables, num_answers, compact): middle_sep_format = 'p{3mm}' if not compact else '' middle_sep_header = ' & & ' if not compact else ' & ' l = middle_sep_format.join(num_tables * ['|'.join(['r'] + num_answers * ['c'] + [''])])
def __table_top(num_tables, num_answers): l = 'p{3mm}'.join(num_tables * ['|'.join(['r'] + num_answers * ['c'] + [''])]) l = '\\\\begin{tabular}{' + l + '}' lines = ['\\\\begin{center}', '\\large', l] parts = [] for i in range(0, num_tables): parts_internal = [] parts_internal.append('\\multicolumn{1}{c}{}') for j in r...
lines.append(' & & '.join(parts) + ' \\\\\\\\')
lines.append(middle_sep_header.join(parts) + ' \\\\\\\\')
def __table_top(num_tables, num_answers): l = 'p{3mm}'.join(num_tables * ['|'.join(['r'] + num_answers * ['c'] + [''])]) l = '\\\\begin{tabular}{' + l + '}' lines = ['\\\\begin{center}', '\\large', l] parts = [] for i in range(0, num_tables): parts_internal = [] parts_internal.append('\\multicolumn{1}{c}{}') for j in r...
infobits_row):
infobits_row, compact):
def __build_row(num_row, row_geometry, question_numbers, num_answers, infobits_row): parts = [] skip_cells = 0 for i, geometry in enumerate(row_geometry): if geometry > 0: parts.append(__build_question_cell(num_row + question_numbers[i], geometry)) elif geometry == -1: parts.append(infobits_row[0][i]) elif geometry == ...
skip_cells += 2 + num_answers row = ' & & '.join(parts)
skip_cells += 1 + num_empty_columns + num_answers row = ' & & '.join(parts) if not compact else ' & '.join(parts)
def __build_row(num_row, row_geometry, question_numbers, num_answers, infobits_row): parts = [] skip_cells = 0 for i, geometry in enumerate(row_geometry): if geometry > 0: parts.append(__build_question_cell(num_row + question_numbers[i], geometry)) elif geometry == -1: parts.append(infobits_row[0][i]) elif geometry == ...
self.student_id = -1
self.student_id = '-1'
def invalidate_id(self): self.image.id = None self.student_id = -1 self.image.clean_drawn_image(True) self.draw_answers()
corners = corner_matrixes[0]
corners = corner_matrixes[(len(corner_matrixes) - 1) // 2]
def check_corners(corner_matrixes, width, height): # Check differences between horizontal lines: corners = corner_matrixes[0] ypoints = [row[-1][1] for row in corners] difs = [] difs2 = [] for i in range(1, len(ypoints)): difs.append(ypoints[i] - ypoints[i - 1]) for i in range(1, len(difs)): difs2.append(difs[i] - difs...
self.options['show-lines'],
self.options['debug-ocr'],
def detect_id(self): if self.id_corners is None: self.id = None corners_up, corners_down = self.id_corners digits = [] self.id_scores = [] for i in range(0, len(corners_up) - 1): corners = (corners_up[i], corners_up[i + 1], corners_down[i], corners_down[i + 1]) digit, scores = (ocr.digit_ocr(self.image_proc, corners, s...
camera = config.getint('default', 'camera-dev')
camera = config.getint('DEFAULT', 'camera-dev')
def select_camera(options, config): if options.camera_dev is None: try: camera = config.getint('default', 'camera-dev') except: camera = -1 else: camera = options.camera_dev return camera
save_pattern = config.get('default', 'save-filename-pattern')
save_pattern = config.get('DEFAULT', 'save-filename-pattern')
def main(): options = read_cmd_options() config = read_config() save_pattern = config.get('default', 'save-filename-pattern') if options.ex_data_filename is not None: solutions, dimensions, id_num_digits = \ process_exam_data(options.ex_data_filename) else: solutions = [] dimensions = [] id_num_digits = 0 read_id = (i...
self.options = options if not options['capture-from-file']:
if options == {}: self.options = self.__class__.get_default_options() else: self.options = options if not self.options['capture-from-file']:
def __init__(self, camera, boxes_dim, options = {}): self.options = options if not options['capture-from-file']: self.image_raw = capture(camera, True) self.image_proc = pre_process(self.image_raw) elif options['capture-raw-file'] is not None: self.image_raw = load_image(options['capture-raw-file']) self.image_proc = p...
elif options['capture-raw-file'] is not None: self.image_raw = load_image(options['capture-raw-file'])
elif self.options['capture-raw-file'] is not None: self.image_raw = load_image(self.options['capture-raw-file'])
def __init__(self, camera, boxes_dim, options = {}): self.options = options if not options['capture-from-file']: self.image_raw = capture(camera, True) self.image_proc = pre_process(self.image_raw) elif options['capture-raw-file'] is not None: self.image_raw = load_image(options['capture-raw-file']) self.image_proc = p...
elif options['capture-proc-file'] is not None: self.image_raw = load_image(options['capture-proc-file'])
elif self.options['capture-proc-file'] is not None: self.image_raw = load_image(self.options['capture-proc-file'])
def __init__(self, camera, boxes_dim, options = {}): self.options = options if not options['capture-from-file']: self.image_raw = capture(camera, True) self.image_proc = pre_process(self.image_raw) elif options['capture-raw-file'] is not None: self.image_raw = load_image(options['capture-raw-file']) self.image_proc = p...
if not options['show-image-proc']:
if not self.options['show-image-proc']:
def __init__(self, camera, boxes_dim, options = {}): self.options = options if not options['capture-from-file']: self.image_raw = capture(camera, True) self.image_proc = pre_process(self.image_raw) elif options['capture-raw-file'] is not None: self.image_raw = load_image(options['capture-raw-file']) self.image_proc = p...
if self.image.options['read-id'] and self.student_id != '-1': sid = self.student_id else: sid = 'noid' filename = regexp_seqnum.sub(str(self.im_id), filename_pattern) filename = regexp_id.sub(sid, filename)
filename = self.__saved_image_name(filename_pattern)
def save_image(self, filename_pattern): if self.image.options['read-id'] and self.student_id != '-1': sid = self.student_id else: sid = 'noid' filename = regexp_seqnum.sub(str(self.im_id), filename_pattern) filename = regexp_id.sub(sid, filename) cv.SaveImage(filename, self.image.image_drawn)
raw_pattern = filename_pattern + "-raw" proc_pattern = filename_pattern + "-proc" cv.SaveImage(raw_pattern%self.im_id, self.image.image_raw) cv.SaveImage(proc_pattern%self.im_id, self.image.image_proc)
filename = self.__saved_image_name(filename_pattern) cv.SaveImage(filename + '-raw', self.image.image_raw) cv.SaveImage(filename + '-proc', self.image.image_proc)
def save_debug_images(self, filename_pattern): raw_pattern = filename_pattern + "-raw" proc_pattern = filename_pattern + "-proc" cv.SaveImage(raw_pattern%self.im_id, self.image.image_raw) cv.SaveImage(proc_pattern%self.im_id, self.image.image_proc)
for line in axes[0][1] + axes[1][1]:
for line in axes[0][1]:
def draw_lines(image_raw, image_proc, boxes_dim): lines = detect_lines(image_proc) if lines.total < 2: return axes = detect_boxes(lines, boxes_dim) if axes is not None: corner_matrixes = cell_corners(axes[1][1], axes[0][1], boxes_dim) for line in axes[0][1] + axes[1][1]: draw_tangent(image_raw, line[0], line[1], (255, ...
if lines[i][0] - lines[first][0] > 15:
if lines[i][0] - lines[first][0] > param_collapse_diff:
def collapse_lines(lines): coll = [] lines.sort() first = 0 sum_rho = lines[0][0] sum_theta = lines[0][1] for i in range(1, len(lines)): if lines[i][0] - lines[first][0] > 15: coll.append((sum_rho / (i - first), sum_theta / (i - first))) first = i sum_rho = lines[i][0] sum_theta = lines[i][1] else: sum_rho += lines[i][...
y = rho1 * (math.cos(theta2) - math.cos(theta1)) \
y = (rho1 * math.cos(theta2) - rho2 * math.cos(theta1)) \
def intersection(hline, vline): rho1, theta1 = hline rho2, theta2 = vline y = rho1 * (math.cos(theta2) - math.cos(theta1)) \ / (math.sin(theta1) * math.cos(theta2) \ + math.sin(theta2) * math.cos(theta1)) x = (rho2 - y * math.sin(theta2)) / math.cos(theta2) return (int(x), int(y))
+ math.sin(theta2) * math.cos(theta1))
- math.sin(theta2) * math.cos(theta1))
def intersection(hline, vline): rho1, theta1 = hline rho2, theta2 = vline y = rho1 * (math.cos(theta2) - math.cos(theta1)) \ / (math.sin(theta1) * math.cos(theta2) \ + math.sin(theta2) * math.cos(theta1)) x = (rho2 - y * math.sin(theta2)) / math.cos(theta2) return (int(x), int(y))
cv.SaveImage(filename_pattern%self.im_id, self.image.image_drawn)
if self.image.options['read-id'] and self.student_id != '-1': sid = self.student_id else: sid = 'noid' filename = regexp_seqnum.sub(str(self.im_id), filename_pattern) filename = regexp_id.sub(sid, filename) cv.SaveImage(filename, self.image.image_drawn)
def save_image(self, filename_pattern): cv.SaveImage(filename_pattern%self.im_id, self.image.image_drawn)
def init_csv_module(): csv.register_dialect('tabs', delimiter = '\t')
def init_csv_module(): csv.register_dialect('tabs', delimiter = '\t')
'save-filename-pattern': 'exam-%%03d.png',
'save-filename-pattern': 'exam-{student-id}-{seq-number}.png',
def read_config(): config = {'camera-dev': '-1', 'save-filename-pattern': 'exam-%%03d.png', 'csv-dialect': 'excel'} parser = ConfigParser.SafeConfigParser() parser.read([os.path.expanduser('~/.camgrade.cfg')]) if 'default' in parser.sections(): for option in parser.options('default'): config[option] = parser.get('defau...
init_csv_module()
def main(): init_csv_module() options = read_cmd_options() config = read_config() save_pattern = config['save-filename-pattern'] if options.ex_data_filename is not None: solutions, dimensions, id_num_digits = \ process_exam_data(options.ex_data_filename) else: solutions = [] dimensions = [] id_num_digits = 0 read_id =...
self.width = 0.8
self.width = 1
def __init__(self): PlotInfo.__init__(self, "clustered bar") self.bars = [] self.spacing = 0 self.width = 0.8
bar.width = self.width
def add(self, bar): if not isinstance(bar, Bar) and not isinstance(bar, StackedBars): print >>sys.stderr, "Can only add Bars to a ClusteredBars" sys.exit(1) self.bars.append(bar)
labelLocations.append((clusterWidth + self.spacing) * x +\ clusterWidth / 2.0)
labelLocations.append((clusterWidth + self.spacing) * float(x) - (self.width / 2.0) + clusterWidth / 2.0)
def getXLabelLocations(self): labelLocations = [] clusterWidth = sum([bar.width for bar in self.bars])
xMin = min(xVals)
xMin = min(xVals) - self.width
def draw(self, axis): if self.xTickLabels is not None: self.xTickLabelPoints = self.getXLabelLocations() if len(self.xTickLabelPoints) != len(self.xTickLabels): print >>sys.stderr, "Number of clustered bar labels doesn't match number of points" print >>sys.stderr, "Labels: %s" % (self.xTickLabels) print >>sys.stderr, "...
xMin = min(xMin, min(xVals))
xMin = min(xMin, min(xVals) - self.width)
def draw(self, axis): if self.xTickLabels is not None: self.xTickLabelPoints = self.getXLabelLocations() if len(self.xTickLabelPoints) != len(self.xTickLabels): print >>sys.stderr, "Number of clustered bar labels doesn't match number of points" print >>sys.stderr, "Labels: %s" % (self.xTickLabels) print >>sys.stderr, "...
axis.set_xticks(range(len(self.xTickLabels)))
axis.set_xticks(self.xValues[0:len(self.xTickLabels)])
def draw(self, axis): if len(self.xValues) > 0 and self.autosort: zipped = zip(self.xValues, self.yValues) zipped.sort() self.xValues, self.yValues = zip(*zipped) if self.xTickLabels is not None: if self.xTickLabelPoints is None: axis.set_xticks(range(len(self.xTickLabels))) else: axis.set_xticks(self.xTickLabelPoints...
axis.set_yticks(range(len(self.yTickLabels)))
axis.set_yticks(self.yValues[0:len(self.yTickLabels)])
def draw(self, axis): if len(self.xValues) > 0 and self.autosort: zipped = zip(self.xValues, self.yValues) zipped.sort() self.xValues, self.yValues = zip(*zipped) if self.xTickLabels is not None: if self.xTickLabelPoints is None: axis.set_xticks(range(len(self.xTickLabels))) else: axis.set_xticks(self.xTickLabelPoints...
bar.width = self.width
def add(self, bar): if not isinstance(bar, Bar): print >>sys.stderr, "Can only add Bars to a StackedBars" sys.exit(1) if len(self.bars) == 0: # Fake having xValues self.xValues = bar.xValues self.yValues = bar.yValues
return [i + self.width / 2.0 for i in xrange(numBarVals)]
return range(numBarVals)
def getXLabelLocations(self): if len(self.bars) == 0: return [] else: numBarVals = len(self.bars[0].xValues) return [i + self.width / 2.0 for i in xrange(numBarVals)]
index = random.randint(int(first)+1,int(currentMax))
index = random.randint(int(first)+1,int(currentMax)-1)
def requestDC(number): log('requestDC') global ingestCount global first global auth global requestDCHTTP pids = [] cv.acquire() currentMax = ingestCount cv.release() request = requestDCHTTP for i in range(0,int(number)) : #todo something about seed index = random.randint(int(first)+1,int(currentMax)) log("requesting...
pids.append(pid)
def requestDC(number): log('requestDC') global ingestCount global first global auth global requestDCHTTP pids = [] cv.acquire() currentMax = ingestCount cv.release() request = requestDCHTTP for i in range(0,int(number)) : #todo something about seed index = random.randint(int(first)+1,int(currentMax)) log("requesting...
def addRel(pids): global auth log("adding rel")
def modifyDefensively(targetIN,rdf,auth): attempts = 0 log("modifying object defensively") while (attempts<5): result = HTTPRequest().PUT(targetIN,rdf,[auth]) status = result.getStatusCode() if status >= 200 and status < 300: break else: log("failed attempt "+str(attempts)) grinder.sleep(1000) attempts = attempts+1 st...
def requestDC(number): log('requestDC') global ingestCount global first global auth global requestDCHTTP pids = [] cv.acquire() currentMax = ingestCount cv.release() request = requestDCHTTP for i in range(0,int(number)) : #todo something about seed index = random.randint(int(first)+1,int(currentMax)) log("requesting...
targetOUT = SERVER + '/objects/' + pid + '/datastreams/MY-RELS-EXT/content'
def addRel(pids): global auth log("adding rel") index = random.randint(1,len(pids)) pid = pids[index-1] log("adding rel to " + pid) targetOUT = SERVER + '/objects/' + pid + '/datastreams/MY-RELS-EXT/content' targetIN = SERVER + '/objects/' + pid + '/datastreams/MY-RELS-EXT' result = requestRELSEXT.GET(targetOUT,[auth]...
result = requestRELSEXT.GET(targetOUT,[auth])
def addRel(pids): global auth log("adding rel") index = random.randint(1,len(pids)) pid = pids[index-1] log("adding rel to " + pid) targetOUT = SERVER + '/objects/' + pid + '/datastreams/MY-RELS-EXT/content' targetIN = SERVER + '/objects/' + pid + '/datastreams/MY-RELS-EXT' result = requestRELSEXT.GET(targetOUT,[auth]...
result = modifyDatastreamHTTP.PUT(targetIN,rdf,[auth])
modifyDatastreamHTTP(targetIN,rdf,auth)
def addRel(pids): global auth log("adding rel") index = random.randint(1,len(pids)) pid = pids[index-1] log("adding rel to " + pid) targetOUT = SERVER + '/objects/' + pid + '/datastreams/MY-RELS-EXT/content' targetIN = SERVER + '/objects/' + pid + '/datastreams/MY-RELS-EXT' result = requestRELSEXT.GET(targetOUT,[auth]...
print "TesttRunner created" pid = establishFirst() number = pid.replace(PIDPREFIX,"") first = number print "found "+first+" as the first nonused pid"
log("TestRunner created") startingpid = grinder.getProperties().getProperty('firstpid') if (startingpid is not None and startingpid > 0): first = startingpid else: pid = establishFirst() number = pid.replace(PIDPREFIX,"") first = number log("found "+first+" as the first nonused pid")
def __init__(self): global first print "TesttRunner created" pid = establishFirst() number = pid.replace(PIDPREFIX,"") first = number print "found "+first+" as the first nonused pid" self.initialisationTime = System.currentTimeMillis()
display.file = os.path.join(imagepath, display.filename)
display.file = os.path.join(imagepath, display.filename).replace('\\', '\\\\')
def maintain_display_drivers(current_pass, scene): path = getdefaultribpath(scene) rmansettings = scene.renderman_settings shad = rmansettings.defaultshadow deep = rmansettings.deepdisplay quant_presets = { "8bit" : [0, 255, 0, 255], "16bit" : [0, 65535, 0, 65535], "32bit" : [0, 0, 0, 0] } for display in current_pa...
searchpath_option.textparameter = value
searchpath_option.textparameter = value.replace('\\', '\\\\')
def maintain_searchpath(name, value): if not name in master_searchpath: master_searchpath.add().name = name searchpath_option = master_searchpath[name] searchpath_option.export = True searchpath_option.parametertype = "string" searchpath_option.textparameter = value maintain_options(current_pass, scene) try: slave_sea...
texpath = os.path.join(getdefaultribpath(scene), rmansettings.texdir).replace('\\', '/') shadowpath = os.path.join(getdefaultribpath(scene), rmansettings.shadowdir).replace('\\', '/') envpath = os.path.join(getdefaultribpath(scene), rmansettings.envdir).replace('\\', '/') maintain_searchpath('texture', texpath+':'+shad...
texpath = os.path.join(getdefaultribpath(scene), rmansettings.texdir) shadowpath = os.path.join(getdefaultribpath(scene), rmansettings.shadowdir) envpath = os.path.join(getdefaultribpath(scene), rmansettings.envdir) maintain_searchpath('texture', texpath+':'+shadowpath+':'+envpath)
def maintain_searchpath(name, value): if not name in master_searchpath: master_searchpath.add().name = name searchpath_option = master_searchpath[name] searchpath_option.export = True searchpath_option.parametertype = "string" searchpath_option.textparameter = value maintain_options(current_pass, scene) try: slave_sea...
maintain_searchpath('shader', shader_path_value.replace('\\', '/'))
maintain_searchpath('shader', shader_path_value)
def maintain_searchpath(name, value): if not name in master_searchpath: master_searchpath.add().name = name searchpath_option = master_searchpath[name] searchpath_option.export = True searchpath_option.parametertype = "string" searchpath_option.textparameter = value maintain_options(current_pass, scene) try: slave_sea...
string = os.path.join(getdefaultribpath(scene), texture.name+framepadding(scene)+".bake").replace('\\', '/')
string = os.path.join(getdefaultribpath(scene), texture.name+framepadding(scene)+".bake").replace('\\', '\\\\')
def writeparms(path, write, scene): for parm in path: name = parm.name if name.find('[') != -1: name = name[:name.find('[')] if parm.export: if parm.parametertype == 'string': if parm.texture: texture = bpy.data.textures[parm.textparameter] if texture.renderman.type == 'bake': string = os.path.join(getdefaultribpath(sc...
tx = prepared_texture_file(texture.image.filepath, scene).replace('\\', '/')
tx = prepared_texture_file(texture.image.filepath, scene).replace('\\', '\\\\')
def writeshaderparameter(parameterlist, write, scene): for parm in parameterlist: if parm.parametertype == 'string': if parm.texture: if parm.texture != "" and parm.textparameter in bpy.data.textures: texture = bpy.data.textures[parm.textparameter] if texture.renderman.type == "file": image = texture.image if image.sou...
tx = os.path.join(getdefaultribpath(scene), texture.name+framepadding(scene)+".bake").replace('\\', '/')
tx = os.path.join(getdefaultribpath(scene), texture.name+framepadding(scene)+".bake").replace('\\', '\\\\')
def writeshaderparameter(parameterlist, write, scene): for parm in parameterlist: if parm.parametertype == 'string': if parm.texture: if parm.texture != "" and parm.textparameter in bpy.data.textures: texture = bpy.data.textures[parm.textparameter] if texture.renderman.type == "file": image = texture.image if image.sou...
write('\n')
def writeSettings(current_pass, write, scene, dir = ""): print("write Scene Settings ...") render = scene.render path = scene.renderman_settings.ribpath if not current_pass.displaydrivers: nodisplay = True else: nodisplay = False if current_pass.name == "Beauty" and not current_pass.displaydrivers: adddisp(current_p...
return 'ReadArchive "'+matfilepath+'"\n'.replace('\\', '/')
return 'ReadArchive "'+matfilepath+'"\n'
def matblur(function, args=[]): sampletime = [] motion_samples = mat.renderman[current_pass.name].motion_samples current_frame = scene.frame_current shutterspeed, sampletime = motionblur(motion_samples, current_pass, scene) if current_pass.motionblur: write('MotionBegin[') for s in sampletime: write(str(s)+' ') write(...
for psystem in obj.particle_systems: if psystem.settings.type == 'EMITTER': filename = obj.name+'_'+psystem.name+framepadding(scene)+'.rib' particle_dir = os.path.join(getdefaultribpath(scene), rmansettings.particledir)
if len(obj.particle_systems) > 0: for psystem in obj.particle_systems: if psystem.settings.type == 'EMITTER': filename = obj.name+'_'+psystem.name+framepadding(scene)+'.rib' particle_dir = os.path.join(getdefaultribpath(scene), rmansettings.particledir) if not os.path.exists(particle_dir): os.mkdir(particle_dir) path...
def writeParticles(path, obj, current_pass, write, scene): rmansettings = scene.renderman_settings pfiles = [] for psystem in obj.particle_systems: if psystem.settings.type == 'EMITTER': filename = obj.name+'_'+psystem.name+framepadding(scene)+'.rib' particle_dir = os.path.join(getdefaultribpath(scene), rmansettings.p...
if not os.path.exists(particle_dir): os.mkdir(particle_dir) path = os.path.join(particle_dir, filename) pfiles.append(path) file = open(path, "w") pwrite = file.write pwrite('Points\n') pwrite('"P" [') for part in psystem.particles: rotation = part.rotation.to_euler() rotx = str(math.degrees(rotation[0])) roty = st...
write('AttributeEnd\n')
def writeParticles(path, obj, current_pass, write, scene): rmansettings = scene.renderman_settings pfiles = [] for psystem in obj.particle_systems: if psystem.settings.type == 'EMITTER': filename = obj.name+'_'+psystem.name+framepadding(scene)+'.rib' particle_dir = os.path.join(getdefaultribpath(scene), rmansettings.p...
if mat: write(writeMaterial(mat, path, current_pass, scene))
if mat: write(writeMaterial(mat, path, current_pass, scene).replace('\\', '\\\\'))
def writeObject(path, obj, current_pass, write, scene): if obj.type == 'MESH': if check_visible(obj, scene): print("write "+obj.name) mat = obj.active_material write("\nAttributeBegin\n") write('Attribute "identifier" "name" ["'+obj.name+'"]\n') write_attrs_or_opts(obj.renderman[current_pass.name].attribute_groups, w...
write('ReadArchive "'+fullpath.replace('\\', '/')+'"\n')
write('ReadArchive "'+fullpath.replace('\\', '\\\\')+'"\n')
def export_object(obj, current_pass, path, write, scene, type = "ReadArchive"): if type == 'ObjectInstance': inst = True else: inst = False if inst: global exported_instances if obj.data.name in exported_instances: return 0 exported_instances.append(obj.data.name) write('ObjectBegin "'+obj.data.name+'"\n') ##deforma...
write('DelayedReadArchive "'+fullpath.replace('\\', '/')+'" [')
write('DelayedReadArchive "'+fullpath.replace('\\', '\\\\')+'" [')
def export_object(obj, current_pass, path, write, scene, type = "ReadArchive"): if type == 'ObjectInstance': inst = True else: inst = False if inst: global exported_instances if obj.data.name in exported_instances: return 0 exported_instances.append(obj.data.name) write('ObjectBegin "'+obj.data.name+'"\n') ##deforma...
def export(current_pass, path, rhandle, scene):
def export(current_pass, path, scene):
def export(current_pass, path, rhandle, scene): degrees = math.degrees if current_pass.environment: camera = scene.objects[current_pass.camera_object] envrots = [[180, 90, 180], [180, -90, 180], [90, -180, 180], [-90, -180, 180], [0, 0, 0], [0, 180, 0]]
process_envmap(current_pass, fov, rhandle, scene)
process_envmap(current_pass, fov, scene)
def export(current_pass, path, rhandle, scene): degrees = math.degrees if current_pass.environment: camera = scene.objects[current_pass.camera_object] envrots = [[180, 90, 180], [180, -90, 180], [90, -180, 180], [-90, -180, 180], [0, 0, 0], [0, 180, 0]]
def process_envmap(current_pass, fov, rhandle, scene):
def process_envmap(current_pass, fov, scene):
def process_envmap(current_pass, fov, rhandle, scene): envdirections = ["_px", "_nx", "_py", "_ny", "_pz", "_nz"] envfile = current_pass.displaydrivers[0].file textool = scene.renderman_settings.textureexec envtx = bpy.data.textures[current_pass.envname].renderman width = envtx.width swidth = envtx.swidth twidth = envt...
scene.frame_current = i render()
scene.frame_set(i) render(scene)
def invoke(self, context, event): scene = context.scene path = getdefaultribpath(scene) checkpaths(path) checkpaths(os.path.join(path, scene.renderman_settings.polydir)) checkpaths(os.path.join(path, scene.renderman_settings.shadowdir)) checkpaths(os.path.join(path, scene.renderman_settings.envdir)) checkpaths(os.path....
render()
render(scene)
def invoke(self, context, event): scene = context.scene path = getdefaultribpath(scene) checkpaths(path) checkpaths(os.path.join(path, scene.renderman_settings.polydir)) checkpaths(os.path.join(path, scene.renderman_settings.shadowdir)) checkpaths(os.path.join(path, scene.renderman_settings.envdir)) checkpaths(os.path....
def image(name): return name.replace("[frame]", framepadding()) def start_render(render, ribfile, current_pass, rhandle, scene):
def image(name, scene): return name.replace("[frame]", framepadding(scene)) def start_render(render, ribfile, current_pass, scene):
def image(name): return name.replace("[frame]", framepadding())
img = image(disp.file)
img = image(disp.file, scene)
def start_render(render, ribfile, current_pass, rhandle, scene): r = scene.render x = int(r.resolution_x * r.resolution_percentage * 0.01) y = int(r.resolution_y * r.resolution_percentage * 0.01)
def render(rhandle, scene):
def render(scene):
def render(rhandle, scene): rndr = scene.renderman_settings.renderexec if rndr != "": maintain(scene) path = getdefaultribpath(scene) active_pass = getactivepass(scene)
export(item, path, rhandle, scene)
export(item, path, scene)
def render(rhandle, scene): rndr = scene.renderman_settings.renderexec if rndr != "": maintain(scene) path = getdefaultribpath(scene) active_pass = getactivepass(scene)