示例#1
0
def get_dims(lines):
    idx, width_line = utils.find_line(lines, 'parameter DATA_WIDTH')
    idx, depth_line = utils.find_line(lines, 'parameter DEPTH')
    w_match = re.search('d(\d+);', width_line)
    d_match = re.search('d(\d+);', depth_line)
    if w_match is None:
        raise Exception('Could not determine shift reg width.')
    if d_match is None:
        raise Exception('Could not determine shift reg depth.')
    width = int(w_match.group(1))
    depth = int(d_match.group(1))
    return width, depth
示例#2
0
def process_shiftreg_file(ifname, ofname):
    # Read the file and get the dimensions
    lines = []
    with open(ifname, 'r') as f:
        lines = f.readlines()
    width, depth = get_dims(lines)

    # Fix the declaration of the shift register signals
    # Find the reg ... SRL_SIG line
    srl_sig_pattern = r'reg.*SRL_SIG'
    srl_sig_idx, srl_sig_line = utils.find_line(lines, srl_sig_pattern)
    # Declare a separate register for each element
    regs = [('sr_%d' % d) for d in range(depth)]
    # Replace it with this:
    srl_dec = 'reg[DATA_WIDTH-1:0] ' + ', '.join(regs) + ';\n'
    lines[srl_sig_idx] = srl_dec

    # Fix the assignments of the elements in the shift register.
    # Find the line that begins the for loop
    forloop_idx, forloop_line = utils.find_line(lines, r'for \(i=0')
    # Empty the next two lines
    lines[forloop_idx + 1] = '\n'
    lines[forloop_idx + 2] = '\n'
    # Create the assignments
    s = ' ' * 12
    assignments = s + 'sr_0 <= data;\n'
    for d in range(depth):
        if (d == 0):
            continue
        assignments += s + ('sr_%d' % d) + ' <= ' + ('sr_%d' % (d - 1)) + ';\n'
    # Put in the assignments
    lines[forloop_idx] = assignments

    # Fix the output data
    # Find the line that assigns q
    qassign_idx, qassign_line = utils.find_line(lines, 'assign q')
    # Build the always block with the case statement.
    alen = math.ceil(math.log2(depth))
    q_block = 'always @( ' + ', '.join(regs) + ', a) begin\n'
    q_block += '   case (a)\n'
    for d in range(depth):
        q_block += (' ' * 6) + ("%d'd%d" %
                                (alen, d)) + ': q = ' + regs[d] + ';\n'
    q_block += (' ' * 6) + ('default: q = sr_%d;\n' % (depth - 1))
    q_block += '   endcase\n'
    q_block += 'end\n'
    # Put in the new assignment code
    lines[qassign_idx] = q_block

    # Write the output
    with open(ofname, 'w') as of:
        of.writelines(lines)
示例#3
0
def processing(img, object_points, img_points, M, Minv, left_line, right_line):
    #camera calibration, image distortion correction
    undist = utils.cal_undistort(img, object_points, img_points)
    #get the thresholded binary image
    thresholded = thresholding(undist)
    #perform perspective  transform
    thresholded_wraped = cv2.warpPerspective(thresholded,
                                             M,
                                             img.shape[1::-1],
                                             flags=cv2.INTER_LINEAR)

    #perform detection
    if left_line.detected and right_line.detected:
        left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line_by_previous(
            thresholded_wraped, left_line.current_fit, right_line.current_fit)
    else:
        left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line(
            thresholded_wraped)
    left_line.update(left_fit)
    right_line.update(right_fit)

    #draw the detected laneline and the information
    area_img = utils.draw_area(undist, thresholded_wraped, Minv, left_fit,
                               right_fit)
    curvature, pos_from_center = utils.calculate_curv_and_pos(
        thresholded_wraped, left_fit, right_fit)
    result = utils.draw_values(area_img, curvature, pos_from_center)

    return result
def get_face_direction(region_skin_image, m, n, tempX, tempY, border, eye1, eye2, pivot):
	'''based on nose and mouth'''
	line = ut.find_line(eye1, eye2)
	
	farthestPoint = ut.find_the_farthest_point(line, border)
	specialVector = [farthestPoint[0] - point[0], farthestPoint[1] - point[1]]

	perpendicularVector = [eye1[1] - eye2[1], eye2[0] - eye1[0]]
	if (ut.find_angle_between_two_vectors(perpendicularVector, specialVector) < 90):
		return perpendicularVector
	return [eye2[1] - eye1[1], eye1[0] - eye2[0]]
