def draw(self, action): action = np.clip(action, -1, 1) a = scale(action[0:3], -1, 1, 0, 1) b = scale(action[3:13], -1, 1, 0, config['STATE_DIM'][0] - 1) c = scale(action[13:14], -1, 1, 0, 4) action = np.concatenate([a, b, c]).reshape(config['ACTION_DIM'], ) # Parameter Validation and noises action_category = np.argmax(action[0:3]) if self.stroke_count == 0: axis = np.asarray(action[3:13], dtype=np.uint8) + np.int_( np.random.normal(0, 2, action[3:13].shape[0])) c_p = action[13] + np.random.normal(0, 1) else: axis = np.asarray(action[3:13], dtype=np.uint8) c_p = action[13] for i in range(axis.shape[0]): if axis[i] < 2: axis[i] = 2 elif axis[i] >= self.dim[0] - 2: axis[i] = self.dim[0] - 2 if action_category == 1: self.stroke_count += 1 # Draw line rr, cc = line(axis[0], axis[1], axis[2], axis[3]) self.canvas[rr, cc] = 1 if action_category == 2: self.stroke_count += 1 # Draw Curve try: rr, cc = bezier_curve(axis[4], axis[5], axis[6], axis[7], axis[8], axis[9], c_p) except MemoryError: while True: try: _x1, _y1 = move_point(axis[4], axis[5]) _x2, _y2 = move_point(axis[6], axis[7]) _x3, _y3 = move_point(axis[8], axis[9]) rr, cc = bezier_curve(_x1, _y1, _x2, _y2, _x3, _y3, c_p) break except MemoryError: continue try: self.canvas[rr, cc] = 1 except IndexError: rr = np.clip(rr, 0, config['STATE_DIM'][0] - 1) cc = np.clip(cc, 0, config['STATE_DIM'][1] - 1) self.canvas[rr, cc] = 1
def test_bezier_curve_shape(): img = np.zeros((15, 20), 'uint8') x1, y1 = (1, 5) x2, y2 = (6, 11) x3, y3 = (1, 14) rr, cc = bezier_curve(x1, y1, x2, y2, x3, y3, 2, shape=(15, 20)) img[rr, cc] = 1 shift = 5 img_ = np.zeros((15 + 2 * shift, 20), 'uint8') x1, y1 = (1 + shift, 5) x2, y2 = (6 + shift, 11) x3, y3 = (1 + shift, 14) rr, cc = bezier_curve(x1, y1, x2, y2, x3, y3, 2, shape=None) img_[rr, cc] = 1 assert_array_equal(img, img_[shift:-shift, :])
def test_bezier_curve_shape(): img = np.zeros((15, 20), 'uint8') r0, c0 = 1, 5 r1, c1 = 6, 11 r2, c2 = 1, 14 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 2, shape=(15, 20)) img[rr, cc] = 1 shift = 5 img_ = np.zeros((15 + 2 * shift, 20), 'uint8') r0, c0 = 1 + shift, 5 r1, c1 = 6 + shift, 11 r2, c2 = 1 + shift, 14 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 2, shape=None) img_[rr, cc] = 1 assert_array_equal(img, img_[shift:-shift, :])
def abstract(self, es): #pick some points in the edge list, and reconnect the points by a quadratic bezier curve w = es #the weight to control the middle point defining_points = [] ab = self.abstraction_level for i, e in enumerate(self.edge): if (i % ab == 0): defining_points.append(e) #defining_points.append(defining_points[0]) results = [] start_point = 0 end_point = len(defining_points) - 1 - ((len(defining_points) - 1) % 2) if (end_point != len(defining_points) - 1): last = defining_points[end_point:] defining_points.insert( len(defining_points) - 1, [last[0][0], last[1][1]]) for i in range(start_point, end_point, 2): cpt = defining_points[i:i + 3] rr, cc = bezier_curve(cpt[0][0], cpt[0][1], cpt[1][0], cpt[1][1], cpt[2][0], cpt[2][1], es) #print i,cpt #print i,zip(rr,cc) results += zip(rr, cc) rr, cc = line(defining_points[end_point][0], defining_points[end_point][1], defining_points[start_point][0], defining_points[start_point][1]) results += zip(rr, cc) #delete the duplicate points final_results = list(set(results)) #remain the previous order final_results.sort(key=results.index) self.edge = final_results
def test_bezier_curved_weight_neq_1(): img = np.zeros((23, 10), 'uint8') x1, y1 = (1, 1) x2, y2 = (11, 11) x3, y3 = (21, 1) rr, cc = bezier_curve(x1, y1, x2, y2, x3, y3, 2) img[rr, cc] = 1 assert_equal(img[x1, y1], 1) assert_equal(img[x3, y3], 1) img_ = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) assert_equal(img, img_)
def test_bezier_curved_weight_neq_1(): img = np.zeros((23, 10), 'uint8') r0, c0 = 1, 1 r1, c1 = 11, 11 r2, c2 = 21, 1 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 2) img[rr, cc] = 1 assert_equal(img[r0, c0], 1) assert_equal(img[r2, c2], 1) img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_equal(img, img_)
def test_bezier_curved_weight_neq_1(): img = np.zeros((23, 10), 'uint8') r0, c0 = 1, 1 r1, c1 = 11, 11 r2, c2 = 21, 1 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 2) img[rr, cc] = 1 assert_equal(img[r0, c0], 1) assert_equal(img[r2, c2], 1) img_ = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) assert_equal(img, img_)
def test_bezier_curved_weight_neq_1(): img = np.zeros((23, 10), 'uint8') x1, y1 = (1, 1) x2, y2 = (11, 11) x3, y3 = (21, 1) rr, cc = bezier_curve(x1, y1, x2, y2, x3, y3, 2) img[rr, cc] = 1 assert_equal(img[x1, y1], 1) assert_equal(img[x3, y3], 1) img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_equal(img, img_)
def _indices_of_path(path, scale=1): """ Retrieve pixel indices (integer values). Parameters ---------- path: SVG-like path formatted as JSON string The path is formatted like ['M', x0, y0], ['Q', xc1, yc1, xe1, ye1], ['Q', xc2, yc2, xe2, ye2], ... ['L', xn, yn] where (xc, yc) are for control points and (xe, ye) for end points. Notes ----- I took a weight of 1 and it seems fine from visual inspection. """ rr, cc = [], [] for (Q1, Q2) in zip(path[:-2], path[1:-1]): # int(round()) is for Python 2 compatibility inds = draw.bezier_curve(int(round(Q1[-1] / scale)), int(round(Q1[-2] / scale)), int(round(Q2[2] / scale)), int(round(Q2[1] / scale)), int(round(Q2[4] / scale)), int(round(Q2[3] / scale)), 1) rr += list(inds[0]) cc += list(inds[1]) return rr, cc
def _get_unrotated_rr_cc(self): return draw.bezier_curve(self.ystart, self.xstart, self.ymid, self.xmid, self.yend, self.xend, weight=self.weight)
def test_bezier_curve_straight(): image = np.zeros((200, 200), dtype=int) r0, c0 = 50, 50 r1, c1 = 150, 50 r2, c2 = 150, 150 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 0) image[rr, cc] = 1 image2 = np.zeros((200, 200), dtype=int) rr, cc = line(r0, c0, r2, c2) image2[rr, cc] = 1 assert_array_equal(image, image2)
def test_bezier_curve_straight(): image = np.zeros((200, 200), dtype=int) x0 = 50 y0 = 50 x1 = 150 y1 = 50 x2 = 150 y2 = 150 rr, cc = bezier_curve(x0, y0, x1, y1, x2, y2, 0) image [rr, cc] = 1 image2 = np.zeros((200, 200), dtype=int) rr, cc = line(x0, y0, x2, y2) image2 [rr, cc] = 1 assert_array_equal(image, image2)
def test_bezier_curve_straight(): image = np.zeros((200, 200), dtype=int) x0 = 50 y0 = 50 x1 = 150 y1 = 50 x2 = 150 y2 = 150 rr, cc = bezier_curve(x0, y0, x1, y1, x2, y2, 0) image[rr, cc] = 1 image2 = np.zeros((200, 200), dtype=int) rr, cc = line(x0, y0, x2, y2) image2[rr, cc] = 1 assert_array_equal(image, image2)
def draw_arc(min_angle, max_angle, array_shape, intensity=255, weight=0.4, directed=None): ''' Method which draws an Arc. :param min_angle: int, minimal angle for curve generation :param max_angle: int, maximum angle for curve generation :param array_shape: tuple(int, int), shape of image :param intensity: int, set intensity of arc :param weight: float, middle control point weight, tension of line :param directed: tuple(center point area1, center point area2, radius) :return: 2d array, containing bezier curve like arc ''' gamma = random.randint(min_angle, max_angle) arr = np.zeros(array_shape, dtype=np.uint8) length = array_shape[1] width = array_shape[0] if directed is None: p1 = (random.randint(0, width), random.randint(0, length)) p2 = (random.randint(0, width), random.randint(0, length)) else: p1 = (random.randint(directed[0][0] - directed[2], directed[0][0] + directed[2]), random.randint(directed[0][1] - directed[2], directed[0][1] + directed[2])) p2 = (random.randint(directed[1][0] - directed[2], directed[1][0] + directed[2]), random.randint(directed[1][1] - directed[2], directed[1][1] + directed[2])) alpha = (180 - gamma) / 2 p1p2 = math.sqrt(np.square(p2[0] - p1[0]) + (np.square(p2[1] - p1[1]))) p1pm = math.sin(alpha) / math.sin(gamma) * p1p2 x_p3 = int(abs(p1pm * math.cos(alpha))) y_p3 = int(abs(p1pm * math.sin(alpha))) # draw bezier curve rr, cc = bezier_curve(p1[0], p1[1], x_p3, y_p3, p2[0], p2[1], weight, array_shape) arr[rr, cc] = intensity return arr
def parse_obj(obj): """Create (576, 768) binary mask from object data""" scale = 1 / obj['scaleX'] path = obj['path'] rr, cc = [], [] # find indices of SVG pathusing bezier curve for (Q1, Q2) in zip(path[:-2], path[1:-1]): inds = draw.bezier_curve(int(round(Q1[-1] / scale)), int(round(Q1[-2] / scale)), int(round(Q2[2] / scale)), int(round(Q2[1] / scale)), int(round(Q2[4] / scale)), int(round(Q2[3] / scale)), 1) rr += list(inds[0]) cc += list(inds[1]) radius = round(obj['strokeWidth'] / 2. / scale) # create mask mask = np.zeros((576, 768), dtype=np.bool) mask[rr, cc] = 1 mask = ndimage.binary_dilation(mask, morphology.disk(radius)) return mask
def draw_bezier_curve_line(im, red, green, blue): shape = im.shape row_length = shape[1] column_length = shape[2] r0 = np.random.randint(0, high=row_length) c0 = np.random.randint(0, high=column_length) r1 = np.random.randint(0, high=row_length) c1 = np.random.randint(0, high=column_length) r2 = np.random.randint(0, high=row_length) c2 = np.random.randint(0, high=column_length) weight = np.random.randint(0, 11) rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, weight, (224, 224)) im[0, rr, cc] = red # im[0][rr,cc]? im[1, rr, cc] = green im[2, rr, cc] = blue return im
def addCurve(img, x_range=(0, 64), y_range=(0, 64), val=1, dil_range=(2, 4), shape=(64, 64)): """Adds a random line to img, which could be a 2D numpy array or torch tensor. Mutates the input img. Arguments --------- x_range: The range over x values which the control points can take y_range: The range over y values which the control points can take val: The value to fill at points on the added line shape: The shape of the image to truncate the curve if it exceeds the limits dil_range: The range of kernel sizes to randomly choose between for dilating the drawn object. Effectively corresponds to stroke width. """ r, c = d.bezier_curve(randint(*x_range), randint(*y_range), randint(*x_range), randint(*y_range), randint(*x_range), randint(*y_range), 1, shape=shape) temp_img = np.zeros(shape) temp_img[r, c] = val dilate_size = np.random.randint(*dil_range) temp_img = grey_dilation(temp_img, size=(dilate_size, dilate_size)) img[np.where(temp_img == val)] = val return img
def draw(self, action): assert self.goal is not None if self.previous_score is None: self.previous_score = \ self.classifier.get_score(self.canvas.reshape(-1, self.dim[0], self.dim[1], 1), self.goal) # do_nothing, q_line, q_curve, x0_line, y0_line, x1_line ,y1_line, # x0_c, y0_c, x1_c, y1_c, x2_c, y2_c, c if self.stroke_count > self.max_stroke: self.terminal = True # Parameter Validation and noises action_category = np.argmax(action[0:3]) axis = np.asarray(action[3:13], dtype=np.uint8) + np.int_( np.random.normal(0, 3, action[3:13].shape[0])) c_p = action[13] + np.random.normal(0, 1) for i in range(axis.shape[0]): if axis[i] < 0: axis[i] = 1 elif axis[i] >= self.dim[0]: axis[i] = self.dim[0] - 2 if action_category == 1: self.stroke_count += 1 # Draw line rr, cc = line(axis[0], axis[1], axis[2], axis[3]) self.canvas[rr, cc] = 1 if action_category == 2: self.stroke_count += 1 # Draw Curve rr, cc = bezier_curve(axis[4], axis[5], axis[6], axis[7], axis[8], axis[9], c_p) try: self.canvas[rr, cc] = 1 except IndexError: print(axis[4], axis[5], axis[6], axis[7], axis[8], axis[9], c_p) print(rr) print(cc) raise score = self.classifier.get_score( self.canvas.reshape(-1, self.dim[0], self.dim[1], 1), self.goal) if score > 0.9: self.terminal = True if action_category == 0: self.terminal = True #reward = 10*score**3 reward = 1 if score > self.previous_score: pass # reward = 1 + score - self.previous_score else: reward = 0 ''' if self.terminal: reward = reward + np.log(score) + 0.7 ''' if self.terminal and self.stroke_count == 0: reward = -10 self.previous_score = score return U.to_one_hot(self.goal, self.classifier.number_of_goals ), self.canvas, reward, self.terminal
img[rr, cc, 1] = 1 # fill circle rr, cc = disk((200, 200), 100, shape=img.shape) img[rr, cc, :] = (1, 1, 0) # fill ellipse rr, cc = ellipse(300, 300, 100, 200, img.shape) img[rr, cc, 2] = 1 # circle rr, cc = circle_perimeter(120, 400, 15) img[rr, cc, :] = (1, 0, 0) # Bezier curve rr, cc = bezier_curve(70, 100, 10, 10, 150, 100, 1) img[rr, cc, :] = (1, 0, 0) # ellipses rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 4.) img[rr, cc, :] = (1, 0, 1) rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=-math.pi / 4.) img[rr, cc, :] = (0, 0, 1) rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 2.) img[rr, cc, :] = (1, 1, 1) ax1.imshow(img) ax1.set_title('No anti-aliasing') ax1.axis('off')
# 1-D random sample flat_mask = mask.reshape([1, -1]) index = np.arange(flat_mask.size) # keep those pixels that are in the target area index_mask = np.multiply(flat_mask, index) index_mask = index_mask[index_mask != 0] l = np.random.choice(index_mask, 3) # convert to 2D coordinates X = np.floor_divide(l, I.shape[1]) + 1 Y = np.remainder(l, I.shape[1]) # fit bezier curve rr, cc = draw.bezier_curve(X[0], Y[0], X[1], Y[1], X[2], Y[2], \ weight=random.uniform(0, 5),shape=(I.shape[0], I.shape[1])) area_scribbles[rr, cc] = 1 area_scribbles = np.multiply(area_scribbles, mask) scribbles = np.add(scribbles, area_scribbles) start_ = time.clock() dst = cv.pyrMeanShiftFiltering(I, 25, 30, termcrit=(cv.TERM_CRITERIA_MAX_ITER+ \ cv.TERM_CRITERIA_EPS, 5, 1)) end = time.clock() print("Filtering time used: ", end - start_) # extend matrix dimensions scribbles = np.expand_dims(scribbles, axis=2) scribbles = np.repeat(scribbles, 3, axis=2) coloured_scribbles = np.multiply(dst, scribbles).astype(np.int32)
img[rr, cc, 1] = 1 # fill circle rr, cc = circle(200, 200, 100, img.shape) img[rr, cc, :] = (1, 1, 0) # fill ellipse rr, cc = ellipse(300, 300, 100, 200, img.shape) img[rr, cc, 2] = 1 # circle rr, cc = circle_perimeter(120, 400, 15) img[rr, cc, :] = (1, 0, 0) # Bezier curve rr, cc = bezier_curve(70, 100, 10, 10, 150, 100, 1) img[rr, cc, :] = (1, 0, 0) # ellipses rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 4.) img[rr, cc, :] = (1, 0, 1) rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=-math.pi / 4.) img[rr, cc, :] = (0, 0, 1) rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 2.) img[rr, cc, :] = (1, 1, 1) ax1.imshow(img) ax1.set_title('No anti-aliasing') ax1.axis('off')
# coding: utf-8 #!/usr/bin/python import os import random from skimage import draw,data,io import numpy as np import matplotlib.pyplot as plt os.chdir(os.path.dirname(__file__)) img=io.imread("a.png") #绘制曲线 #y0, x0 : int #y1, x1 : int #y2, x2 : int #weight : double rr, cc = draw.bezier_curve(random.randint(0, 56),5, random.randint(0, 56), 25, random.randint(0, 56), 50, 2) #设置曲线颜色 curve_color=random.randint(0, 100) draw.set_color(img,[rr,cc],[curve_color,curve_color,curve_color]) draw.set_color(img,[rr+1,cc],[curve_color,curve_color,curve_color]) draw.set_color(img,[rr-1,cc],[curve_color,curve_color,curve_color]) img=img.astype(np.uint8) io.imshow(img) plt.show()
from skimage.draw import bezier_curve import time tic = time.time() for i in range(1000): bezier_curve(51, 51, 491, 491, 51, 491, 128) print(time.time() - tic)
#5、贝塞儿曲线 #格式:skimage.draw.bezier_curve(y1,x1,y2,x2,y3,x3,weight) #y1,x1表示第一个控制点坐标 #y2,x2表示第二个控制点坐标 #y3,x3表示第三个控制点坐标 #weight表示中间控制点的权重,用于控制曲线的弯曲度。 from skimage import draw, data import matplotlib.pyplot as plt img = data.chelsea() rr, cc = draw.bezier_curve(150, 50, 50, 280, 260, 400, 2) draw.set_color(img, [rr, cc], [255, 0, 0]) plt.imshow(img, plt.cm.gray) #6、画空心圆 #和前面的画圆是一样的,只是前面是实心圆,而此处画空心圆,只有边框线。 #格式:skimage.draw.circle_perimeter(yx,yc,radius) #yx,yc是圆心坐标,radius是半径 from skimage import draw, data import matplotlib.pyplot as plt img = data.chelsea() rr, cc = draw.circle_perimeter(150, 150, 50)
def update_gt(self, ev): data_shape = self.DM.data_shape level = self.DM.gtselected['level'] label = self.DM.gtselected['label'] plevel = self.DM.gtselected['parent_level'] plabel = self.DM.gtselected['parent_label'] t0 = time.time() # Get positions log.debug('* Smoothing indexes') cr, cc = self.current pr, pc = [], [] if self.DM.gtinterpolation == 'bezier': for i in range(1, len(cr) - 1, 2): line_r, line_c = bezier_curve(cr[i - 1], cc[i - 1], cr[i], cc[i], cr[i + 1], cc[i + 1], 2) pr.extend(line_r) pc.extend(line_c) if len(cr) % 2 == 0: line_r, line_c = line(cr[-2], cc[-2], cr[-1], cc[-1]) pr.extend(line_r) pc.extend(line_c) else: for i in range(len(cr) - 1): line_r, line_c = line(cr[i], cc[i], cr[i + 1], cc[i + 1]) pr.extend(line_r) pc.extend(line_c) pos = np.c_[pr, pc] if pos.shape[0] == 0: pos = np.c_[cr, cc] print("Time Smooth:", time.time() - t0) t0 = time.time() _, region_maxy, region_maxx = self.DM.region_shape() pos[:, 0] = np.clip(pos[:, 0], 0, region_maxy - 1) pos[:, 1] = np.clip(pos[:, 1], 0, region_maxx - 1) radius = self.DM.gtradius ymin, xmin = pos.min(0) - radius ymax, xmax = pos.max(0) + radius ymin = max(ymin, 0) xmin = max(xmin, 0) ymax = min(ymax, region_maxy - 1) xmax = min(xmax, region_maxx - 1) mask2d = np.zeros((ymax - ymin + 1, xmax - xmin + 1), np.bool) mask2d[pos[:, 0] - ymin, pos[:, 1] - xmin] = True mask2d = ndi.binary_dilation(mask2d, disk(radius).astype(np.bool)) slice_z = slice(self.idx, self.idx + 1) slice_y = slice(ymin, ymax + 1) slice_x = slice(xmin, xmax + 1) pos = np.column_stack(np.where(mask2d)) print("Time Dilate:", time.time() - t0) t0 = time.time() log.debug('* Calculating indexes') if self.DM.gtlevel == 1: t0 = time.time() sv = self.DM.load_slices(self.DM.svlabels, slice_z, slice_y, slice_x, apply_roi=True) sv = sv[0, pos[:, 0], pos[:, 1]] sv = np.unique(sv) if np.isnan(sv).any() or (sv < 0).any(): self.launcher.show_error( 'SuperVoxels are not created for this ROI') return total_idx = np.array([], np.int32) with h5.File(self.DM.ds_path(self.DM.svtable), 'r') as t1, \ h5.File(self.DM.ds_path(self.DM.svindex), 'r') as t2: svtable = t1['data'] svindex = t2['data'] for v in sv: if v == self.DM.svtotal - 1: slc = slice(svtable[v], None) else: slc = slice(svtable[v], svtable[v + 1]) total_idx = np.append(total_idx, svindex[slc]) indexes = np.column_stack( np.unravel_index(total_idx, self.DM.data_shape)) if self.DM.data_shape != self.DM.region_shape(): log.debug('* Filtering indexes') mask = np.ones(indexes.shape[0], np.bool) for i, axis in enumerate(self.DM.active_roi): curr = indexes[:, i] mask[curr < axis.start] = False mask[curr >= axis.stop] = False indexes = indexes[mask] zmin, ymin, xmin = indexes.min(0) zmax, ymax, xmax = indexes.max(0) indexes[:, 0] -= zmin indexes[:, 1] -= ymin indexes[:, 2] -= xmin apply_roi = False elif self.DM.gtlevel == 2: mv = self.DM.load_slices(self.DM.mvlabels, slice_z, slice_y, slice_x) mv = mv[0, pos[:, 0], pos[:, 1]] mv = np.unique(mv) if np.isnan(mv).any() or (mv < 0).any(): self.launcher.show_error( 'MegaVoxels are not created for this ROI') return total_idx = np.array([], np.int32) with h5.File(self.DM.ds_path(self.DM.mvtable), 'r') as t1, \ h5.File(self.DM.ds_path(self.DM.mvindex), 'r') as t2: mvtable = t1['data'] mvindex = t2['data'] for v in mv: if v == self.DM.mvtotal - 1: slc = slice(mvtable[v], None) else: slc = slice(mvtable[v], mvtable[v + 1]) total_idx = np.append(total_idx, mvindex[slc]) indexes = np.column_stack( np.unravel_index(total_idx, self.DM.data_shape)) if self.DM.data_shape != self.DM.region_shape(): log.debug('* Filtering indexes') mask = np.ones(indexes.shape[0], np.bool) for i, axis in enumerate(self.DM.active_roi): curr = indexes[:, i] mask[curr < axis.start] = False mask[curr >= axis.stop] = False indexes = indexes[mask] zmin, ymin, xmin = indexes.min(0) zmax, ymax, xmax = indexes.max(0) indexes[:, 0] -= zmin indexes[:, 1] -= ymin indexes[:, 2] -= xmin apply_roi = False else: zmin = zmax = self.idx indexes = np.empty((pos.shape[0], 3), np.int32) indexes[:, 0] = 0 indexes[:, 1:] = pos apply_roi = True print("Time Get Index:", time.time() - t0) t0 = time.time() slice_z = slice(zmin, zmax + 1) slice_y = slice(ymin, ymax + 1) slice_x = slice(xmin, xmax + 1) if plevel is not None and plevel >= 0 and plabel >= 0: plevel = self.LBLM.dataset(plevel) pdata = self.DM.load_slices(plevel, slice_z, slice_y, slice_x, apply_roi=apply_roi) mask = (pdata == plabel) valid = mask[indexes[:, 0], indexes[:, 1], indexes[:, 2]] indexes = indexes[valid] hdata = self.DM.load_slices(level, slice_z, slice_y, slice_x, apply_roi=apply_roi) values = hdata[indexes[:, 0], indexes[:, 1], indexes[:, 2]] hdata[indexes[:, 0], indexes[:, 1], indexes[:, 2]] = label self.DM.write_slices(level, hdata, slice_z, slice_y, slice_x, apply_roi=apply_roi) self.DM.last_changes.append( (level, (slice_z, slice_y, slice_x), indexes, values, apply_roi)) print("Time Replace Data:", time.time() - t0) log.debug('* Done') self.update_volume(self.idx)
def blank(src): height, width, _ = src.shape if height != width: raise Exception("non-square image") image_size = width dst = src for i in range(np.random.randint(0, 30)): hole_type = np.random.randint(0, 5) if hole_type == 0: sx = np.random.randint(0, image_size) sy = np.random.randint(0, image_size) ex = np.random.randint(0, image_size) ey = np.random.randint(0, image_size) rr, cc = draw.line(sx, sy, ex, ey) dst[rr, cc] = 0 elif hole_type == 1: c_cent = np.random.randint(0, image_size) r_cent = np.random.randint(0, image_size) c_rad = np.random.randint(1, 15) r_rad = np.random.randint(1, 15) rr, cc = draw.ellipse(c_cent, r_cent, c_rad, r_rad, rotation=np.deg2rad(np.random.randint( 0, 360)), shape=(300, 300)) dst[rr, cc] = 0 elif hole_type == 2: r0 = np.random.randint(0, image_size) c0 = np.random.randint(0, image_size) r1 = np.random.randint(0, image_size) c1 = np.random.randint(0, image_size) r2 = np.random.randint(0, image_size) c2 = np.random.randint(0, image_size) weight = np.random.randint(1, 5) rr, cc = draw.bezier_curve(r0, c0, r1, c1, r2, c2, weight, (300, 300)) dst[rr, cc] = 0 elif hole_type > 2: pg_width = np.random.randint(1, 50) pg_height = np.random.randint(1, int(299 / pg_width)) pg_x = np.random.randint(0, image_size - pg_width) pg_y = np.random.randint(0, image_size - pg_height) x_pts = [] y_pts = [] for i in range(np.random.randint(3, 10)): x_pts.append(np.random.randint(pg_x, pg_x + pg_width)) y_pts.append(np.random.randint(pg_y, pg_y + pg_height)) rr, cc = draw.polygon(x_pts, y_pts, (300, 300)) dst[rr, cc] = 0 """image, _ = draw.random_shapes((width, width), max_shapes=30, max_size=300, multichannel=False, intensity_range=(255, 255), allow_overlap=True, num_trials=100, random_seed=None) for x in range(0, 300): for y in range(0, 300): if image[x][y] == 255: dst[x][y] = 0""" return dst
def draw(self, action): # do_nothing, q_line, q_curve, x0_line, y0_line, x1_line ,y1_line, # x0_c, y0_c, x1_c, y1_c, x2_c, y2_c, c if self.stroke_count >= self.max_stroke - 1: self.terminal = True # Parameter Validation and noises action_category = np.argmax(action[0:3]) if self.stroke_count == 0: axis = np.asarray(action[3:13], dtype=np.uint8) + np.int_( np.random.normal(0, 2, action[3:13].shape[0])) c_p = action[13] + np.random.normal(0, 1) else: axis = np.asarray(action[3:13], dtype=np.uint8) c_p = action[13] for i in range(axis.shape[0]): if axis[i] < 2: axis[i] = 2 elif axis[i] >= self.dim[0] - 2: axis[i] = self.dim[0] - 2 if action_category == 1: self.stroke_count += 1 # Draw line rr, cc = line(axis[0], axis[1], axis[2], axis[3]) self.canvas[rr, cc] = 1 if action_category == 2: self.stroke_count += 1 # Draw Curve try: rr, cc = bezier_curve(axis[4], axis[5], axis[6], axis[7], axis[8], axis[9], c_p) # TODO: Fix this curve error except MemoryError: while True: try: _x1, _y1 = move_point(axis[4], axis[5]) _x2, _y2 = move_point(axis[6], axis[7]) _x3, _y3 = move_point(axis[8], axis[9]) rr, cc = bezier_curve(_x1, _y1, _x2, _y2, _x3, _y3, c_p) break except MemoryError: continue try: self.canvas[rr, cc] = 1 except IndexError: rr = np.clip(rr, 0, config['STATE_DIM'][0] - 1) cc = np.clip(cc, 0, config['STATE_DIM'][1] - 1) self.canvas[rr, cc] = 1 score = self.classifier.get_score( self.canvas.reshape(-1, self.dim[0], self.dim[1], 1)) if score > 0.95: self.terminal = True if action_category == 0: self.terminal = True if self.terminal: if self.stroke_count == 0: reward = -1 else: reward = score - self.previous_score self.previous_score = score else: reward = 0 return self.canvas, reward, self.terminal