def draw(): global detector, prev, vs, shotDetector, started, height, width, ball, inHand, fps, currX, currY background(255) fill(0) stroke_weight(0) frame = vs.read() detector.process(vs, frame) fill(0) drawRect(backboard) fill(244, 140, 0) drawRect(rim) fill(224, 198, 112) drawRect(courtFloor) # free throw fill(0, 200, 0) r1 = Rect(width - FREETHROW_DIST * ppm - 5, height - 10, 5, 10) drawRect(r1) # top of key fill(0, 0, 200) r2 = Rect(width - TOP_KEY_DIST * ppm - 5, height - 10, 5, 10) drawRect(r2) # three point line fill(200, 0, 0) r3 = Rect(width - THREEPOINT_DIST * ppm - 5, height - 10, 5, 10) drawRect(r3) fill(255, 102, 0) print(detector.centerPoint) width2 = translate(detector.centerPoint[0], 0, 700, width // 2, 0) height2 = translate(detector.centerPoint[1], 0, 300, 0, height // 2) circle((width2 * 2, height2 * 2), 50)
def assign_document_word_to_row(word, rows): ''' assign word to nearest row (L2 distance) :param word: a word returned by Google Cloud Vision :param rows: a list of rows in one column :return: rows with information of the input word ''' areas, dists = [], [] box = np.array( [[word.bounding_box.vertices[0].x, word.bounding_box.vertices[0].y], [word.bounding_box.vertices[1].x, word.bounding_box.vertices[1].y], [word.bounding_box.vertices[2].x, word.bounding_box.vertices[2].y], [word.bounding_box.vertices[3].x, word.bounding_box.vertices[3].y]]) word_rect = cv2.minAreaRect(box) for i in range(len(rows)): areas.append(Rect.AreaOfOverlap(word_rect, rows[i].row_rect)) dists.append(Rect.DistOfRects(word_rect, rows[i].row_rect)) max_area = 0 if max(areas) > 0: #assign word to the row_img with max_area max_area = max(areas) index = areas.index(max_area) else: #if the word has no intersection with any row img, assign it to closest row_img index = dists.index(min(dists)) rows[index].words.append(MessageToDict(word)) try: rows[index].AOIs.append(max_area / word_rect[1][0] / word_rect[1][1]) except: # 0/0 rows[index].AOIs.append(0)
def __init__(self, x, y): """ :param: X-Koordinate, Y-Koordinate """ self.x = x #pos X self.y = y # pos Y # Sprite self.img = pygame.image.load("sprites/tower.png") self.width = 16 self.height = 16 self.size = 32 # Einstellungen des Towers self.range = 150 # Reichweite der schusse self.cd = 10 # Zeit bevor neuer Schuss (Cooldown) self.prev = 0 # last time shot self.damage = 10 # Schaden # Hitbox self.space = 14 # Freiraum zwischen sprite und nachst mogliche pos self.hitbox = Rect(self.x - self.width - self.space, self.y - self.height - self.space, self.x + self.width + self.space, self.y + self.height + self.space) # Display Einstellungen self.disp_mode = 0 # for highlight self.radius_color = (0, 0, 255, 100)
def main(rect_json, args): if 'row' in args.rectdir: row=True else: row=False print('processing ' + rect_json) imgpath = os.path.join(args.imgdir, GetImgFilename(rect_json)) img=cv2.imread(imgpath) with open(os.path.join(args.rectdir, rect_json)) as file: rects = json.load(file) outputdir = os.path.join(args.outputdir, rect_json.split('.')[0]) if not os.path.isdir(outputdir): os.mkdir(outputdir) if row: #output row for key in sorted(rects.keys()): #import pdb;pdb.set_trace() i = 0 for rect in rects[key]: warped, _ = Rect.CropRect(img, rect) cv2.imwrite(os.path.join(outputdir, rect_json.split('.')[0] +'_' + key + '_' + str(i).zfill(3) + '.png'), warped) i+=1 else: #output col i = 0 for rect in rects: #import pdb;pdb.set_trace() warped, _ = Rect.CropRect(img, rect) cv2.imwrite(os.path.join(outputdir,rect_json.split('.')[0]+'_'+str(i).zfill(1)+'.png'),warped) i+=1
def drag_monitor(curr_monitor, remaining_monitor_list, curr_mouse_dict, prev_mouse_dict): if curr_monitor is not None and curr_mouse_dict["left"]: x_delta, y_delta = [ curr_mouse_dict["pos"][i] - prev_mouse_dict["pos"][i] for i in range(2) ] if not any([ Rect.is_colliding(curr_monitor.rect, check_monitor.rect, rect_1_x_delta=x_delta, rect_1_y_delta=y_delta) for check_monitor in remaining_monitor_list ]): curr_monitor.rect.reposition(curr_monitor.rect.x + x_delta, curr_monitor.rect.y + y_delta) elif not any([ Rect.is_colliding(curr_monitor.rect, check_monitor.rect, rect_1_y_delta=y_delta) for check_monitor in remaining_monitor_list ]): curr_monitor.rect.reposition(curr_monitor.rect.x, curr_monitor.rect.y + y_delta) elif not any([ Rect.is_colliding(curr_monitor.rect, check_monitor.rect, rect_1_x_delta=x_delta) for check_monitor in remaining_monitor_list ]): curr_monitor.rect.reposition(curr_monitor.rect.x + x_delta, curr_monitor.rect.y)
def CombineSmallRowRects(self): ''' combine very small rows (rowHeight very small) with closest row ''' for i in range(len(self.rowHeights) - 1, 0 - 1, -1): if self.rowHeights[i] < self.rowHeight * 0.8 and len( self.rowHeights ) >= 2: # small row: combine it with the closest row if i == 0: if Rect.DistOfRects(self.rowRects[0], self.rowRects[1]) < self.rowHeight * 3: self.CombineRowRects(0, 1) else: self.rowRects.pop(i) self.rowHeights.pop(i) elif i == len(self.rowHeights) - 1: if Rect.DistOfRects( self.rowRects[i], self.rowRects[i - 1]) < self.rowHeight * 3: self.CombineRowRects(i - 1, i) else: self.rowRects.pop(i) self.rowHeights.pop(i) elif Rect.DistOfRects(self.rowRects[i], self.rowRects[i - 1]) < Rect.DistOfRects( self.rowRects[i], self.rowRects[i + 1]): # combine with the row above self.CombineRowRects(i - 1, i) else: # combine with the row below self.CombineRowRects(i, i + 1)
def main(): gui_scalar = 20 monitor_list = get_monitor_list(gui_scalar) position_monitors(monitor_list) display = get_pygame_display(monitor_list) pygame.init() clock = pygame.time.Clock() mouse_rect = Rect.Rect(width=10, height=10, x=0, y=0, color=(255, 255, 255)) pygame_mouse_rect = Rect.Rect(width=10, height=10, x=0, y=0, color=(255, 255, 255)) prev_mouse_dict = Functions.get_mouse_dict() curr_monitor = None remaining_monitor_list = monitor_list while True: pygame.event.pump() for event in pygame.event.get(): if event.type == pygame.QUIT or pygame.key.get_pressed()[ pygame.K_ESCAPE]: quit() curr_mouse_dict = Functions.get_mouse_dict() # mouse_position = Functions.get_mouse_position(gui_scalar=1, x_delta=0, y_delta=0) # mouse_rect.reposition(*mouse_position) # pygame_mouse_rect.reposition(*curr_mouse_dict["pos"]) curr_monitor, remaining_monitor_list = update_curr_monitor_and_remaining_monitor_list( curr_monitor, remaining_monitor_list, monitor_list, curr_mouse_dict, prev_mouse_dict) drag_monitor(curr_monitor, remaining_monitor_list, curr_mouse_dict, prev_mouse_dict) # drawing ------------------------------------ display.fill((0, 0, 40)) for monitor in monitor_list: monitor.rect.draw(display) mouse_rect.draw(display, center=True) pygame.display.flip() clock.tick(60) # drawing ------------------------------------ prev_mouse_dict = curr_mouse_dict
def obtain_candidate(self,Im,Depth,mask,Point_ini,Angle,isTop): Ini = self.PointatD(Point_ini, Angle, 50) n = [] for d in xrange(20,200,5): P = self.PointatD(Ini,Angle,d) m=0 for i in self.candidates: if i is None or P is None: continue if isTop: if Rect.contains(i[1], P): n.append(m) else: if Rect.contains(i[0], P): n.append(m) m += 1 return n # gray = cv2.cvtColor(label_rgb,cv2.COLOR_RGB2GRAY) # gray = cv2.Canny(gray,0,1) # gray = abs(gray-255)*255 # gray = cv2.erode(gray,kernel) # cnts,h = cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2:] # closer = None # dist_max=9999999999 # for c in cnts: # i+=1 # M = cv2.moments(c) # if int(M["m00"]) !=0: # cX = int(M["m10"] / M["m00"]) # cY = int(M["m01"] / M["m00"]) # # a = np.array((cY+200,cX)) # # b= np.array((Point_ini[0],Point_ini[1])) # # dist = np.linalg.norm(a-b) # # if dist < dist_max and self.inside([(Point_ini[1],Point_ini[0]),f1,f2],((cY+200,cX))): # # dist_max = dist # # closer=(cX,cY) # # draw the contour and center of the shape on the image # cv2.drawContours(Image, [c], -1, (0, 255, 0), 2) # cv2.circle(Image, (cX, cY), 2, (255, 255, 255), -1) # # show the image # # if closer != None: # Point_ini=(Point_ini[0],Point_ini[1]-200) # final_point=(final_point[1],final_point[0]-200) # f1=(f1[1],f1[0]-200) # f2=(f2[1],f2[0]-200) # print final_zero # final_zero=(final_zero[1],final_zero[0]-200) # print final_zero # cv2.circle(Image, Point_ini, 5, (0,0,255), -1) # cv2.circle(Image, closer, 5, (255, 0, 0), -1) # cv2.line(Image, Point_ini, final_point, (0, 255, 255), 2) # cv2.line(Image, Point_ini, final_zero, (255, 255, 0), 2) # cv2.line(Image,Point_ini,f1,(0,255,255),2) # cv2.line(Image, Point_ini, f2, (0, 255, 255), 2)
def setup(): global detector, vs, frame_rate, prev, shotDetector, ppm, cp5, heightField, distField, backboard, rim, courtFloor, rects size(width, height) detector = Detector.Detector() vs = VideoStream(src=0).start() shotDetector = shot.Shot(2.35) frame_rate = 20 prev = 0 ppm = height / 5 # pixels per meter backboard = Rect(width - BACKBOARD_WIDTH * ppm - 5, height - TOP_BACKBOARD * ppm, BACKBOARD_WIDTH * ppm, BACKBOARD_HEIGHT * ppm) rim = Rect(width - BACKBOARD_WIDTH * ppm - 5 - HOOP_D * ppm, height - HOOP_HEIGHT * ppm, HOOP_D * ppm, 5) courtFloor = Rect(0, height - 10, width, 10) rects = [backboard, rim, courtFloor]
def __init__(self, game, location): # dungeon generator self.game = game self.location = location #fill map_dung with "blocked" tiles self.map_dung = [] for y in range(self.game.const.MAP_DUNG_HEIGHT): self.map_dung.append([]) for x in range(self.game.const.MAP_DUNG_WIDTH): self.map_dung[y].append(Tile(Tiles["wall"])) rooms = [] num_rooms = 0 for r in range(self.game.const.MAX_ROOMS): #random width and height w = random.randint(self.game.const.ROOM_MIN_SIZE, self.game.const.ROOM_MAX_SIZE) h = random.randint(self.game.const.ROOM_MIN_SIZE, self.game.const.ROOM_MAX_SIZE) #random position without going out of the boundaries of the map_dung x = random.randint(0, self.game.const.MAP_DUNG_WIDTH - w - 1) y = random.randint(0, self.game.const.MAP_DUNG_HEIGHT - h - 1) new_room = Rect(x, y, w, h) failed = False for other_room in rooms: if new_room.intersect(other_room): failed = True break if not failed: self.create_room(new_room) self.place_objects(new_room) (new_x, new_y) = new_room.center() if num_rooms == 0: self.location.player.x = new_x self.location.player.y = new_y else: (prev_x, prev_y) = rooms[num_rooms-1].center() if random.randint(0, 1) == 1: self.create_h_tunnel(prev_x, new_x, prev_y) self.create_v_tunnel(prev_y, new_y, new_x) else: self.create_v_tunnel(prev_y, new_y, prev_x) self.create_h_tunnel(prev_x, new_x, new_y) rooms.append(new_room) num_rooms += 1
def main(ROIfilename, imgdir, ROIdir, outputdir): ''' :param ROIfilename: :param imgdir: :param ROIdir: :param outputdir: :return: rect(s) of columns seperate ROI into several columns ''' threshold1 = 10 #threshold for binarization threshold2 = 190 #threshold for deciding if the last col has content print("processing " + ROIfilename) imgfilename = GetImgFilename(ROIfilename) img = cv2.imread(os.path.join(imgdir, imgfilename), 0) with open(os.path.join(ROIdir, ROIfilename)) as file: rect = json.load(file) warped, M = Rect.CropRect(img, rect) #local binarization warped_b = cv2.adaptiveThreshold(warped, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 15, threshold1) H, W = warped_b.shape # col index to segment the ROI colIndex = ColIndex(warped_b) col_rects = [] for i in range(len(colIndex) - 1): col = warped_b[:, colIndex[i] + int(W / 50):colIndex[i + 1] - int(W / 50)] if i < len(colIndex) - 2 or np.max(np.sum( col, axis=0)) / 255 > threshold2: #check if last col is empty box_col = [[colIndex[i], 0], [colIndex[i], H - 1], [colIndex[i + 1], 0], [colIndex[i + 1], H - 1]] #get the rect of box_col in original image col_rects.append( Rect.RectOnDstImg(box_col, np.linalg.inv(M), flag_box=True)) #save the rect as json outputpath = os.path.join(outputdir, ROIfilename.split('.')[0] + '.json') with open(outputpath, 'w') as outfile: json.dump(col_rects, outfile) print('writing results to ' + outputpath)
def Split(self): '''某个象限节点内储存的物体数量超过MAX_OBJECTS时,对这个节点进行划分''' subWidth = self.oRect.width // 2 subHeight = self.oRect.height // 2 x = self.oRect.x y = self.oRect.y self.lNodes[0] = CQuadTree(self.iLevel + 1, Rect(x + subWidth, y, subWidth, subHeight)) self.lNodes[1] = CQuadTree(self.iLevel + 1, Rect(x, y, subWidth, subHeight)) self.lNodes[2] = CQuadTree(self.iLevel + 1, Rect(x, y + subHeight, subWidth, subHeight)) self.lNodes[3] = CQuadTree( self.iLevel + 1, Rect(x + subWidth, y + subHeight, subWidth, subHeight))
def SegLargeRow(self, img_b, rowRect, theta, f=0): ''' :param img_b: :param rowRect: :param theta: rotation angle :param f: flag :return: segmented [row_rect] ''' rect = [list(rowRect[0]), list(rowRect[1]), rowRect[2]] if rect[2] < -45: rect[1][0] += 30 else: rect[1][1] += 30 rect[2] += theta warped_b, M = Rect.CropRect(img_b, rect) largeRow = Column(warped_b, M, self.colRect, self.rowHeight) largeRow.SegToRows() # move the center of rows so that they locate within the col if f: rot = ( rowRect[2] - self.colRect[2] ) % 90 # relative rotation of row to col (rowRect[2]=colRect[2]+rot) if rot > 45: rot -= 90 rot += theta # relative rotation of rect to col for i in range(len(largeRow.rowRects)): rect = largeRow.rowRects[i] vec = np.array( [rect[0][0] - rowRect[0][0], rect[0][1] - rowRect[0][1]]) vec = vec * np.tan(np.deg2rad(rot)) vec = [vec[1], -vec[0]] largeRow.rowRects[i] = [[ rect[0][0] + vec[0], rect[0][1] + vec[1] ], rect[1], rect[2]] return largeRow
def SetRows(self, OCR=True): for i in range(len(self.row_rects)): #row rect on col img coordinate row_rect = Rect.RectOnDstImg(self.row_rects[i], self.M_scan2col) self.rows.append(Row(row_rect, i)) if OCR: self.AssignDocumentWordsToRow()
def CombineRowRects(self, i, j): if i != j: #combine rect i and j to i self.rowRects[i] = Rect.CombineRects(self.rowRects[i], self.rowRects[j]) self.rowHeights[i] = GetRowHeight(self.rowRects[i]) self.rowRects.pop(j) self.rowHeights.pop(j)
def get_rect(self, scalar=None): if scalar is None: scalar = 1 if self.width and self.height: return Rect.Rect(width=self.width * scalar, height=self.height * scalar, x=0, y=0) return None
def RemoveMinistry(img, colRects): rect = Rect.CombineRects(colRects[0], colRects[1]) ROI = [list(rect[0]), list(rect[1]), rect[2]] if ROI[1][0] > ROI[1][1]: #divide width by 4 ROI[1][1] /= 4 else: ROI[1][0] /= 4 img_b = Binarization(img, patchSize=31, threshold=10) warped_b, _ = Rect.CropRect(img_b, ROI) warped_b = cv2.medianBlur(warped_b, 3) warped_b = cv2.medianBlur(warped_b, 3) kernel = np.ones([21, 3], np.uint8) warped_b = cv2.morphologyEx(warped_b, cv2.MORPH_CLOSE, kernel) #use CCL to detected largest region ret, labels = cv2.connectedComponents(warped_b) size, index = 0, -1 Height = lambda x: max(x) - min(x) for i in range(1, ret + 1): # O(n^3) if labels[labels == i].shape[0] > warped_b.shape[0] * 3 and Height( np.where(labels == i)[0]) > size: # remove small CCL regions size, index = Height(np.where(labels == i)[0]), i HRange, _ = np.where(labels == index) if min(HRange) > 0.05 * warped_b.shape[0] and min( HRange) < 0.3 * warped_b.shape[0]: for i in range(2): H, theta = min(HRange), colRects[i][2] colRect = [ list(colRects[i][0]), list(colRects[i][1]), colRects[i][2] ] if colRect[1][0] > colRect[1][1]: colRect[1][0] -= H else: colRect[1][1] -= H if theta < -45: theta += 90 colRect[0] = [ colRect[0][0] - H * np.sin(np.deg2rad(theta)) / 2, colRect[0][1] + H * np.cos(np.deg2rad(theta)) / 2 ] colRects[i] = colRect return True return False
def SetCols(self): row_nums = [0] for key in sorted(self.row_rects.keys()): row_nums.append(row_nums[-1] + len(self.row_rects[key])) for i in range(len(self.ocr_jsonfiles)): _, M_scan2col = Rect.CropRect(self.img, self.col_rects[i]) self.cols.append( Col(self.ocr_jsonfiles[i], M_scan2col, self.row_rects[str(i)], i)) self.cols[-1].SetRows()
def obtain_candidate(self,Image,Depth,dep,center,angle): Point1 = Rect.Point(center[0]-50,center[1]-50) Point2 = Rect.Point(center[0] + 50, center[1] + 50) R = Rect.Rect(Point1,Point2) n = 0 for i in self.candidates: if Rect.overlap(R,i[0]): return n n+=1 return None
def __init__(self, screen, price_scaling): """ :param: screen, Geld scaling """ self.screen = screen self.towers = [] self.money = 500 self.price = 200 self.price_scaling = price_scaling # Definiert die benuzbaren Flaechen oder Verbotene self.legal = [ Rect(10, 10, 80, 590), Rect(170, 10, 540, 510), Rect(540, 10, 790, 220), Rect(620, 310, 790, 590) ] self.illegal = []
def __init__(self): self.cap = cv2.VideoCapture(0) ##Tracker for pixel change self.tracker = Tracker.Tracker(False) ##Tracker for ColorTracking #self.tracker = ColourTrack.ColorTracker(False, 60) ##Tracker for fiducials #self.tracker = FiducialTrack.FiducialTrack(False, "fid4.png", (0,255,0)) #self.tracker2 = FiducialTrack.FiducialTrack(False, "fid1.png", (0,0,255)) self.fiducials_activated = False self.score = 0 ##Initializes a list of Rectangle objects from the Rect class. self.rects = [Rect.Rect(self.cap.read()[1]), Rect.Rect(self.cap.read()[1])] self.play_time = 0
def cargarAnimacionEntidad(archivoXML, entidad): # CARGAR ARCHIVO XML try: dom = minidom.parse(archivoXML) # -- CARGAR ANIMACIONES -- animaciones = dom.getElementsByTagName("animacion") for animacion in animaciones: nombreAnimacion = animacion.getAttribute("nombre") entidad.crearAnimacion(nombreAnimacion) # -- CUERPOS CHOQUE -- dictCC = {} cuerposChoque = dom.getElementsByTagName("cuerpoChoque") for cuerpoChoque in cuerposChoque: nombreCuerpoChoque = cuerpoChoque.getAttribute("nombre") x = int(cuerpoChoque.getAttribute("x")) y = int(cuerpoChoque.getAttribute("y")) ancho = int(cuerpoChoque.getAttribute("ancho")) alto = int(cuerpoChoque.getAttribute("alto")) dictCC[nombreCuerpoChoque] = Rect.Rect(x, y, ancho, alto) # -- CARGAR FOTOGRAMAS -- fotogramas = dom.getElementsByTagName("fotograma") for fotograma in fotogramas: nombreFotograma = fotograma.getAttribute("nombre") nombreCuerpoChoque = fotograma.getAttribute("cuerpoChoque") x = int(fotograma.getAttribute("x")) y = int(fotograma.getAttribute("y")) ancho = int(fotograma.getAttribute("ancho")) alto = int(fotograma.getAttribute("alto")) entidad.addFotogramaCuerpoChoque(nombreFotograma, Rect.Rect(x, y, ancho, alto), dictCC[nombreCuerpoChoque]) # -- CARGAR RELACION ANIMACION -> FOTOGRAMAS -- fotoAnimaciones = dom.getElementsByTagName("fotoAnimacion") for fotoAnimacion in fotoAnimaciones: nombreAnimacion = fotoAnimacion.getAttribute("nombreAnimacion") nombreFotograma = fotoAnimacion.getAttribute("nombreFotograma") duracionFotograma = int(fotoAnimacion.getAttribute("duracion")) entidad.addFotogramaAnimacion(nombreAnimacion, nombreFotograma, duracionFotograma) except: print "Error al leer el archivo " + archivoXML
def update_curr_monitor_and_remaining_monitor_list(curr_monitor, remaining_monitor_list, monitor_list, curr_mouse_dict, prev_mouse_dict): for m_i, monitor in enumerate(monitor_list): if curr_mouse_dict["left"] and not prev_mouse_dict["left"]: if Rect.is_point_in_rect(*curr_mouse_dict["pos"], monitor.rect): return monitor, monitor_list[:m_i] + monitor_list[m_i + 1:] elif not curr_mouse_dict["left"] and prev_mouse_dict["left"]: return None, monitor_list return curr_monitor, remaining_monitor_list
def GetRowRects(self, rowLeftIndex, rowRightIndex): ''' :param rowLeftIndex: a list of start index of rows :param rowRightIndex: a list of end index of rows :return: [row rect] computed from rowLeftIndex, rowRightIndex ''' H, W = self.warpedImg_b.shape for i in range(len(rowLeftIndex)): # four pts of the rect box = np.array([[0, rowLeftIndex[i]], [W - 1, rowLeftIndex[i]], [0, rowRightIndex[i]], [W - 1, rowRightIndex[i]]]) rect = Rect.RectOnDstImg(box, np.linalg.inv(self.M), flag_box=True) self.rowRects.append(rect) self.rowHeights.append(GetRowHeight(rect))
def main(ROIRectJson,args): print("processing "+ROIRectJson) scale = 2 img = cv2.imread(os.path.join(args.imgdir,GetImgFilename(ROIRectJson)),0) img = cv2.pyrDown(img) img_b = Binarization(img)*255 H,W = img_b.shape res = np.zeros([H,W,3], np.uint8) with open(os.path.join(args.clsdir,ROIRectJson)) as clsjson: cls = json.load(clsjson) cls=cls["name"] with open(os.path.join(args.rowrectdir, ROIRectJson)) as rectjson: rowrects = json.load(rectjson) tmp=[] for key in rowrects.keys(): tmp+=rowrects[key] rowrects=tmp with open(os.path.join(args.ROIrectdir, ROIRectJson)) as rectjson: ROIrect = json.load(rectjson) #import pdb;pdb.set_trace() boxes={"company name":[], #red "address":[], #green "variable name":[], #golden rod "variable value":[], #dark turquoise "personnel":[]} for i in range(len(rowrects)): box = cv2.boxPoints(tuple(rowrects[i])) box = np.int0(box/scale) boxes[cls[i]].append(box) mask = np.zeros([H,W,3], np.uint8) for key in boxes.keys(): cv2.drawContours(mask, boxes[key], -1, ColorDict[key], -1) b,g,r = mask[:,:,0],mask[:,:,1],mask[:,:,2] #import pdb;pdb.set_trace() b,g,r = b*img_b,g*img_b,r*img_b mask = cv2.merge([b,g,r]) res+=mask res=255-res box = cv2.boxPoints(tuple(ROIrect)) box = np.int0(box/scale) warped,_=Rect.CropRect(res,cv2.minAreaRect(box)) #import pdb;pdb.set_trace() cv2.imwrite(os.path.join(args.outputdir,ROIRectJson.split('.')[0]+'.jpg'),warped)
def __init__(self, row_rect=None, row_index=None): ''' :param row_rect: row_rect of this row :param row_index: index of this row in column :param subrows: if there are multiple rows in this row image, indicate each row by subrow ''' self.row_bbox = None self.row_rect = row_rect if row_rect: self.row_bbox = Rect.OrderPoints(cv2.boxPoints( tuple(row_rect))).tolist() self.words = [] self.subrows = [] self.AOIs = [ ] # area of intersections (normalized by area of each word) self.row_index = str(row_index).zfill(3)
def create_room(): """Создает комнату с рандомными размерами. return: Rect """ rnd = 0 w = libtcod.random_get_int(rnd, const.MIN_ROOM_WIDTH, const.MAX_ROOM_WIDTH) h = libtcod.random_get_int(rnd, const.MIN_ROOM_HEIGHT, const.MAX_ROOM_HEIGHT) x = libtcod.random_get_int(rnd, 1, const.MAP_WIDTH - w - 1) y = libtcod.random_get_int(rnd, 1, const.MAP_HEIGHT - h - 1) room = Rect.Rect(x, y, w, h, "room") return room
def getArea(tweet): sf = Rect(Point(-122.75,36.8), Point(-121.75,37.8)) ny = Rect(Point(-74,40), Point(-73,41)) ch = Rect(Point(-89,41), Point(-88,42)) la = Rect(Point(-119,33), Point(-117,34.5)) if tweet['place'] != None: box = tweet['place']['bounding_box'] coord = box['coordinates'] loc = Rect(Point(coord[0][0][0], coord[0][0][1]), Point(coord[0][2][0], coord[0][2][1])) if sf.overlaps(loc): return "San Fran" if ny.overlaps(loc): return "New York" if ch.overlaps(loc): return "Chicago" if la.overlaps(loc): return "Los Angeles" return None
def create_tonel(x, y, direct): """Создает горизонтальный или вертикальный тонель с рандомной шириной или высотой, с заданными координатами. args: direct -- направление h|0 - горизонтальный, v|1 - вертикальный return: Rect """ rnd = 0 if direct == 1: # UP h = libtcod.random_get_int(rnd, const.MIN_TONEL_HEIGHT, const.MAX_TONEL_HEIGHT) w = 1 y, h = h, y elif direct == 2: # RIGHT h = 1 w = libtcod.random_get_int(rnd, const.MIN_TONEL_WIDTH, const.MAX_TONEL_WIDTH) elif direct == 3: # DOWN h = libtcod.random_get_int(rnd, const.MIN_TONEL_HEIGHT, const.MAX_TONEL_HEIGHT) w = 1 elif direct == 4: # LEFT h = 1 w = libtcod.random_get_int(rnd, const.MIN_TONEL_WIDTH, const.MAX_TONEL_WIDTH) w, x = x, w tonnel = Rect.Rect(x, y, w, h, "tonnel") return tonnel
class Tower(): def __init__(self, x, y): """ :param: X-Koordinate, Y-Koordinate """ self.x = x #pos X self.y = y # pos Y # Sprite self.img = pygame.image.load("sprites/tower.png") self.width = 16 self.height = 16 self.size = 32 # Einstellungen des Towers self.range = 150 # Reichweite der schusse self.cd = 10 # Zeit bevor neuer Schuss (Cooldown) self.prev = 0 # last time shot self.damage = 10 # Schaden # Hitbox self.space = 14 # Freiraum zwischen sprite und nachst mogliche pos self.hitbox = Rect(self.x - self.width - self.space, self.y - self.height - self.space, self.x + self.width + self.space, self.y + self.height + self.space) # Display Einstellungen self.disp_mode = 0 # for highlight self.radius_color = (0, 0, 255, 100) def draw(self, screen): """ Anzeige der Tower :param screen: surface :return: None """ if (self.disp_mode == 0): self.img = pygame.transform.scale(self.img, (self.size, self.size)) screen.blit(self.img, ((self.x - self.img.get_width() / 2), (self.y - self.img.get_height() / 2))) else: self.draw_radius(screen) self.img = pygame.transform.scale(self.img, (self.size, self.size)) screen.blit(self.img, ((self.x - self.img.get_width() / 2), (self.y - self.img.get_height() / 2))) def draw_radius(self, screen): """ Zeichnet den range radius :param : screen :return: None """ surface = pygame.Surface((self.range * 4, self.range * 4), pygame.SRCALPHA, 32) pygame.draw.circle(surface, self.radius_color, (self.range, self.range), self.range, 0) screen.blit(surface, (self.x - self.range, self.y - self.range)) def target(self, clk, screen, enemies): """ Findet den nächst möglichen Gegner und fuegt Schaden zu :param : Clock, Screen, list of enemies :return: Money gained """ money = 0 target = [] # Moegliche Ziele # Sort enemies by proximity for en in enemies: dis = math.sqrt((self.x - en.x)**2 + (self.y - en.y)**2) if (dis < self.range): target.append((en, dis)) target.sort(key=lambda a: a[1]) # if target exists if (len(target) > 0): if (clk - self.prev > self.cd): # not on cooldown self.prev = clk pygame.draw.line(screen, (255, 255, 255), (self.x, self.y), (target[0][0].x, target[0][0].y), 7) # Laser Beam index = enemies.index(target[0][0]) enemies[index].health -= self.damage if (enemies[index].health <= 0): money += enemies[index].value enemies.pop(index) return money def highlight(self): """ Change Mode wenn Maus über den Tower :return: None :todo: possible overlap of hitbox """ (mouse_x, mouse_y) = pygame.mouse.get_pos() if (self.hitbox.inside(mouse_x, mouse_y)): self.disp_mode = 1 else: self.disp_mode = 0
def part1(): # Starting point rect_list = [] # Open the file filename = "./day03/day03input.txt" #filename = "./day03/sample.txt" with open(filename, "r") as infile: for line in infile: # Each line looks like this: # - Starts with hash (#), followed by a number and a space # - Then left corner, comma, top corner, followed by a colon # - Then the width, an 'x', and the height # Get the ID current_char = 1 # Bypass the leading hash while not line[current_char].isspace(): current_char += 1 id = int(line[1:current_char]) # Skip all the cruft (whitespace and the @) while line[current_char].isspace() or line[current_char] == '@': current_char += 1 start = current_char # Get the left coordinate while line[current_char] != ',': current_char += 1 left = int(line[start:current_char]) start, current_char = current_char + 1, current_char + 1 # Get the top coordinate while line[current_char] != ':': current_char += 1 top = int(line[start:current_char]) start, current_char = current_char + 1, current_char + 1 # Get the width while line[current_char] != 'x': current_char += 1 width = int(line[start:current_char]) start, current_char = current_char + 1, current_char + 1 # Get the height height = int(line[start:]) #print(f"{id} is ({left}, {top}, {width}, {height}).") rect_list.append(Rect.Rect(left, top, width, height)) overlap = [[0 for i in range(1000)] for j in range(1000)] total_overlap = 0 for first in range(0, len(rect_list)): for second in range(first + 1, len(rect_list)): new_rect = rect_list[first].overlap(rect_list[second]) if new_rect is not None: rect_list[first].has_overlap = True rect_list[second].has_overlap = True for w in range(new_rect.left, new_rect.left + new_rect.width): for h in range(new_rect.top, new_rect.top + new_rect.height): if not overlap[w][h]: total_overlap += 1 overlap[w][h] = 1 print(f"Part 1: Overlap = {total_overlap}") for first in range(0, len(rect_list)): if not rect_list[first].has_overlap: print(f"Part 2: Swatch {first+1} has no overlap!")
def main(pagefilename, args): ''' :return: rect(s) of detected ROI estimate the ROI by finding the vertical lines ''' #if "pr1956_f0006_2_1" not in pagefilename: # return 0 print("processing " + pagefilename) imgfilename = '_'.join(pagefilename.split('_')[:-1]) + '.png' img = cv2.imread(os.path.join(args.inputdir, imgfilename), 0) with open(os.path.join(args.pagedir, pagefilename)) as file: rect = json.load(file) warped, M_scan2page = Rect.CropRect(img, rect) img = cv2.pyrDown(cv2.pyrDown(warped)) scale = 2**2 # remove salt-and-pepper noise, reduce the number of CCL areas img = cv2.medianBlur(img, 3) img = cv2.medianBlur(img, 3) # local binarization img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 15, 5) #cv2.imwrite('binary1.png', img) # filling small holes on vertical lines kernel = np.ones([5, 5], np.uint8) img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) # CCL ret, labels = cv2.connectedComponents(img) # CCL # find candidate of the four vertical lines for i in range(1, ret): # O(n^3), that's why we need downsampling HRange, WRange = np.where(labels == i) if (max(HRange) - min(HRange)) > 0.6 * img.shape[0] and ( max(WRange) - min(WRange)) > 0.6 * img.shape[1]: mask = (labels == i).astype(np.uint8) #kernel = np.ones([3, 3], np.uint8) #mask= cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) kernel = np.ones([3, 11], np.uint8) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) #cv2.imwrite('binary2.png', mask) mask = mask.astype(np.uint8) h_mid, w_mid = int(img.shape[0] / 2), int(mask.shape[1] / 2) if np.sum(mask[h_mid - 100:h_mid + 100, w_mid - 100:w_mid + 100]) > 0: break #import pdb;pdb.set_trace() if i == ret: print("no output for " + pagefilename) return 0 _, cnts, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) lines = np.concatenate(cnts, axis=0) # fit a rect that include the lines rect = cv2.minAreaRect(lines) box = cv2.boxPoints(tuple(rect)) * scale rect = Rect.RectOnDstImg(box, np.linalg.inv(M_scan2page), True) #save the rect as json with open(os.path.join(args.outputdir, pagefilename), 'w') as outfile: json.dump(rect, outfile)
def __init__(self, lObjs): self.oRect = Rect(0, 0, 1000, 500) # 初始屏幕尺寸 self.oTree = CQuadTree(0, self.oRect) # 创建四叉树根结点 self.lAllObjs = lObjs # 场景中所有物体 self.AddObjs2QuadTree()
def AddColumn(self, colRect): col_b, M = Rect.CropRect(self.img_b, colRect) col = Column(col_b, M, colRect) self.columns.append(col)