示例#5
0
	def on_opt_btn_clicked(self,action,name):
		if name == "OK":
			pn = self.notebook.get_current_page()
			if pn != -1:
				doc = self.das[pn]
				doff = int(self.options_off,16)
				dlen = int(self.options_len,16)
				lnum = utils.find_line(doc,doff)
				self.expwin.destroy()
				utils.html_export(self,doc,lnum,doff,dlen)
		else:
			self.expwin.destroy()
示例#6
0
	def on_opt_btn_clicked(self,action,name):
		if name == "OK":
			pn = self.notebook.get_current_page()
			if pn != -1:
				doc = self.das[pn]
				doff = int(self.options_off,16)
				dlen = int(self.options_len,16)
				lnum = utils.find_line(doc,doff)
				self.expwin.destroy()
				utils.html_export(self,doc,lnum,doff,dlen)
		else:
			self.expwin.destroy()
示例#7
0
def sort_ships(front_list, back_list, sub_list, preset_list):
    global ship_dict
    # Filter by line
    clear_boxes(front_list, back_list, sub_list, preset_list, False)
    (backline, frontline, subline) = utils.find_line(ship_dict)

    # Sort by selected stat
    # TODO maybe parallelize
    backline = utils.sort_ships(backline, back_list.SortList.get_selected())
    frontline = utils.sort_ships(frontline, front_list.SortList.get_selected())
    subline = utils.sort_ships(subline, sub_list.SortList.get_selected())

    # Get filters
    back_filters = back_list.FilterList.get_filters()
    front_filters = front_list.FilterList.get_filters()
    sub_filters = sub_list.FilterList.get_filters()

    # loop through filters and apply filters
    for i in back_filters[0].keys():
        backline = utils.filter_ships_ui(backline, i, back_filters)
    for i in front_filters[0].keys():
        frontline = utils.filter_ships_ui(frontline, i, front_filters)
    for i in sub_filters[0].keys():
        subline = utils.filter_ships_ui(subline, i, sub_filters)

    # Create the lists
    (back, front, oil, sub,
     suboil) = utils.create_line(backline, frontline, subline, preset_ships,
                                 True)

    # Add names to the list
    (back_images, back_names) = prepare_for_update(back)
    t1 = threading.Thread(target=back_list.update_pics,
                          args=(back_images, back_names))

    (front_images, front_names) = prepare_for_update(front)
    t2 = threading.Thread(target=front_list.update_pics,
                          args=(front_images, front_names))

    (sub_images, sub_names) = prepare_for_update(sub)
    t3 = threading.Thread(target=sub_list.update_pics,
                          args=(sub_images, sub_names))
    t1.start()
    t2.start()
    t3.start()

    t1.join()
    t2.join()
    t3.join()
示例#8
0
def menu2():
    """ Menu that sorts our data however we like to our top 3 for front and back"""
    global ship_dict
    # Split dictionary into backline and frontline
    (backline, frontline, subline) = utils.find_line(ship_dict)
    # Sort by respective stat
    stat = input('Enter the stat you would like to sort the backline by: ')
    print("Sorting by " + stat)
    new_backline = utils.sort_ships(backline, stat)
    new_backline = filter_menu(new_backline)

    stat = input('Enter the stat you would like to sort the frontline by: ')
    print("Sorting by " + stat)
    new_frontline = utils.sort_ships(frontline, stat)
    new_frontline = filter_menu(new_frontline)

    stat = input('Enter the stat you would like to sort the subline by: ')
    print("Sorting by " + stat)
    new_subline = utils.sort_ships(subline, stat)
    new_subline = filter_menu(new_subline)

    if new_backline == None or new_frontline == None:
        print("Empty line")
        # TODO maybe a delay
        menu_actions['main']()

    # Allow user to add ships if they want to
    preset_names = []
    test = "Y"
    while (test == 'Y'):
        name_choice = input('Name of Ship to add by default to line: ')
        if (name_choice == 'N/A' or name_choice == ""):
            break
        else:
            # TODO I can do index here, right?
            for ship in ship_dict:
                # check for the name
                if ship["Name"] == name_choice:
                    preset_names.append(ship)
                    break
            test = input('Would you like to add another? (Y/N): ')

    # Pass it all in and create the lineup
    utils.create_line(new_backline, new_frontline, new_subline, preset_names)

    choice = input("Enter 0 to exit or main for main menu: ")
    exec_menu(choice)
    return
