def test_class_rect(): r1 = Rect(10, 10, 50, 50) r2 = eval(repr(r1)) print(r1, str(r1.area()), sep=':') print(r2, str(r2.area()), sep=':') r1.draw() r2.draw()
def test_class_rect(): r1 = Rect(10, 10, 50, 50) r2 = eval(repr(r1)) print(r1, str(r1.area()), sep=':') print(r2, str(r2.area()), sep=':') r1.draw() r2.draw() # 비교 연산자 오버로딩 print(Rect(10, 20) == Rect(20, 10)) print(Rect(10, 10) > Rect(10, 5)) print(Rect(10, 20) < Rect(20, 10))
def _get_rect_tensor_descs_no_overlap(self, rect, window_rect, factor): assert isinstance(rect, Rect) assert isinstance(window_rect, Rect) window_size = window_rect.height() map_size = window_size >> (factor + self.num_poolings) edge = window_size / map_size center = rect.center() sx = int(center.x - window_rect.left) sy = int(center.y - window_rect.top) x = int(sx / edge) y = int(sy / edge) res = [] for dx in range(-3, 3): for dy in range(-2, 2): wx = x + dx wy = y + dy if 0 <= wx and wx < map_size and 0 <= wy and wy < map_size: # window coord wrect = Rect(wx * edge, wy * edge, (wx + 1) * edge, (wy + 1) * edge) # img coord wrect.move(window_rect.top, window_rect.left) i = wrect.intersection(rect) if i.valid(): #self._check_rect(rect, wrect): # img coord #i = wrect.intersection(rect) qual_out = i.area() / float(wrect.area()) # if qual_out <= 0: # print rect ,wrect, i # window coord i.move(-wrect.top, -wrect.left) # window 0..1 coord i.stretch(1.0 / wrect.height(), 1.0 / wrect.width()) if qual_out > 0.01: res.append((wy, wx, i.left, i.top, i.right, i.bottom, qual_out)) return res
def edit_hippo_dataset(data_dir, images_to_edit, input_project, output_project, include_selected): filenames_to_edit = {f'{exp_id}-{slice_id}' for exp_id, rng in ast.literal_eval(images_to_edit).items() for slice_id in rng} \ if images_to_edit is not None else None project = json.load(open(input_project, 'rt')) entries = project['_via_img_metadata'] new_entries = dict() for num, (name, entry) in enumerate(entries.items()): print(f"Processing image {num + 1} of {len(entries)}") if filenames_to_edit is None or entry["filename"].split('.')[0] in filenames_to_edit: image_path = f'{data_dir}/{entry["filename"]}' image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) contours = [ np.asarray(list(zip(r['shape_attributes']['all_points_x'], r['shape_attributes']['all_points_y']))) for r in entry['regions']] mask = np.zeros_like(image) cv2.fillPoly(mask, contours, color=1) while True: image_to_display = image.copy() image_to_display[mask != 0] = np.minimum(image_to_display.astype(np.uint16)[mask != 0] * 4, 255).astype(np.uint8) image_to_display = cv2.cvtColor(image_to_display, cv2.COLOR_GRAY2BGR) image_to_display[:, :, 0][mask == 0] = 0 image_to_display[:, :, 1][mask == 0] = 0 image_to_display = cv2.resize(image_to_display, (0, 0), fx=3, fy=3) roi = cv2.selectROI("Select region to edit", image_to_display) print(roi) roi = Rect(*(np.asarray(list(roi)) // 3)) if roi.area() == 0: break mask[roi.y: roi.y + roi.h, roi.x: roi.x + roi.w] = 1 if include_selected else 0 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = [c.squeeze() for c in contours if c.shape[0] > 1 and cv2.boundingRect(c)[3] > 50] new_entries[f'{entry["filename"]}{entry["size"]}'] = create_file_entry(f'{data_dir}/{entry["filename"]}', contours) else: new_entries[name] = entry project['_via_img_metadata'] = new_entries json.dump(project, open(output_project, 'wt'))
def update_cropped(boundary, rect, current_area): inner_rect = Rect(rect.lindex, rect.rindex, max([rect.start, boundary.start]), min([rect.end, boundary.end])) return max([inner_rect.area(), current_area])
image = cv2.equalizeHist(image) image = image * mask ret, thresh = cv2.threshold(image, 80, 255, 0) contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = [ c.squeeze() for c in contours if c.shape[0] > 1 and cv2.boundingRect(c)[3] > 50 ] pattern = np.zeros_like(image) cv2.fillPoly(pattern, contours, color=1) while True: roi = cv2.selectROI("Select region to edit", cv2.resize(pattern * image, (0, 0), fx=3, fy=3)) print(roi) roi = Rect(*(np.asarray(list(roi)) // 3)) if roi.area() == 0: break pattern[roi.y:roi.y + roi.h, roi.x:roi.x + roi.w] = 0 contours, _ = cv2.findContours(pattern, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = [ c.squeeze() for c in contours if c.shape[0] > 1 and cv2.boundingRect(c)[3] > 50 ] new_entries[f'{entry["filename"]}{entry["size"]}'] = create_file_entry( f'{output_dir}/{entry["filename"]}', contours) project['_via_img_metadata'] = new_entries json.dump(project, open(f'{output_dir}/annotations.json', 'wt'))
class Land_Plot: def __init__(self, matrix, fertile_symbol): self.matrix = matrix self.active_rects = [] self.largest_rect = Rect(1, 0) self.active_row = 0 self.fertile_symbol = fertile_symbol self.all_rects = [self.largest_rect] def process_all_rows(self): self.__init__(self.matrix, self.fertile_symbol) while (self.active_row < len(self.matrix)): self.process_row() self.retire_rects(self.active_rects) self.sort_all_rects() return self.largest_rect def process_row(self): row = self.matrix[self.active_row] row_rects = self.make_rects(row) self.append_row(row_rects) self.active_row += 1 def make_rects(self, row): i = 0 rects = [] current_rect = None while i < len(row): if row[i] == self.fertile_symbol: if current_rect == None: current_rect = Rect(i, i) rects.append(current_rect) else: current_rect.bump_rindex() else: current_rect = None i += 1 return rects def append_row(self, row_rects): ''' 1: active_rects that are not contained within one of the row_rects are retired. active_rects that are have their height increased by 1. 2: row_rects that are not contained within an active_rect start a new active_rect with a height of 1 3: when an active_rect and row_rect share part of a base, but the active_rect is not contained within the row_rect, a new active_rect is created with a height of the active_rect + 1, and a base of the shared base. ''' to_retire = [] to_append = [] i = 0 while i < len(row_rects): j = 0 rr = row_rects[i] append_later = True while j < len(self.active_rects): ar = self.active_rects[j] if rr.shares_base_with(ar): # ar and rr interact if ar.contained_within(rr): if rr.contained_within(ar): # 1 ar.bump_end() append_later = False else: # 1 and 2 ar.bump_end() elif rr.contained_within(ar): # 1 and 3 to_retire.append(ar) to_append.append(ar.combine_rects(rr)) append_later = False else: to_retire.append(ar) to_append.append(ar.combine_rects(rr)) # 1 2 and 3 j += 1 if append_later: to_append.append( Rect(rr.lindex, rr.rindex, self.active_row, self.active_row)) i += 1 # end while loops self.retire_rects(to_retire) self.active_rects += to_append self.all_rects += to_append def retire_rects(self, rects_to_retire): new_active_rects = [] for i in range(0, len(self.active_rects)): current_rect = self.active_rects[i] if current_rect in rects_to_retire: if current_rect.area() > self.largest_rect.area(): self.largest_rect = current_rect else: new_active_rects.append(current_rect) self.active_rects = new_active_rects def sort_all_rects(self): self.sort_from(0, len(self.all_rects) - 1) def sort_from(self, l, r): if r - l > 0: m = (l + r) // 2 rs = self.all_rects if rs[l].area() > rs[m].area(): if rs[m].area() > rs[r].area(): c = m else: c = r elif rs[l].area() > rs[r].area(): c = l else: c = r [rs[c], rs[l]] = [rs[l], rs[c]] i = l + 1 j = i while i < r: if rs[i].area() > rs[l].area(): [rs[i], rs[j]] = [rs[j], rs[i]] j += 1 i += 1 [rs[l], rs[j - 1]] = [rs[j - 1], rs[l]] self.sort_from(l, j - 1) self.sort_from(j, r)
from rect import Rect # from sys import argv # import orientacao_objeto # import orientacao_objeto as oop if __name__ == "__main__": """animal = MyAnimal(gender=False, age=25) print(animal.age) animal.walk() print(animal.species) # delattr(animal, "species") print(getattr(animal, "hungry")) delattr(animal, "age") print(getattr(animal, "age", "idade removida")) print(animal.walking is True) herbivore = Herbivore() print(herbivore.walking) man = Man(legs=2) print(man.food_type) print(man.legs) Logger.info("Verificando... info") print(f"Classmethod execution: {Math.add(3, 4)}")""" rect = Rect(20, 30) print(rect.area()) rect.__dir__ a = [1, 2, 3, 4, 5, 6, 7] print(type(a)) print(*a)