def main(): logging.basicConfig() logging.getLogger().setLevel(logging.INFO) # Using the correct encoding when printing sys.stdout = codecs.getwriter('mbcs' if os.name == 'nt' and sys.stdout.isatty() else 'utf-8')(sys.stdout, 'replace') set_agent('(PrivateChatSession; http://dev.ivybits.tk/projects/hal/)') try: sys.argv.remove('-d') except ValueError: pass else: from xail import main main.DEBUG_MODE = True logger.warning('Using debug mode!') try: dir = sys.argv[1] except IndexError: dir = '.' hal = HAL() def loadengine(pattern, name): engine = getattr(hal.xail, name) for file in glob(os.path.join(dir, pattern)): logger.info('%s Engine: Loading %s', name, file) engine.load(io.open(file, encoding='utf-8')) loadengine('*.gen', 'substr') loadengine('*.mtx', 'matrix') loadengine('*.rgx', 'regex') for file in glob(os.path.join(dir, '*.xail')): logger.info('Loading %s', file) hal.feed(io.open(file, encoding='utf-8')) user = getuser() prompt = '-%s:' % user halpro = '-HAL:' length = max(len(prompt), len(halpro)) prompt.ljust(length) halpro.ljust(length) prompt += ' ' context = {'USERNAME': user} print(halpro, 'Hello %s. I am HAL %s.'%(user, hal.version)) print() try: while True: line = raw_input(prompt) try: print(halpro, hal.answer(line, context)) except IOError as e: if e.errno != 0: raise print() # It gets error 0 when some characters can't be displayed print() except (EOFError, KeyboardInterrupt): pass finally: print(halpro, 'Goodbye.')
def bootstrap(self): from HAL import HAL write = self.write timer = self.timer = clock if os.name == 'nt' else time begin = timer() write('Initializing Engine...') self.hal = HAL() write(' done\n') try: dirname = sys.argv[1] except IndexError: dirname = os.getcwd() # Here's the legacy loading def loadfiles(pattern, attr, name): engine = getattr(self.hal.xail, attr) for file in glob(os.path.join(dirname, pattern)): write('%s Engine: Loading %s...' % (name, file)) engine.load(io.open(file, encoding='utf-8')) write(' Done\n') loadfiles('*.gen', 'matrix', 'Matrix') loadfiles('*.mtx', 'substr', 'Substring') loadfiles('*.rgx', 'regex', 'Regex') # New unified XAIL loading files = glob(os.path.join(dirname, '*.xail')) max_length = max(map(len, files)) for file in files: write('Loading %s' % file + ' ' * (max_length - len(file)) + '...') start = timer() self.hal.feed(io.open(file, encoding='utf-8')) write(' Finished in %8.2f ms\n' % ((timer() - start) * 1000)) write('\n') user = getuser() prompt = '-%s: '%user halpro = '-HAL: ' length = max(len(prompt), len(halpro)) prompt.ljust(length) halpro.ljust(length) self.prompt, self.halpro = prompt, halpro self.context = {'USERNAME': user} write('Loaded in %.2f seconds.\n\n' % (timer() - begin)) write(halpro + 'Hello %s. I am HAL %s.' % (user, self.hal.version) + '\n\n') self.entry.bind('<Return>', self.answer)
def check_target(self, posx, posy, targetx, targety): if (abs(targetx - posx) <= 6 and abs(targety - posy) <= 6): currentTarget.setReached(True) currentTarget = GUI.map.getNextTarget() if (currentTarget != None): return 1 else: return 0 while True: currentTarget = GUI.map.getNextTarget() GUI.map.targetx = currentTarget.getPose().x GUI.map.targety = currentTarget.getPose().y posx = HAL.getPose3d().x posy = HAL.getPose3d().y targetid = currentTarget.getId() # TODO k_obstacle = 0.6 k_car = 0.2 k_target = -0.2 unit_angle = (HAL.getLaserData().maxAngle - HAL.getLaserData().minAngle) / len(HAL.getLaserData().values) unit_range = 1 / (HAL.getLaserData().maxRange - HAL.getLaserData().minRange) target_vector = [ k_target * (GUI.map.targetx - posx), k_target * (GUI.map.targety - posy)
from GUI import GUI from HAL import HAL import cv2 as cv import numpy as np from scipy.stats import mode # Parameter initialization size_accumulator = 10 directions_map = np.zeros([size_accumulator, 5]) frame_previous = HAL.getImage() gray_previous = cv.cvtColor(frame_previous, cv.COLOR_BGR2GRAY) hsv = np.zeros_like(frame_previous) hsv[:, :, 1] = 255 threshold = 10.0, # Threshold value for magnitude param = { 'pyr_scale': 0.5, # Image scale (<1) to build pyramids for each image 'levels': 3, # Number of pyramid layers 'winsize': 15, # Averaging window size 'iterations': 3, # Number of iterations the algorithm does at each pyramid level 'poly_n': 5, # Size of the pixel neighborhood used to find polynomial expansion in each pixel 'poly_sigma': 1.1, # Standard deviation of the Gaussian that is used to smooth derivatives used as a basis for the polynomial expansion 'flags': cv.OPTFLOW_LK_GET_MIN_EIGENVALS } while True: frame = HAL.getImage()
# Initialize some values error_last = 0 error_sum = 0 # Set controller gains #Kp = .00075 #Kd = .00001 #Ki = .00001 Kp = .001 Kd = .001 Ki = .000001 while True: # load the current image image = HAL.getImage() # Find the red line in the image mask = cv2.inRange(image, lower, upper) output = cv2.bitwise_and(image, image, mask = mask) # Locate the centroid of the red line M = cv2.moments(mask, binaryImage=True) # Display a white circle at the centroid of the line if M['m00'] != 0: cx = int(M['m10'] / M['m00']) cy = int(M['m01'] / M['m00']) cv2.circle(image, (cx, cy), 10, (255, 255, 255), -1) else: cx = 0
from GUI import GUI from HAL import HAL import math import numpy as np # Enter sequential code! threshold_angle = 0.01 threshold_distance = 0.25 threshold = 0.01 kp = 1.0 while True: # Enter iterative code! # creating Objects currentTarget = GUI.map.getNextTarget() laser_data = HAL.getLaserData () # definging Variables pos = [HAL.getPose3d().x, HAL.getPose3d().y] dist = [-1*(currentTarget.getPose().x - pos[0]), -1*(currentTarget.getPose().y - pos[1])] mod_dist = math.sqrt(dist[0]**2 + dist[1]**2) GUI.map.targetx = currentTarget.getPose().x GUI.map.targety = currentTarget.getPose().y if (dist[1] <= 0.001): currentTarget.setReached(True) GUI.map.carx = 1.5*(dist[0] / mod_dist) GUI.map.cary = 1.5*(dist[1] / mod_dist) GUI.map.obsx = 0.0 GUI.map.obsy = 0.0 # Creating the Histogram
class Application(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.root = master self.grid(sticky='WENS') self.createWidgets() self.queue = Queue() self.after(100, self.update_console) Thread(target=self.bootstrap).start() def write(self, text): self.queue.put(text) sys.stdout.write(text) def clear(self): self.queue.put(None) def update_console(self): try: while True: line = self.queue.get_nowait() if line is None: self.console.delete(1.0, 'end') else: self.console.insert('end', str(line)) self.console.see('end') self.console.update_idletasks() except Empty: pass self.after(100, self.update_console) def bootstrap(self): from HAL import HAL write = self.write timer = self.timer = clock if os.name == 'nt' else time begin = timer() write('Initializing Engine...') self.hal = HAL() write(' done\n') try: dirname = sys.argv[1] except IndexError: dirname = os.getcwd() # Here's the legacy loading def loadfiles(pattern, attr, name): engine = getattr(self.hal.xail, attr) for file in glob(os.path.join(dirname, pattern)): write('%s Engine: Loading %s...' % (name, file)) engine.load(io.open(file, encoding='utf-8')) write(' Done\n') loadfiles('*.gen', 'matrix', 'Matrix') loadfiles('*.mtx', 'substr', 'Substring') loadfiles('*.rgx', 'regex', 'Regex') # New unified XAIL loading files = glob(os.path.join(dirname, '*.xail')) max_length = max(map(len, files)) for file in files: write('Loading %s' % file + ' ' * (max_length - len(file)) + '...') start = timer() self.hal.feed(io.open(file, encoding='utf-8')) write(' Finished in %8.2f ms\n' % ((timer() - start) * 1000)) write('\n') user = getuser() prompt = '-%s: '%user halpro = '-HAL: ' length = max(len(prompt), len(halpro)) prompt.ljust(length) halpro.ljust(length) self.prompt, self.halpro = prompt, halpro self.context = {'USERNAME': user} write('Loaded in %.2f seconds.\n\n' % (timer() - begin)) write(halpro + 'Hello %s. I am HAL %s.' % (user, self.hal.version) + '\n\n') self.entry.bind('<Return>', self.answer) def answer(self, e=None): write = self.write input = self.input.get() answer = self.hal.answer(input, self.context) write(self.prompt + input + '\n') write(self.halpro + answer + '\n\n') self.input.set('') def createWidgets(self): font_console = Font(family='Consolas', size=11) self.input = tk.StringVar() self.config(borderwidth=10) self.console = ScrolledText(self, font=font_console, state='normal') self.entry = ttk.Entry(self, textvariable=self.input, font=font_console) submit = ttk.Button(self, text='Submit') self.console.grid(columnspan=3, sticky='WENS') tk.LabelFrame(self, height=5).grid(row=1) self.entry.grid(row=2, sticky='WE') tk.LabelFrame(self, width=5).grid(row=2, column=1) submit.grid(row=2, column=2) submit['command'] = self.answer self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.root.wm_title('HAL') self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=0) self.rowconfigure(0, weight=1)
# Enter sequential code! from GUI import GUI from HAL import HAL while True: # Enter iterative code! img = HAL.get_ventral_image() GUI.showImage(img)
from GUI import GUI from HAL import HAL # Enter sequential code! import cv2 import numpy as np while True: frame = HAL.getImage() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (30, 30), 0) #Otsu's Thresholding ret, th = cv2.threshold(blur, 0, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #Adaptive Gaussian Thresholding th1 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) blue_lower = np.array([0, 120, 97], dtype='uint8') blue_upper = np.array([179, 255, 255], dtype='uint8') mask = cv2.inRange(hsv, blue_lower, blue_upper) erosion = cv2.erode(mask, kernel, iterations=2) dialation = cv2.dialate(erosion, kernel, iterations=2) cont = cv2.findContours(dialation, cv2.RETR_LIST, cv2.cv2.CHAIN_APPROX_SIMPLE) areas = [cv2.contourArea(c) for c in cont] if len(areas) > 0: area_max = np.argmax(areas)