示例#9
0
def processing(img, object_points, img_points, M, Minv, left_line, right_line):
    undist = utils.cal_undistort(img, object_points, img_points)
    thresholded = thresholding(undist)
    thresholded_wraped = cv2.warpPerspective(thresholded,
                                             M,
                                             img.shape[1::-1],
                                             flags=cv2.INTER_LINEAR)
    if left_line.detected and right_line.detected:
        left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line_by_previous(
            thresholded_wraped, left_line.current_fit, right_line.current_fit)
    else:
        left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line(
            thresholded_wraped)
    left_line.update(left_fit)
    right_line.update(right_fit)

    area_img = utils.draw_area(undist, thresholded_wraped, Minv, left_fit,
                               right_fit)

    curvature, pos_from_center = utils.calculate_curv_and_pos(
        thresholded_wraped, left_fit, right_fit)
    result = utils.draw_values(area_img, curvature, pos_from_center)
    return result
示例#10
0
def processing(img, M, Minv, left_line, right_line):
    prev_time = time.time()
    img = Image.fromarray(img)
    undist = img
    #get the thresholded binary image
    img = np.array(img)
    blur_img = cv2.GaussianBlur(img, (3, 3), 0)
    Sobel_x_thresh = utils.abs_sobel_thresh(blur_img,
                                            orient='x',
                                            thresh_min=90,
                                            thresh_max=255)
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    dilated = cv2.dilate(Sobel_x_thresh, kernel, iterations=2)
    #perform perspective  transform
    thresholded_wraped = cv2.warpPerspective(dilated,
                                             M,
                                             img.shape[1::-1],
                                             flags=cv2.INTER_LINEAR)
    #perform detection
    if left_line.detected and right_line.detected:
        left_fit, right_fit = utils.find_line_by_previous(
            thresholded_wraped, left_line.current_fit, right_line.current_fit)
    else:
        left_fit, right_fit = utils.find_line(thresholded_wraped)
    left_line.update(left_fit)
    right_line.update(right_fit)
    # #draw the detected laneline and the information
    undist = Image.fromarray(img)
    area_img = utils.draw_area(undist, thresholded_wraped, Minv, left_fit,
                               right_fit)
    area_img = np.array(area_img)
    curr_time = time.time()
    exec_time = curr_time - prev_time
    info = "time: %.2f ms" % (1000 * exec_time)
    print(info)
    return area_img, thresholded_wraped
示例#11
0
def processing(img, M, Minv, left_line, right_line):
    #img = RotateClockWise90(img)
    #img = np.rot90(img)
    prev_time = time.time()
    img = Image.fromarray(img)
    undist = img
    #get the thresholded binary image
    img = np.array(img)
    thresholded = thresholding(img)
    #perform perspective  transform
    thresholded_wraped = cv2.warpPerspective(thresholded,
                                             M,
                                             img.shape[1::-1],
                                             flags=cv2.INTER_LINEAR)
    #perform detection
    if left_line.detected and right_line.detected:
        left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line_by_previous(
            thresholded_wraped, left_line.current_fit, right_line.current_fit)
    else:
        left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line(
            thresholded_wraped)
    left_line.update(left_fit)
    right_line.update(right_fit)
    # #draw the detected laneline and the information
    undist = Image.fromarray(img)
    area_img, gre1 = utils.draw_area(undist, thresholded_wraped, Minv,
                                     left_fit, right_fit)
    curvature, pos_from_center = utils.calculate_curv_and_pos(
        thresholded_wraped, left_fit, right_fit)
    area_img = np.array(area_img)
    result = utils.draw_values(area_img, curvature, pos_from_center)
    curr_time = time.time()
    exec_time = curr_time - prev_time
    info = "time: %.2f ms" % (1000 * exec_time)
    print(info)
    return result, thresholded_wraped
