class Animator(object): def __init__(self, positions, diameter): self.count = positions.shape[0] plt.ion() fig = plt.figure(figsize=(10, 10)) ax = fig.gca() self.ax = ax diameters = np.ones(self.count) * diameter colors = [randcolor() for _ in range(self.count)] self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=ax.transData, edgecolor='face', facecolor=colors) ax.add_collection(self.circles) ax.axis([0, 1, 0, 1]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_axis_bgcolor('black') plt.draw() def update(self, positions): self.circles.set_offsets(positions) plt.draw()
class Animator(object): def __init__(self, positions, diameter): self.count = positions.shape[0] plt.ion() fig = plt.figure(figsize=(10, 10)) ax = fig.gca() self.ax = ax diameters = np.ones(self.count) * diameter colors = [randcolor() for _ in range(self.count)] self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=ax.transData, edgecolor='face', facecolor=colors) ax.add_collection(self.circles) ax.axis([0, 1, 0, 1]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_axis_bgcolor('black') plt.draw() plt.pause(0.1) #plt.show() #plt.savefig('foo.png') def update(self, positions): self.circles.set_offsets(positions) plt.draw() #plt.show() plt.pause(0.1)
class Animator(object): def __init__(self, positions, diameter): self.circ_count = positions.shape[0] plt.ion() fig = plt.figure(figsize=(10, 10)) ax = fig.gca() self.ax = ax diameters = np.ones(self.circ_count) * diameter circ_colors = [(0.0, 0.0, 1.0) for _ in range(self.circ_count)] #add circles self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=ax.transData, edgecolor='face', facecolor=circ_colors) ax.add_collection(self.circles) #add polygons self.poly_count = 3 verts = [[(0, 1), (1, 0), (2, 2)], [(6, 5), (3, 7), (7, 6)], [(0, -1), (-1, 0), (4, 5)]] poly_colors = [(0.0, 0.0, 1.0) for _ in range(self.poly_count)] self.polygons = PolyCollection(verts, facecolors=poly_colors) ax.add_collection(self.polygons) ax.axis([-20, 20, -20, 20]) ax.get_xaxis().set_visible(True) ax.get_yaxis().set_visible(True) #ax.set_axis_bgcolor('black') plt.draw() plt.pause(0.1) def update(self, positions): #update number of balls self.circles.set_offsets(positions) colors = [(1.0, 0.0, 0.0) for _ in range(self.circ_count)] self.circles.set_facecolors(colors) #redefine circles diameter = 2 diameters = np.ones(self.circ_count + 100) * diameter circ_colors = [(0.0, 0.0, 1.0) for _ in range(self.circ_count)] #add circles self.circles.remove() self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=self.ax.transData, edgecolor='face', facecolor=circ_colors) self.ax.add_collection(self.circles) #label text_labels = [None] * positions.shape[0] for i in range(positions.shape[0]): text_labels[i] = plt.text(positions[i, 0], positions[i, 1], str(i), color='white') #remove polygon #self.polygons.remove() poly_color = np.random.uniform(0.0, 0.89, (3, )) + 0.1 verts = [[(10, 1), (9, 0), (8, 2), (10, 2)], [(8, 8), (9, 9), (6, 7)]] self.polygons.set_verts(verts) plt.draw() plt.pause(0.1) #remove labels for i in range(positions.shape[0]): text_labels[i].remove()
class Animator(object): def __init__(self, template_w, template_h): #set up figure plt.ion() #fig = plt.figure(figsize = (10,10)) fig = plt.figure(figsize=(template_w, template_h)) #print template_w, template_h #raw_input() ax = fig.gca() #set axis dimension ax.axis([ -2 * template_w / 2.0, 2 * template_w / 2.0, -2 * template_h / 2.0, 2 * template_h / 2.0 ]) #ax.axis([-template_w/2.0, template_w/2.0,-template_h/2.0,template_h/2.0]) ax.get_xaxis().set_visible(True) ax.get_yaxis().set_visible(True) #draw template self.plot_template(template_w, template_h) #draw to screen plt.draw() plt.pause(0.1) #save axes to object self.ax = ax #save animator canvas area self.width = template_w self.height = template_h self.title = plt.text(0, 20, 'start title', color='k') #plot template def plot_template(self, l=20.0, w=20.0): x_pos = [-l / 2, l / 2, l / 2, -l / 2, -l / 2] y_pos = [-w / 2, -w / 2, w / 2, w / 2, -w / 2] plt.plot(x_pos, y_pos, 'k-', linewidth=3.0) plt.xlabel('x') plt.ylabel('y') def generate_color_array(self, collision): #define colors (red = collision, blue = no collision) colors = [None] * len(collision) for i in range(len(collision)): if collision[i] == True: colors[i] = (1.0, 0.0, 0.0) else: colors[i] = (0.0, 0.0, 1.0) return colors #add circular objects def add_circular_objects(self, diameters, positions, collision, pause_time=0.1): circ_colors = self.generate_color_array(collision) self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=self.ax.transData, edgecolor='k', facecolor=circ_colors) self.ax.add_collection(self.circles) #add text label text_labels = [None] * len(collision) for i in range(len(collision)): text_labels[i] = plt.text(positions[i, 0], positions[i, 1], str(i), color='k') self.circle_labels = text_labels #draw to screen #plt.draw() #plt.pause(pause_time) #remove text labels #for i in range(len(collision)): # text_labels[i].remove() #add polygon objects def add_polygon_objects(self, verts, collision, pause_time=0.1): poly_colors = self.generate_color_array(collision) self.polygons = PolyCollection(verts, facecolors=poly_colors) self.ax.add_collection(self.polygons) #add text label num_circles = self.circles.get_offsets().shape[0] #print 'number of circles =', num_circles text_labels = [None] * len(collision) for i in range(len(collision)): temp = np.array(verts[i]) x = np.mean(temp[:, 0]) y = np.mean(temp[:, 1]) text_labels[i] = plt.text(x, y, str(i + num_circles), color='k') self.polygon_labels = text_labels plt.draw() plt.pause(pause_time) #remove text labels #for i in range(len(collision)): # text_labels[i].remove() #remove circular objects: def remove_circles(self): self.circles.remove() for label in self.circle_labels: label.remove() #remove polygon objects: def remove_polygons(self): self.polygons.remove() for label in self.polygon_labels: label.remove() #update circular objects def update_circular_objects(self, positions, collision, pause_time=0.1): #set circle colors circ_colors = self.generate_color_array(collision) self.circles.set_facecolors(circ_colors) #set circle positions self.circles.set_offsets(positions) #remove labels for label in self.circle_labels: label.remove() #add labels text_labels = [None] * len(collision) for i in range(len(collision)): text_labels[i] = plt.text(positions[i, 0], positions[i, 1], str(i), color='k') self.circle_labels = text_labels plt.draw() plt.pause(pause_time) #update polygon objects def update_polygon_objects(self, positions, collision, pause_time=0.1): #set polygon colors poly_colors = self.generate_color_array(collision) self.polygons.set_facecolors(poly_colors) #set polygon positions #print 'new verts positions=' , positions self.polygons.set_verts(positions) #remove labels for label in self.polygon_labels: label.remove() #self.title.remove() #add new labels num_circles = self.circles.get_offsets().shape[0] #print self.polygons.get_offsets() #assert(0) text_labels = [None] * len(collision) for i in range(len(collision)): temp = np.array(positions[i]) x = np.mean(temp[:, 0]) y = np.mean(temp[:, 1]) text_labels[i] = plt.text(x, y, str(i + num_circles), color='k') self.polygon_labels = text_labels plt.draw() plt.pause(pause_time) #display the total area covered def show_title(self, area, pause_time=0.1): title = plt.text(-self.width / 4, self.height, 'total covered area = ' + str(area), color='k', fontsize=20) self.title.remove() self.title = title
class HoughDemo(ImageProcessDemo): TITLE = u"Hough Demo" DEFAULT_IMAGE = "stuff.jpg" SETTINGS = ["th2", "show_canny", "rho", "theta", "hough_th", "minlen", "maxgap", "dp", "mindist", "param2", "min_radius", "max_radius", "blur_sigma", "linewidth", "alpha", "check_line", "check_circle"] check_line = Bool(True) check_circle = Bool(True) #Gaussian blur parameters blur_sigma = Range(0.1, 5.0, 2.0) show_blur = Bool(False) # Canny parameters th2 = Range(0.0, 255.0, 200.0) show_canny = Bool(False) # HoughLine parameters rho = Range(1.0, 10.0, 1.0) theta = Range(0.1, 5.0, 1.0) hough_th = Range(1, 100, 40) minlen = Range(0, 100, 10) maxgap = Range(0, 20, 10) # HoughtCircle parameters dp = Range(1.0, 5.0, 1.9) mindist = Range(1.0, 100.0, 50.0) param2 = Range(5, 100, 50) min_radius = Range(5, 100, 20) max_radius = Range(10, 100, 70) # draw parameters linewidth = Range(1.0, 3.0, 1.0) alpha = Range(0.0, 1.0, 0.6) def control_panel(self): return VGroup( Group( Item("blur_sigma", label=u"标准方差"), Item("show_blur", label=u"显示结果"), label=u"高斯模糊参数" ), Group( Item("th2", label=u"阈值2"), Item("show_canny", label=u"显示结果"), label=u"边缘检测参数" ), Group( Item("rho", label=u"偏移分辨率(像素)"), Item("theta", label=u"角度分辨率(角度)"), Item("hough_th", label=u"阈值"), Item("minlen", label=u"最小长度"), Item("maxgap", label=u"最大空隙"), label=u"直线检测" ), Group( Item("dp", label=u"分辨率(像素)"), Item("mindist", label=u"圆心最小距离(像素)"), Item("param2", label=u"圆心检查阈值"), Item("min_radius", label=u"最小半径"), Item("max_radius", label=u"最大半径"), label=u"圆检测" ), Group( Item("linewidth", label=u"线宽"), Item("alpha", label=u"alpha"), HGroup( Item("check_line", label=u"直线"), Item("check_circle", label=u"圆"), ), label=u"绘图参数" ) ) def __init__(self, **kwargs): super(HoughDemo, self).__init__(**kwargs) self.connect_dirty("th2, show_canny, show_blur, rho, theta, hough_th," "min_radius, max_radius, blur_sigma," "minlen, maxgap, dp, mindist, param2, " "linewidth, alpha, check_line, check_circle") self.lines = LineCollection([], linewidths=2, alpha=0.6) self.axe.add_collection(self.lines) self.circles = EllipseCollection( [], [], [], units="xy", facecolors="none", edgecolors="red", linewidths=2, alpha=0.6, transOffset=self.axe.transData) self.axe.add_collection(self.circles) def _img_changed(self): self.img_gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) def draw(self): img_smooth = cv2.GaussianBlur(self.img_gray, (0, 0), self.blur_sigma, self.blur_sigma) img_edge = cv2.Canny(img_smooth, self.th2 * 0.5, self.th2) if self.show_blur and self.show_canny: show_img = cv2.cvtColor(np.maximum(img_smooth, img_edge), cv2.COLOR_BAYER_BG2BGR) elif self.show_blur: show_img = cv2.cvtColor(img_smooth, cv2.COLOR_BAYER_BG2BGR) elif self.show_canny: show_img = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2BGR) else: show_img = self.img if self.check_line: theta = self.theta / 180.0 * np.pi lines = cv2.HoughLinesP(img_edge, self.rho, theta, self.hough_th, minLineLength=self.minlen, maxLineGap=self.maxgap) if lines is not None: lines = lines[0] lines.shape = -1, 2, 2 self.lines.set_segments(lines) self.lines.set_visible(True) else: self.lines.set_visible(False) else: self.lines.set_visible(False) if self.check_circle: circles = cv2.HoughCircles(img_smooth, 3, self.dp, self.mindist, param1=self.th2, param2=self.param2, minRadius=self.min_radius, maxRadius=self.max_radius) if circles is not None: circles = circles[0] self.circles._heights = self.circles._widths = circles[:, 2] self.circles.set_offsets(circles[:, :2]) self.circles._angles = np.zeros(len(circles)) self.circles._transOffset = self.axe.transData self.circles.set_visible(True) else: self.circles.set_visible(False) else: self.circles.set_visible(False) self.lines.set_linewidths(self.linewidth) self.circles.set_linewidths(self.linewidth) self.lines.set_alpha(self.alpha) self.circles.set_alpha(self.alpha) self.draw_image(show_img)
plt.ylabel('position~$y$') plt.xlabel('position~$x$') radius = 1.0 ellipse_pos = EllipseCollection(widths=radius, heights=radius, angles=0, units='xy', facecolors='r', offsets=[], transOffset=ax.transData) ellipse_neg = EllipseCollection(widths=radius, heights=radius, angles=0, units='xy', facecolors='b', offsets=[], transOffset=ax.transData) ax.add_collection(ellipse_pos) ax.add_collection(ellipse_neg) idx_pos = q > 0.0 idx_neg = np.logical_not(idx_pos) ellipse_pos.set_offsets(np.column_stack((x[idx_pos], y[idx_pos]))) ellipse_neg.set_offsets(np.column_stack((x[idx_neg], y[idx_neg]))) #plt.scatter(x, y, s = area, c = ["r","b"]) plt.savefig('../figures/Kristall.pdf', bbox_inches='tight')
class Animator(object): def __init__(self, template_w, template_h): #set up figure plt.ion() fig = plt.figure(figsize = (10,10)) ax = fig.gca() ax.axis([-template_w/2.0, template_w/2.0,-template_h/2.0,template_h/2.0]) ax.get_xaxis().set_visible(True) ax.get_yaxis().set_visible(True) #draw template self.plot_template(template_w,template_h) #draw to screen plt.draw() plt.pause(0.1) #save axes to object self.ax = ax #plot template def plot_template(self,l = 20.0, w = 20.0): x_pos = [-l/2, l/2, l/2, -l/2, -l/2 ] y_pos = [-w/2, -w/2, w/2, w/2, -w/2] plt.plot(x_pos,y_pos,'k-',linewidth = 3.0) plt.xlabel('x') plt.ylabel('y') def generate_color_array(self,collision): #define colors (red = collision, blue = no collision) colors = [None] * len(collision) for i in range(len(collision)): if collision[i] == True: colors[i] = (1.0,0.0,0.0) else: colors[i] = (0.0,0.0,1.0) return colors #add circular objects def add_circular_objects(self,diameters,positions,collision): circ_colors = self.generate_color_array(collision) self.circles = EllipseCollection(widths=diameters, heights=diameters, angles=np.zeros_like(diameters), units='xy', offsets=positions, transOffset=self.ax.transData, edgecolor='k', facecolor=circ_colors) self.ax.add_collection(self.circles) #add text label text_labels = [None] * len(collision) for i in range(len(collision)): text_labels[i]= plt.text(positions[i,0],positions[i,1],str(i),color = 'w') self.circle_labels = text_labels #draw to screen plt.draw() plt.pause(0.1) #remove text labels #for i in range(len(collision)): # text_labels[i].remove() #add polygon objects def add_polygon_objects(self,verts,collision): poly_colors = self.generate_color_array(collision) self.polygons = PolyCollection(verts, facecolors=poly_colors) self.ax.add_collection(self.polygons) #add text label num_circles = self.circles.get_offsets().shape[1] text_labels = [None] * len(collision) for i in range(len(collision)): temp = np.array(verts[i]) x = np.mean(temp[:,0]) y = np.mean(temp[:,1]) text_labels[i]= plt.text(x,y,str(i+num_circles),color = 'w') self.polygon_labels = text_labels plt.draw() plt.pause(0.1) #remove text labels #for i in range(len(collision)): # text_labels[i].remove() #remove circular objects: def remove_circles(self): self.circles.remove() for label in self.circle_labels: label.remove() #remove polygon objects: def remove_polygons(self): self.polygons.remove() for label in self.polygon_labels: label.remove() #update circular objects def update_circular_objects(self,positions,collision): #set circle colors circ_colors = self.generate_color_array(collision) self.circles.set_facecolors(circ_colors) #set circle positions self.circles.set_offsets(positions) #remove labels for label in self.circle_labels: label.remove() #add labels text_labels = [None] * len(collision) for i in range(len(collision)): text_labels[i]= plt.text(positions[i,0],positions[i,1],str(i),color = 'w') self.circle_labels = text_labels plt.draw() plt.pause(0.1) #update polygon objects def update_polygon_objects(self,positions,collision): #set polygon colors poly_colors = self.generate_color_array(collision) self.polygons.set_facecolors(poly_colors) #set polygon positions #print 'new verts positions=' , positions self.polygons.set_verts(positions) #remove labels for label in self.polygon_labels: label.remove() #add new labels num_circles = self.circles.get_offsets().shape[1] #print self.polygons.get_offsets() #assert(0) text_labels = [None] * len(collision) for i in range(len(collision)): temp = np.array(positions[i]) x = np.mean(temp[:,0]) y = np.mean(temp[:,1]) text_labels[i]= plt.text(x,y,str(i+num_circles),color = 'w') self.polygon_labels = text_labels plt.draw() plt.pause(0.1)
class HoughDemo(ImageProcessDemo): TITLE = u"Hough Demo" DEFAULT_IMAGE = "stuff.jpg" SETTINGS = ["th2", "show_canny", "rho", "theta", "hough_th", "minlen", "maxgap", "dp", "mindist", "param2", "min_radius", "max_radius", "blur_sigma", "linewidth", "alpha", "check_line", "check_circle"] check_line = Bool(True) check_circle = Bool(True) #Gaussian blur parameters blur_sigma = Range(0.1, 5.0, 2.0) show_blur = Bool(False) # Canny parameters th2 = Range(0.0, 255.0, 200.0) show_canny = Bool(False) # HoughLine parameters rho = Range(1.0, 10.0, 1.0) theta = Range(0.1, 5.0, 1.0) hough_th = Range(1, 100, 40) minlen = Range(0, 100, 10) maxgap = Range(0, 20, 10) # HoughtCircle parameters dp = Range(1.0, 5.0, 1.9) mindist = Range(1.0, 100.0, 50.0) param2 = Range(5, 100, 50) min_radius = Range(5, 100, 20) max_radius = Range(10, 100, 70) # draw parameters linewidth = Range(1.0, 3.0, 1.0) alpha = Range(0.0, 1.0, 0.6) def control_panel(self): return VGroup( Group( Item("blur_sigma", label=u"标准方差"), Item("show_blur", label=u"显示结果"), label=u"高斯模糊参数" ), Group( Item("th2", label=u"阈值2"), Item("show_canny", label=u"显示结果"), label=u"边缘检测参数" ), Group( Item("rho", label=u"偏移分辨率(像素)"), Item("theta", label=u"角度分辨率(角度)"), Item("hough_th", label=u"阈值"), Item("minlen", label=u"最小长度"), Item("maxgap", label=u"最大空隙"), label=u"直线检测" ), Group( Item("dp", label=u"分辨率(像素)"), Item("mindist", label=u"圆心最小距离(像素)"), Item("param2", label=u"圆心检查阈值"), Item("min_radius", label=u"最小半径"), Item("max_radius", label=u"最大半径"), label=u"圆检测" ), Group( Item("linewidth", label=u"线宽"), Item("alpha", label=u"alpha"), HGroup( Item("check_line", label=u"直线"), Item("check_circle", label=u"圆"), ), label=u"绘图参数" ) ) def __init__(self, **kwargs): super(HoughDemo, self).__init__(**kwargs) self.connect_dirty("th2, show_canny, show_blur, rho, theta, hough_th," "min_radius, max_radius, blur_sigma," "minlen, maxgap, dp, mindist, param2, " "linewidth, alpha, check_line, check_circle") self.lines = LineCollection([], linewidths=2, alpha=0.6) self.axe.add_collection(self.lines) self.circles = EllipseCollection( [], [], [], units="xy", facecolors="none", edgecolors="red", linewidths=2, alpha=0.6, transOffset=self.axe.transData) self.axe.add_collection(self.circles) def _img_changed(self): self.img_gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) def draw(self): img_smooth = cv2.GaussianBlur(self.img_gray, (0, 0), self.blur_sigma, self.blur_sigma) img_edge = cv2.Canny(img_smooth, self.th2 * 0.5, self.th2) if self.show_blur and self.show_canny: show_img = cv2.cvtColor(np.maximum(img_smooth, img_edge), cv2.COLOR_BAYER_BG2BGR) elif self.show_blur: show_img = cv2.cvtColor(img_smooth, cv2.COLOR_BAYER_BG2BGR) elif self.show_canny: show_img = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2BGR) else: show_img = self.img if self.check_line: theta = self.theta / 180.0 * np.pi lines = cv2.HoughLinesP(img_edge, self.rho, theta, self.hough_th, minLineLength=self.minlen, maxLineGap=self.maxgap) if lines is not None: lines = lines[0] lines.shape = -1, 2, 2 self.lines.set_segments(lines) self.lines.set_visible(True) else: self.lines.set_visible(False) else: self.lines.set_visible(False) if self.check_circle: circles = cv2.HoughCircles(img_smooth, 3, self.dp, self.mindist, param1=self.th2, param2=self.param2, minRadius=self.min_radius, maxRadius=self.max_radius) if circles is not None: circles = circles[0] self.circles._heights = self.circles._widths = circles[:, 2] self.circles.set_offsets(circles[:, :2]) self.circles._angles = np.zeros(len(circles)) self.circles._transOffset = self.axe.transData self.circles.set_visible(True) else: self.circles.set_visible(False) else: self.circles.set_visible(False) self.lines.set_linewidths(self.linewidth) self.circles.set_linewidths(self.linewidth) self.lines.set_alpha(self.alpha) self.circles.set_alpha(self.alpha) self.draw_image(show_img)
x = samples[:,1] y = samples[:,2] fig, ax = plt.subplots() ax.set_xlim(-0.5 * 15, 0.5 * 15) ax.set_ylim(-0.5 * 15, 0.5 * 15) ax.set_aspect('equal') plt.ylabel('position~$y$') plt.xlabel('position~$x$') radius = 1.0 ellipse_pos = EllipseCollection(widths=radius, heights=radius, angles=0, units='xy', facecolors='r', offsets=[], transOffset=ax.transData) ellipse_neg = EllipseCollection(widths=radius, heights=radius, angles=0, units='xy', facecolors='b', offsets=[], transOffset=ax.transData) ax.add_collection(ellipse_pos) ax.add_collection(ellipse_neg) idx_pos = q > 0.0 idx_neg = np.logical_not(idx_pos) ellipse_pos.set_offsets(np.column_stack((x[idx_pos], y[idx_pos]))) ellipse_neg.set_offsets(np.column_stack((x[idx_neg], y[idx_neg]))) #plt.scatter(x, y, s = area, c = ["r","b"]) plt.savefig('../figures/Kristall.pdf', bbox_inches='tight')