def main(): cap = None def get(): return cv2.imdecode(np.asarray(bytearray(requests.get(url, stream=True).raw.read()), dtype="uint8"), cv2.IMREAD_COLOR) try: # Try to access remote camera. frame = get() except requests.exceptions.ConnectionError: # Fallback to local camera instead. cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_BUFFERSIZE, 0) def get(): return cap.read()[1] frame = get() ht = Lines(frame.shape[:2]) while True: frame = get() trans = ht.transform(frame) cv2.imshow('Hmmm', trans) if cv2.waitKey(1) & 0xFF == ord('q'): break if cap: cap.release() cv2.destroyAllWindows()
def rotate_right(self): self.rot += 2 if self.rot > 180: self.rot = -180 self.lines.remove_lines() self.lines = Lines(self.amount, self.rayCan, self.walls, self.x, self.y, self.rot) self.lines.draw_lines(self.x, self.y) self.redraw_borders()
def update_rays(self, x): self.rayCan.delete(self.id) self.lines.remove_lines() self.remove_bricks self.amount = x self.lines = Lines(self.amount, self.rayCan, self.walls, self.x, self.y, self.rot) self.DrawCircle()
def rotate_left(self): self.rot -= 2 if self.rot < -180: self.rot = 180 self.lines.remove_lines() self.lines = Lines(self.amount, self.rayCan, self.walls, self.x, self.y, self.rot) self.lines.draw_lines(self.x, self.y) self.redraw_borders()
def draw_lines(self, img, lines): """ NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that shown in P1_example.mp4). Think about things like separating line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left line vs. the right line. Then, you can average the position of each of the lines and extrapolate to the top and bottom of the lane. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). If you want to make the lines semi-transparent, think about combining this function with the weighted_img() function below """ calculated_lines = Lines.calculate_lines(img.shape[0], lines) if calculated_lines is not None: for x1, y1, x2, y2 in calculated_lines: cv2.line(img, (x1, y1), (x2, y2), self.parameters.lines.color, self.parameters.lines.thickness) return img
class Player: def __init__(self, name, x, y, color_name, map): self.name = name self.car = Car(x, y, COLORS[color_name], map) self.lines = Lines(COLORS[color_name]) def set_dest(self, v): self.car.move(v) self.lines.add(self.car.current_line) def get_next_pos(self): return self.car.get_next_pos() def draw(self, surf, main=False): self.car.draw(surf, main) self.lines.draw(surf) def __str__(self): return "%s - %s" %(self.name, self.car)
def __init__(self, x, y, C, C2, W, walls): super().__init__() self.win = W self.rayCan = C self.wallCan = C2 self.id = None self.x = x self.y = y self.r = 10 #radius of circle self.amount = 720 #default angle of rays self.walls = walls self.bricks = [] self.distances = [] self.rot = 0 #starting angle for FOV self.lines = Lines(self.amount, self.rayCan, self.walls, x, y, self.rot) self.DrawCircle()
def cve2lines(cvedirn, station_conv, llfn): railstation_fn = os.path.join(cvedirn, 'railstation_master.txt') # railstation -> 路線 - 駅名リスト # {(cve路線ID, cve路線名): ジョルダン駅名, ...} railstation_data = mk_railstation_data(railstation_fn, station_conv) # Lines instance lines = Lines() for lineID, linename, *stations_j in railstation_data: chk = lines.add_line(lineID, linename, stations_j) if type(chk) is int and chk < 0: print('railstation err: {0}: {1} {2}'.format( chk, lineID, linename)) sys.exit() # 路線リスト lines_list = lines.line_list() with open(llfn, 'w', encoding='utf-8') as f: f.write(''.join(['\t'.join(l) + '\n' for l in lines_list])) return lines
def createLines(): for b in bs: l = Lines(b) lines.append(l)
def scan(main_color, intermediates=None): main_gray = utility.shrink_img(main_color) # 処理速度を上げるため縮小する main_gray = cv2.cvtColor(main_gray, cv2.COLOR_BGR2GRAY) size_color = main_color.shape[:2] size_gray = main_gray.shape length_threshold = 20 distance_threshold = 1.4142 # canny_th1 = 5.0 # canny_th2 = 50.0 canny_th1 = 1.0 canny_th2 = 10 canny_size = 3 do_merge = False do_merge = False fld = cv2.ximgproc.createFastLineDetector(length_threshold, distance_threshold, canny_th1, canny_th2, canny_size, do_merge) line_pnts = fld.detect(main_gray) line_pnts = np.array(line_pnts).reshape((-1, 4)) lines = Lines(line_pnts) print(f"Num of lines: {lines.num} => ", end="") lines.remove_central(size_gray) print(lines.num) equal = lines.equal() labels = partition.partition(lines.num, equal) labels_num = len(np.unique(labels)) if intermediates is not None: intermediates['lines'] = utility.draw_lines(main_gray, lines, labels, labels_num) cv2.imwrite("lines.jpeg", intermediates['lines']) segments = Segments(lines, labels, labels_num, size_gray) print(f"Num of segments: {segments.num} => ", end="") segments.remove_central(size_gray) print(segments.num) if intermediates is not None: intermediates['segments'] = utility.draw_segments(main_gray, segments) cv2.imwrite("segments.jpeg", intermediates['segments']) intersections = Intersections(segments, size_gray) print(f"Num of intersections: {intersections.num}") if intermediates is not None: intermediates['intersections'] = utility.draw_intersections( main_gray, intersections) cv2.imwrite("intersections.jpeg", intermediates['intersections']) df = ml_model.prepare_data(intersections, size_gray) scores = ml_model.get_score(df) indice = np.argsort(scores)[::-1] points_per_section = 3 vertex_lt = [] vertex_rt = [] vertex_lb = [] vertex_rb = [] for idx in indice: if intersections.is_left[idx] and intersections.is_top[idx] and len( vertex_lt) < points_per_section: vertex_lt.append(idx) elif intersections.is_right[idx] and intersections.is_top[idx] and len( vertex_rt) < points_per_section: vertex_rt.append(idx) elif intersections.is_left[idx] and intersections.is_bottom[ idx] and len(vertex_lb) < points_per_section: vertex_lb.append(idx) elif intersections.is_right[idx] and intersections.is_bottom[ idx] and len(vertex_rb) < points_per_section: vertex_rb.append(idx) if len(vertex_lt) >= points_per_section and \ len(vertex_rt) >= points_per_section and \ len(vertex_lb) >= points_per_section and \ len(vertex_rb) >= points_per_section: break if len(vertex_lt) == 0: print("no vertex at left top was found") return None if len(vertex_rt) == 0: print("no vertex at right top was found") return None if len(vertex_lb) == 0: print("no vertex at left bottom was found") return None if len(vertex_rb) == 0: print("no vertex at right bottom was found") return None idx_lt, idx_rt, idx_lb, idx_rb = utility.get_best_set( intersections, scores, vertex_lt, vertex_rt, vertex_lb, vertex_rb) # print(f"selected vertexes: ({idx_lt}, {idx_rt}, {idx_lb}, {idx_rb})") if intermediates is not None: intermediates['detected'] = utility.draw_detected( main_gray, intersections, idx_lt, idx_rt, idx_lb, idx_rb) src_points_gray = np.array([ \ intersections.cross_pnt[idx_lt], \ intersections.cross_pnt[idx_rt], \ intersections.cross_pnt[idx_lb], \ intersections.cross_pnt[idx_rb] ], dtype=np.float32) dst_points_gray = np.array([ \ (0, 0), (size_gray[1], 0), (0, size_gray[0]), (size_gray[1], size_gray[0]) ], dtype=np.float32) scale = np.array(size_color, dtype=np.float32) / np.array(size_gray, dtype=np.float32) scale = scale[::-1] src_points_color = src_points_gray * scale dst_points_color = dst_points_gray * scale M_color = cv2.getPerspectiveTransform(src_points_color, dst_points_color) main_color = cv2.warpPerspective(main_color, M_color, size_color[::-1]) return main_color
import pygame from random import randrange as rd from lines import Lines if __name__ == '__main__': SZ = 600 FPS = 60 pygame.init() win = pygame.display.set_mode((SZ, SZ)) lines = Lines(SZ // 50, SZ // 50, 50, win) clock = pygame.time.Clock() while True: lines.show() for i in pygame.event.get(): if i.type == pygame.QUIT: exit() if i.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() lines.click() clock.tick(FPS)
def __init__(self, database): self.lines = Lines() self.database = database self.talker = Talker() self.talker.start()
class CommentatorTalker(object): def __init__(self, database): self.lines = Lines() self.database = database self.talker = Talker() self.talker.start() def tag(self, tagger, tagged): tag_lines = [] weighted_tag_lines = [] tagger_speed = tagger.getActualSpeed() tagged_speed = tagged.getActualSpeed() tag_line = None if tagger_speed - tagged_speed > 60: tag_lines.append(self.lines.get_fast_tagger_slow_tagged_line()) elif tagger_speed > 60: tag_lines.append(self.lines.get_fast_tagger_line()) elif tagged_speed < 60: tag_lines.append(self.lines.get_slow_tagged_line()) tag_lines.append(self.lines.get_standard_tag_line()) self.say(random.choice(tag_lines) % {'tagger': tagger.getName(), 'tagged': tagged.getName()}) print str(tagger_speed) + ", " + str(tagged_speed) self.check_for_tag_color(tagger, tagged) def check_for_tag_color(self, tagger, tagged): tag_line_strings = [] # cflewis | 2008-11-22 | Say something about the number of tags tag_line_strings.append(self.lines.get_number_of_tags_line() \ % {'tagger': tagger.getName(), 'tagged': tagged.getName(), 'tags': \ self.database.get_tag_number(tagger.getName(), tagged.getName())}) # cflewis | 2008-11-22 | Say something about the speed of the tagger speed_comment = self.get_speed_comment(tagger) if speed_comment is not None: tag_line_strings.append(speed_comment) speed_comment = self.get_speed_comment(tagged) if speed_comment is not None: tag_line_strings.append(speed_comment) self.say(random.choice(tag_line_strings)) # cflewis | 2008-11-26 | Shuffle the color commentary and # push it to the commentator talking buffer, where it can # say these things if it has time to #random.shuffle(tag_line_strings) #while len(tag_line_strings) > 0: # self.say(tag_line_strings.pop()) def get_speed_comment(self, character): average_speed = self.database.get_average_speed(character.getName()) print "Average speed is %s, and actual speed is %s" % (average_speed, character.getActualSpeed()) if character.getActualSpeed() > (average_speed + 10): return self.lines.get_faster_than_average_line() % \ {'character': character.getName(), 'speed': average_speed} if character.getActualSpeed() < (average_speed - 10): return self.lines.get_slower_than_average_line() % \ {'character': character.getName(), 'speed': average_speed} # cflewis | 2008-11-26 | Nothing interesting to say about this return None def say(self, comment): print comment #os.system('say "' + comment +' " &') self.talker.addComment(comment) def clean_up(self): self.talker.end()
import requests from bs4 import BeautifulSoup import json from global_vars import LINES from lines import Lines from stations import Stations data = [] for line in LINES: response = requests.get( f'https://api.openstreetmap.org/api/0.6/relation/{line["code"]}/full') if response.status_code == 200: soup = BeautifulSoup(response.content, "xml") print('got soup!') points = Lines(soup, line['color'], line['ref']) stations = Stations(soup) data.append({**points.return_points(), **stations.return_stations()}) # create file if not exists f = open('src/data/lines.json', 'w') with open('src/data/lines.json', 'w') as outfile: json.dump(data, outfile) print('Output')
class Orb: def __init__(self, x, y, C, C2, W, walls): super().__init__() self.win = W self.rayCan = C self.wallCan = C2 self.id = None self.x = x self.y = y self.r = 10 #radius of circle self.amount = 720 #default angle of rays self.walls = walls self.bricks = [] self.distances = [] self.rot = 0 #starting angle for FOV self.lines = Lines(self.amount, self.rayCan, self.walls, x, y, self.rot) self.DrawCircle() def rotate_left(self): self.rot -= 2 if self.rot < -180: self.rot = 180 self.lines.remove_lines() self.lines = Lines(self.amount, self.rayCan, self.walls, self.x, self.y, self.rot) self.lines.draw_lines(self.x, self.y) self.redraw_borders() def rotate_right(self): self.rot += 2 if self.rot > 180: self.rot = -180 self.lines.remove_lines() self.lines = Lines(self.amount, self.rayCan, self.walls, self.x, self.y, self.rot) self.lines.draw_lines(self.x, self.y) self.redraw_borders() def DrawCircle(self): self.id = self.rayCan.create_oval(self.x - self.r, self.y - self.r, self.x + self.r, self.y + self.r, fill="black") self.lines.draw_lines(self.x, self.y) # self.wallCan.create_oval(self.x - self.r, self.y - self.r, self.x + self.r, self.y + self.r, fill = "black") self.draw_borders() def Redraw(self, x, y): self.x = x self.y = y self.rayCan.coords(self.id, x - self.r, y - self.r, x + self.r, y + self.r) self.lines.redraw_lines(x, y) self.redraw_borders() def update_rays(self, x): self.rayCan.delete(self.id) self.lines.remove_lines() self.remove_bricks self.amount = x self.lines = Lines(self.amount, self.rayCan, self.walls, self.x, self.y, self.rot) self.DrawCircle() def draw_borders(self): borders = self.lines.get_distances() self.wallCan.update() width = self.wallCan.winfo_width() / len(borders) left_point = 0 right_point = width for i in borders: self.bricks.append( self.wallCan.create_rectangle(left_point, i, right_point, 800 - i, outline="", fill=self.determine_color(i))) left_point = right_point right_point += width def redraw_borders(self): borders = self.lines.get_distances() width = 796 / len(borders) left_point = 0 right_point = width for i in range(len(borders)): self.wallCan.coords(self.bricks[i], left_point, borders[i], right_point, 800 - borders[i]) self.wallCan.itemconfig(self.bricks[i], fill=self.determine_color(borders[i])) left_point = right_point right_point += width def remove_bricks(self): for i in self.bricks: self.wallCan.delete(i) self.bricks = [] def determine_color(self, distance): #smaller distance = brighter shadefactor = distance / 400 r = 68 - (68 * shadefactor) g = 32 - (32 * shadefactor) b = 247 - (247 * shadefactor) colour = '#%02x%02x%02x' % (int(r), int(g), int(b)) return colour
def __init__(self, name, x, y, color_name, map): self.name = name self.car = Car(x, y, COLORS[color_name], map) self.lines = Lines(COLORS[color_name])
# -*- coding: utf-8 -*- # Copyright (C) 2013 Sylvain Boily <*****@*****.**> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from flask import Blueprint from lines import Lines import wtforms_json bp_lines = Blueprint('lines', __name__, template_folder='templates/lines') lines = Lines() wtforms_json.init()
llfn = os.path.join(outdirn, 'runtable_line_list.txt') # ジョルダン -> 所定 路線対応リスト取得 1:多 # {(ジョルダン路線名, ジョルダン方面名): [(cve路線ID, cve路線名), ...], ...} line_conv = mk_line_conv(lineconv_fn) # cve -> ジョルダン 駅名対応リスト取得 多:1 # {cve駅名: ジョルダン駅名} station_conv = mk_station_conv(stalinedirec_fn) # railstation -> 路線 - 駅名リスト # {(cve路線ID, cve路線名): ジョルダン駅名, ...} railstation_data = mk_railstation_data(railstation_fn, station_conv) # Lines instance lines = Lines() for (lineID, linename), stations in railstation_data.items(): chk = lines.add_line(lineID, linename, stations) if chk < 0: print('railstation err: {0}: {1} {2}'.format( chk, lineID, linename)) sys.exit() # 運行表データを全部読み、長いデータ順に all_data = read_data_and_sort(rt_dirn) ok_data, osng_data, pas_data, err_data = [], [], [], [] vehicles = {} # 1列車ずつ for l in all_data:
# glut.glutIdleFunc(on_idle) # Some init gl.glPolygonOffset(1, 1) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_LINE_SMOOTH) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_BLEND) gl.glClearColor(1.0, 1.0, 1.0, 1.0) gl.glClearColor(0.4, 0.4, 0.5, 1.0) u_projection = np.eye(4).astype(np.float32) u_view = np.eye(4).astype(np.float32) u_model = np.eye(4).astype(np.float32) phi, theta = 45, 45 lines = Lines() n = 2000 points = np.zeros((n, 3)) T = np.linspace(0, 24 * 2 * np.pi, n) Z = np.linspace(-1, 1, n) U = np.sqrt(1 - Z * Z) X, Y = np.cos(T) * U, np.sin(T) * U points[:, 0] = X points[:, 1] = Y points[:, 2] = Z lines.append(points, fg_color=(1, 1, 1, 1), linewidth=0.015) glut.glutMainLoop()