示例#12
0
	def on_entry_activate (self,action,cmdline=""):
		if cmdline == "":
			cmdline = self.entry.get_text()
		if len(cmdline) > 0:
			if self.curcmd == -1 or self.cmdhistory[self.curcmd] != cmdline:
				self.cmdhistory.append(cmdline)
				self.curcmd = -1
			pn = self.notebook.get_current_page()
			data = ''
			if pn != -1:
				# try to take current selection
				doc = self.das[pn]
				if doc.sel:
						r1,c1,r2,c2 = doc.sel
						data = doc.data[doc.lines[r1][0]+c1:doc.lines[r2][0]+c2]
				cmd = cmdline.split()
				doc.bklines = []
				doc.bkhvlines = []
				doc.bklines += doc.lines
				doc.bkhvlines += doc.hvlines

				if cmd[0].lower() == "name" and len(cmd) > 1:
					ebox = self.notebook.get_tab_label(doc.table)
					ebox.get_children()[0].set_text(cmd[1])
				elif cmd[0].lower() == "bck":
					pass
				elif cmd[0].lower() == "reload":
					exec("reload(%s)"%(cmd[1]))
				elif cmdline[:3].lower() == "run":
					hv = doc
					if len(cmdline) < 5:
						self.open_cli()
						cmdline = ""
					else:
						cmdline = cmdline[4:]
						exec(cmdline)
						hv.expose(None,None)
				elif cmd[0].lower() == "fmt":
					cmd = cmd[1:]
					mpos = cmdline.find("*")
					curpos = doc.lines[doc.curr][0]
					if mpos == -1:
						# wrap lines starting from current to provided lengths
						cmdacc = 0
						for k in cmd:
							cmdacc += int(k)
							if cmdacc + curpos > len(doc.data):
								cmd = cmd[:k]
								break
						doc.fmt_row(doc.curr,cmd)
						lrow = doc.curr+len(cmd)

					elif mpos == len(cmdline)-1:
						# repeat wrapping till end
						print("Rpt to end")
						cmd = cmdline[4:mpos].split()
						cmdacc = 0
						rpt = 0
						for k in cmd:
							cmdacc += int(k)
							if cmdacc + curpos > len(doc.data):
								cmd = cmd[:k]
								rpt = 1
								break
						if rpt == 0:
							rpt = 1+(doc.lines[len(doc.lines)-1][0]-doc.lines[doc.curr][0])/cmdacc
						for i in range(rpt):
							doc.fmt_row(doc.curr+i*len(cmd),cmd)

						lrow = doc.curr+i*len(cmd)
						
					else:
						cmd = cmdline[4:mpos].split()
						rpt = int(cmdline[mpos+1:].strip())
						cmdacc = 0
						for k in cmd:
							cmdacc += int(k)
							if cmdacc + curpos > len(doc.data):
								cmd = cmd[:k]
								rpt = 1
								break
								
						if cmdacc*rpt > doc.lines[len(doc.lines)-1][0]-doc.lines[doc.curr][0]:
							rpt = 1+(doc.lines[len(doc.lines)-1][0]-doc.lines[doc.curr][0])/cmdacc

						#repeat wrapping last arg times
						print("Rpt",rpt,"times",cmd)
						for i in range(rpt):
							doc.fmt_row(doc.curr+i*len(cmd),cmd)

						lrow = doc.curr+i*len(cmd)+1

					doc.hvlines[lrow] = ""
					doc.set_maxaddr()
					doc.expose(None,None)

				elif cmd[0].lower() == "goto":
					addr = 0
					addrflag = 0
					if len(cmd) > 1:
						try:
							goto = cmdline[4:]
							pos = goto.find("+")
							if pos != -1:
								if pos == 1:
									addr = doc.lines[doc.curr][0]+doc.curc+int(goto[pos+1:],16)
									addrflag = 1
								else:
									addr = int(goto[1:pos],16)+int(goto[pos+1:],16)
							else:
								pos = goto.find("-")
								if pos != -1:
									if pos == 1:
										addr = doc.lines[doc.curr][0]+doc.curc-int(goto[pos+1:],16)
										addrflag = 1
									else:
										addr = int(goto[1:pos],16)-int(goto[pos+1:],16)
								else:
									addr = int(goto[1:], 16)
							print("Addr: ",addr)
						except:
							print("Wrong string for Hex address")
					elif doc.sel:
						if len(data) <4:
							dstr = data + "\x00"*(4-len(data[:4]))
						else:
							dstr = data[:4]
						addr = struct.unpack("<I",dstr)
						print("Addr sel: %04x"%addr)
					
					# try to validate/scroll
					llast = len(doc.lines)
					if addr < doc.lines[len(doc.lines)-1][0]:
						lnum = utils.find_line(doc,addr)
						print("Lnum found",lnum,"%x %x"%(doc.lines[lnum][0],doc.lines[lnum+1][0]))
						if addrflag == 0:
							self.entry.set_text("goto %x"%addr)
						doc.curr = lnum
						doc.curc = addr - doc.lines[lnum][0]
						doc.offnum = min(lnum,llast-doc.numtl)
						doc.offset = doc.lines[lnum][0]

					else:
						print("Address after end of file")
						doc.offnum = llast-doc.numtl
						doc.offset = doc.lines[llast-1][0]
					doc.vadj.value = doc.offnum
					doc.expose(doc.hv,action)
				elif cmdline[0] == "?":
					utils.cmd_parse(cmdline,self,doc)
				elif cmdline[0] == "!":
					# off;len;text
					cmd = cmdline[1:].split(";")
					if len(cmd) < 3:
						# add comment to selection or cursor
						if doc.cursor_in_sel():
							rs,cs,re,ce = doc.sel
							clen = doc.get_sel_len()
						else:
							rs = doc.curr
							cs = doc.curc
							clen = 1
						text = cmdline[1:]
						off = doc.lines[rs][0]+cs+1
					else:
						text = ";".join(cmd[2:])
						off = int(cmd[0],16)+1
						clen = int(cmd[1],16)
					try:
						doc.insert_comment2(text,off,clen)
						doc.expose(doc.hv,action)
					except:
						print("Wrong args",sys.exc_info())
				elif cmdline.lower() == "dump":
					fname = self.file_open('Save',None,gtk.FILE_CHOOSER_ACTION_SAVE)
					if fname:
						f = open(fname,'wb')
						f.write(doc.data)
						f.close()
					else:
						print("Nothing to save")
				elif cmd[0].lower() == "html":
					off = -1
					try:
						off = int(cmd[1],16)
						clen = int(cmd[2],16)
						lnum = 0
						if off < len(doc.data):
							lnum = utils.find_line(doc,off)
							addr = doc.lines[lnum]
							if addr < off:
								clen += off - addr
					except:
						print("Something wrong with arguments",sys.exc_info())
					if off == -1:
						lnum = 0
						clen = len(doc.data)
					utils.html_export(self,doc,lnum,off,clen)
				elif cmdline[0] == "/":
					if len(cmdline) > 1:
						pos1 = cmdline.find("+")
						pos2 = cmdline.find("-")
						if pos1 != -1 or pos2 != -1:
							pos = max(pos1,pos2)
							try:
								arg1 = int(cmdline[1:pos],16)
								arg2 = int(cmdline[pos+1:],16)
								if pos1 != -1:
									addr = arg1+arg2
									self.entry.set_text("/%x+%x"%(addr,arg2))
								else:
									addr = arg1-arg2
									self.entry.set_text("/%x-%x"%(addr,arg2))
								lnum = utils.find_line (doc,addr)
								cnum = addr - doc.lines[lnum][0]
							except:
								print("Invalid offset")
						else:
							arg = cmdline[1:]
							try:
								addr = int(arg,16)
								lnum = utils.find_line (doc,addr)
								cnum = addr - doc.lines[lnum][0]
							except:
								print("Invalid offset")
					else:
						lnum = doc.curr
						cnum = doc.curc
					if lnum > 0:
						if cnum > 0:
							doc.fmt(lnum,[cnum])
							lnum += 1
							doc.curr = lnum
							doc.curc = 0
						s = (doc.lines[lnum-1][1]+1)%4
						doc.lines[lnum-1] = (doc.lines[lnum-1][0],s)
						# scroll down if went below screen
						if lnum > doc.offnum+doc.numtl-3:
							doc.offnum += doc.numtl/2
						# scroll up if went above screen
						if lnum < doc.offnum:
							doc.offnum = lnum
						doc.expose(None,None)
示例#13
0
	def on_entry_activate (self,action,cmdline=""):
		if cmdline == "":
			cmdline = self.entry.get_text()
		if len(cmdline) > 0:
			if self.curcmd == -1 or self.cmdhistory[self.curcmd] != cmdline:
				self.cmdhistory.append(cmdline)
				self.curcmd = -1
			pn = self.notebook.get_current_page()
			data = ''
			if pn != -1:
				# try to take current selection
				doc = self.das[pn]
				if doc.sel:
						r1,c1,r2,c2 = doc.sel
						data = doc.data[doc.lines[r1][0]+c1:doc.lines[r2][0]+c2]
				cmd = cmdline.split()
				doc.bklines = []
				doc.bkhvlines = []
				doc.bklines += doc.lines
				doc.bkhvlines += doc.hvlines

				if cmd[0].lower() == "name" and len(cmd) > 1:
					ebox = self.notebook.get_tab_label(doc.table)
					ebox.get_children()[0].set_text(cmd[1])
				elif cmd[0].lower() == "bck":
					pass
				elif cmd[0].lower() == "reload":
					exec("reload(%s)"%(cmd[1]))
				elif cmdline[:3].lower() == "run":
					hv = doc
					if len(cmdline) < 5:
						self.open_cli()
						cmdline = ""
					else:
						cmdline = cmdline[4:]
						exec(cmdline)
						hv.expose(None,None)
				elif cmd[0].lower() == "fmt":
					cmd = cmd[1:]
					mpos = cmdline.find("*")
					curpos = doc.lines[doc.curr][0]
					if mpos == -1:
						# wrap lines starting from current to provided lengths
						cmdacc = 0
						for k in cmd:
							cmdacc += int(k)
							if cmdacc + curpos > len(doc.data):
								cmd = cmd[:k]
								break
						doc.fmt_row(doc.curr,cmd)
						lrow = doc.curr+len(cmd)

					elif mpos == len(cmdline)-1:
						# repeat wrapping till end
						print "Rpt to end"
						cmd = cmdline[4:mpos].split()
						cmdacc = 0
						rpt = 0
						for k in cmd:
							cmdacc += int(k)
							if cmdacc + curpos > len(doc.data):
								cmd = cmd[:k]
								rpt = 1
								break
						if rpt == 0:
							rpt = 1+(doc.lines[len(doc.lines)-1][0]-doc.lines[doc.curr][0])/cmdacc
						for i in range(rpt):
							doc.fmt_row(doc.curr+i*len(cmd),cmd)

						lrow = doc.curr+i*len(cmd)
						
					else:
						cmd = cmdline[4:mpos].split()
						rpt = int(cmdline[mpos+1:].strip())
						cmdacc = 0
						for k in cmd:
							cmdacc += int(k)
							if cmdacc + curpos > len(doc.data):
								cmd = cmd[:k]
								rpt = 1
								break
								
						if cmdacc*rpt > doc.lines[len(doc.lines)-1][0]-doc.lines[doc.curr][0]:
							rpt = 1+(doc.lines[len(doc.lines)-1][0]-doc.lines[doc.curr][0])/cmdacc

						#repeat wrapping last arg times
						print "Rpt",rpt,"times",cmd
						for i in range(rpt):
							doc.fmt_row(doc.curr+i*len(cmd),cmd)

						lrow = doc.curr+i*len(cmd)+1

					doc.hvlines[lrow] = ""
					doc.set_maxaddr()
					doc.expose(None,None)

				elif cmd[0].lower() == "goto":
					addr = 0
					addrflag = 0
					if len(cmd) > 1:
						try:
							goto = cmdline[4:]
							pos = goto.find("+")
							if pos != -1:
								if pos == 1:
									addr = doc.lines[doc.curr][0]+doc.curc+int(goto[pos+1:],16)
									addrflag = 1
								else:
									addr = int(goto[1:pos],16)+int(goto[pos+1:],16)
							else:
								pos = goto.find("-")
								if pos != -1:
									if pos == 1:
										addr = doc.lines[doc.curr][0]+doc.curc-int(goto[pos+1:],16)
										addrflag = 1
									else:
										addr = int(goto[1:pos],16)-int(goto[pos+1:],16)
								else:
									addr = int(goto[1:], 16)
							print "Addr: ",addr
						except:
							print "Wrong string for Hex address"
					elif doc.sel:
						if len(data) <4:
							dstr = data + "\x00"*(4-len(data[:4]))
						else:
							dstr = data[:4]
						addr = struct.unpack("<I",dstr)
						print "Addr sel: %04x"%addr
					
					# try to validate/scroll
					llast = len(doc.lines)
					if addr < doc.lines[len(doc.lines)-1][0]:
						lnum = utils.find_line(doc,addr)
						print "Lnum found",lnum,"%x %x"%(doc.lines[lnum][0],doc.lines[lnum+1][0])
						if addrflag == 0:
							self.entry.set_text("goto %x"%addr)
						doc.curr = lnum
						doc.curc = addr - doc.lines[lnum][0]
						doc.offnum = min(lnum,llast-doc.numtl)
						doc.offset = doc.lines[lnum][0]

					else:
						print "Address after end of file"
						doc.offnum = llast-doc.numtl
						doc.offset = doc.lines[llast-1][0]
					doc.vadj.value = doc.offnum
					doc.expose(doc.hv,action)
				elif cmdline[0] == "?":
					utils.cmd_parse(cmdline,self,doc)
				elif cmdline[0] == "!":
					# off;len;text
					cmd = cmdline[1:].split(";")
					if len(cmd) < 3:
						# add comment to selection or cursor
						if doc.cursor_in_sel():
							rs,cs,re,ce = doc.sel
							clen = doc.get_sel_len()
						else:
							rs = doc.curr
							cs = doc.curc
							clen = 1
						text = cmdline[1:]
						off = doc.lines[rs][0]+cs+1
					else:
						text = ";".join(cmd[2:])
						off = int(cmd[0],16)+1
						clen = int(cmd[1],16)
					try:
						doc.insert_comment2(text,off,clen)
						doc.expose(doc.hv,action)
					except:
						print "Wrong args",sys.exc_info()
				elif cmdline.lower() == "dump":
					fname = self.file_open('Save',None,gtk.FILE_CHOOSER_ACTION_SAVE)
					if fname:
						f = open(fname,'wb')
						f.write(doc.data)
						f.close()
					else:
						print "Nothing to save"
				elif cmd[0].lower() == "html":
					off = -1
					try:
						off = int(cmd[1],16)
						clen = int(cmd[2],16)
						lnum = 0
						if off < len(doc.data):
							lnum = utils.find_line(doc,off)
							addr = doc.lines[lnum]
							if addr < off:
								clen += off - addr
					except:
						print "Something wrong with arguments",sys.exc_info()
					if off == -1:
						lnum = 0
						clen = len(doc.data)
					utils.html_export(self,doc,lnum,off,clen)
				elif cmdline[0] == "/":
					if len(cmdline) > 1:
						pos1 = cmdline.find("+")
						pos2 = cmdline.find("-")
						if pos1 != -1 or pos2 != -1:
							pos = max(pos1,pos2)
							try:
								arg1 = int(cmdline[1:pos],16)
								arg2 = int(cmdline[pos+1:],16)
								if pos1 != -1:
									addr = arg1+arg2
									self.entry.set_text("/%x+%x"%(addr,arg2))
								else:
									addr = arg1-arg2
									self.entry.set_text("/%x-%x"%(addr,arg2))
								lnum = utils.find_line (doc,addr)
								cnum = addr - doc.lines[lnum][0]
							except:
								print "Invalid offset"
						else:
							arg = cmdline[1:]
							try:
								addr = int(arg,16)
								lnum = utils.find_line (doc,addr)
								cnum = addr - doc.lines[lnum][0]
							except:
								print "Invalid offset"
					else:
						lnum = doc.curr
						cnum = doc.curc
					if lnum > 0:
						if cnum > 0:
							doc.fmt(lnum,[cnum])
							lnum += 1
							doc.curr = lnum
							doc.curc = 0
						s = (doc.lines[lnum-1][1]+1)%4
						doc.lines[lnum-1] = (doc.lines[lnum-1][0],s)
						# scroll down if went below screen
						if lnum > doc.offnum+doc.numtl-3:
							doc.offnum += doc.numtl/2
						# scroll up if went above screen
						if lnum < doc.offnum:
							doc.offnum = lnum
						doc.expose(None,None)
示例#14
0
def parse_receipt(raw_text):
    purchases = []
    raw_text_lines = raw_text.split("\n")
    items = [
        " ".join(a.split()[1:]) for a in re.findall("(?=\d+\. ).*", raw_text)
    ]

    for i, it in enumerate(items):
        weight_search_result = re.search("\d+(\.d+)?\ ?(к?гр?|м?л|шт)", it)
        if weight_search_result:
            weight_start, weight_end = weight_search_result.span()
            name = it[:weight_start].strip()
            *_, weight, measurement = re.split("(\d+)",
                                               it[weight_start:weight_end])
            weight = float(weight.strip())
            try:
                measurement, to_divide = normalize_measurement(
                    measurement.strip())
                weight /= to_divide
            except UnrecognizedMeasurement as e:
                print(e)
                measurement = ITEMS_CODE
        else:
            # weighted item, but ask user
            name = it
            measurement = KILOGRAMM_CODE
            weight = None

        if i < len(items) - 1:
            i1, i2 = find_line(raw_text_lines,
                               items[i]), find_line(raw_text_lines,
                                                    items[i + 1])
        else:
            i1, i2 = find_line(raw_text_lines, items[i]), len(raw_text_lines)
        if i1 is not None and i2 is not None:
            metadata = list(filter(lambda x: x, raw_text_lines[i1 + 1:i2]))
            quantity_line = metadata[0].split('x')[1].strip()
            full_price = float(
                quantity_line.split('=')[1].strip().replace(",", "."))
            quantity = float(
                quantity_line.split('=')[0].strip().replace(",", "."))
            if len(metadata) > 1:
                full_price -= float(metadata[1].split(":")[1].strip().replace(
                    ",", "."))

            if weight is None:
                if quantity == 1:
                    # TODO: suspicious, possibly it's pieces and it might not be one, ask user
                    measurement = ITEMS_CODE
                weight = quantity
                full_weight = weight
            else:
                if measurement == ITEMS_CODE:
                    # TODO: multiply by weight of one piece
                    pass
                full_weight = quantity * weight
#             print(f"Name: {name}, Weight: {weight} {code2name[measurement]}, "
#                   f"Quantity: {quantity}, Full weight: {full_weight} {code2name[measurement]} Full price: {full_price}")
            purchases.append(
                Purchase(name, weight, measurement, quantity, full_weight,
                         full_price))
    return purchases
示例#15
0
def processing(img, object_points, img_points, M, Minv, left_line, right_line):
    # camera calibration, image distortion correction
    # undist = utils.cal_undistort(img,object_points,img_points)
    cv2.imshow("img", img)
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # 设置阈值下限和上限,去除背景颜色
    lower_red = np.array([80, 0, 0])
    upper_red = np.array([160, 255, 150])

    lower_white = np.array([0, 0, 221])
    upper_white = np.array([180, 30, 255])

    lower_yellow = np.array([100, 43, 46])
    upper_yellow = np.array([120, 255, 255])

    lower_lane = np.array([0, 0, 50])
    upper_lane = np.array([180, 43, 120])
    # 创建掩膜
    # 将原图像和掩膜做位与运算

    white_img = colorMask("white_mask", img, hsv, lower_white, upper_white)
    # yellow_img = colorMask("yellow_mask", img, hsv, lower_yellow, upper_yellow)
    # lane_img = colorMask("lane_mask", img, hsv, lower_lane, upper_lane)

    undist = img
    gray = cv2.cvtColor(white_img, cv2.COLOR_RGB2GRAY)

    ret, binary = cv2.threshold(gray, 200, 255,
                                cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
    ret, binary2 = cv2.threshold(gray, 200, 1,
                                 cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
    #cv2.imshow("binary", binary)
    rgb = cv2.cvtColor(binary, cv2.COLOR_GRAY2RGB)
    cv2.imshow("rgb", rgb)

    #cv2.imshow("binary2", binary)
    # get the thresholded binary image
    thresholded = thresholding(rgb)
    cv2.imshow("thresholded*255", thresholded * 255)
    #perform perspective  transform
    thresholded_wraped = cv2.warpPerspective(binary2,
                                             M,
                                             img.shape[1::-1],
                                             flags=cv2.INTER_LINEAR)

    cv2.imshow("thresholded_wraped*255", thresholded_wraped * 255)

    #perform detection
    if left_line.detected and right_line.detected:
        print("find line")
        left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line_by_previous(
            thresholded_wraped, left_line.current_fit, right_line.current_fit)
    else:
        print("no find line")
        left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line(
            thresholded_wraped)
    left_line.update(left_fit)
    right_line.update(right_fit)

    #draw the detected laneline and the information
    area_img = utils.draw_area(undist, thresholded_wraped, Minv, left_fit,
                               right_fit)
    cv2.imshow("area_img", area_img)
    cv2.waitKey(50)

    #print(area_img)
    #curvature,pos_from_center = utils.calculate_curv_and_pos(thresholded_wraped,left_fit, right_fit)
    #result = utils.draw_values(area_img,curvature,pos_from_center)
    #result=area_img
    result = rgb
    return result
示例#16
0
    plt.subplot(len(perspective_transformed_images), 2, 2 * i + 2)
    i += 1
    plt.title('lane fitting')
    out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
    out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]
    plt.imshow(out_img)
    plt.plot(left_fitx, ploty, color='yellow')
    plt.plot(right_fitx, ploty, color='yellow')
    plt.xlim(0, 1280)
    plt.ylim(720, 0)
plt.savefig('lane fitting.png')

# In[23]:

for binary_warped in perspective_transformed_images:
    left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line(
        binary_warped)
    curvature, distance_from_center = utils.calculate_curv_and_pos(
        binary_warped, left_fit, right_fit)

# In[24]:

plt.figure(figsize=(20, 40))
for i in range(0, (len(undistorted_test_images))):
    left_fit, right_fit, left_lane_inds, right_lane_inds = utils.find_line(
        perspective_transformed_images[i])
    curvature, distance_from_center = utils.calculate_curv_and_pos(
        perspective_transformed_images[i], left_fit, right_fit)
    result = utils.draw_area(undistorted_test_images[i],
                             perspective_transformed_images[i], Minv, left_fit,
                             right_fit)
    img = utils.draw_values(result, curvature, distance_from_center)