Python draw circle

60 Python code examples are found related to " draw circle". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: visualizer.py    From detectron2 with Apache License 2.0 6 votes vote down vote up
def draw_circle(self, circle_coord, color, radius=3):
        """
        Args:
            circle_coord (list(int) or tuple(int)): contains the x and y coordinates
                of the center of the circle.
            color: color of the polygon. Refer to `matplotlib.colors` for a full list of
                formats that are accepted.
            radius (int): radius of the circle.

        Returns:
            output (VisImage): image object with box drawn.
        """
        x, y = circle_coord
        self.output.ax.add_patch(
            mpl.patches.Circle(circle_coord, radius=radius, fill=True, color=color)
        )
        return self.output 
Example 2
Source File: GXCHIMERA.py    From gxpy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def draw_circle_offset_markers(cls, mview, vv_xi, vv_yi, vv_xo, vv_yo, off_size):
        """
        Plots location marker and joining line for circle offset symbols
        
        :param mview:     View
        :param vv_xi:     Original (marker) X location
        :param vv_yi:     Original (marker) Y location
        :param vv_xo:     Offset (new) X location
        :param vv_yo:     Offset (new) Y location
        :param off_size:  Marker symbol radius
        :type  mview:     GXMVIEW
        :type  vv_xi:     GXVV
        :type  vv_yi:     GXVV
        :type  vv_xo:     GXVV
        :type  vv_yo:     GXVV
        :type  off_size:  float

        .. versionadded:: 5.0.7

        **License:** `Geosoft Extended End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-ext-end-user-lic>`_

        **Note:** Draws black filled circle (symbols.gfn #7) and a joining line.
        """
        gxapi_cy.WrapCHIMERA._draw_circle_offset_markers(GXContext._get_tls_geo(), mview, vv_xi, vv_yi, vv_xo, vv_yo, off_size) 
Example 3
Source File: mouse_drawing.py    From Mastering-OpenCV-4-with-Python with MIT License 6 votes vote down vote up
def draw_circle(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        print("event: EVENT_LBUTTONDBLCLK")
        cv2.circle(image, (x, y), 10, colors['magenta'], -1)

    if event == cv2.EVENT_MOUSEMOVE:
        print("event: EVENT_MOUSEMOVE")

    if event == cv2.EVENT_LBUTTONUP:
        print("event: EVENT_LBUTTONUP")

    if event == cv2.EVENT_LBUTTONDOWN:
        print("event: EVENT_LBUTTONDOWN")


# We create the canvas to draw: 600 x 600 pixels, 3 channels, uint8 (8-bit unsigned integers)
# We set the background to black using np.zeros(): 
Example 4
Source File: rendering.py    From RAVEN with GNU General Public License v3.0 6 votes vote down vote up
def draw_circle(img, center, radius, color, width):
    # if filled
    if color != 0:
        # fill the interior
        cv2.circle(img,
                   center,
                   radius,
                   color,
                   -1)
        # draw the edge
        cv2.circle(img,
                   center,
                   radius,
                   255,
                   width)
    # if not filled
    else:
        cv2.circle(img,
                   center,
                   radius,
                   255,
                   width) 
Example 5
Source File: opencv_draw.py    From Python-Code with MIT License 6 votes vote down vote up
def draw_circle(event,x,y,flags,param):
    global ix,iy,drawing,mode

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix,iy = x,y

    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing == True:
            if mode == True:
                cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
            else:
                cv2.circle(img,(x,y),5,(0,0,255),-1)

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        if mode == True:
            cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
        else:
            cv2.circle(img,(x,y),5,(0,0,255),-1) 
Example 6
Source File: viewer.py    From rl-medical with Apache License 2.0 6 votes vote down vote up
def draw_circle(self, radius=10, res=30, pos_x=0, pos_y=0,
                    color=(1.0,1.0,1.0,1.0),**attrs):

        points = []
        # window start indexing from bottom left
        x = self.img_height - pos_x
        y = pos_y

        for i in range(res):
            ang = 2*math.pi*i / res
            points.append((math.cos(ang)*radius + y ,
                           math.sin(ang)*radius + x))

        # draw filled polygon
        if   len(points) == 4 : glBegin(GL_QUADS)
        elif len(points)  > 4 : glBegin(GL_POLYGON)
        else: glBegin(GL_TRIANGLES)
        for p in points:
            # choose color
            glColor4f(color[0],color[1],color[2],color[3]);
            glVertex3f(p[0], p[1],0)  # draw each vertex
        glEnd()
        # reset color
        glColor4f(1.0, 1.0, 1.0, 1.0); 
Example 7
Source File: epaper2in13b.py    From micropython-waveshare-epaper with MIT License 6 votes vote down vote up
def draw_circle(self, frame_buffer, x, y, radius, colored):
        # Bresenham algorithm
        x_pos = -radius
        y_pos = 0
        err = 2 - 2 * radius
        if (x >= self.width or y >= self.height):
            return
        while True:
            self.set_pixel(frame_buffer, x - x_pos, y + y_pos, colored)
            self.set_pixel(frame_buffer, x + x_pos, y + y_pos, colored)
            self.set_pixel(frame_buffer, x + x_pos, y - y_pos, colored)
            self.set_pixel(frame_buffer, x - x_pos, y - y_pos, colored)
            e2 = err
            if (e2 <= y_pos):
                y_pos += 1
                err += y_pos * 2 + 1
                if(-x_pos == y_pos and e2 <= x_pos):
                    e2 = 0
            if (e2 > x_pos):
                x_pos += 1
                err += x_pos * 2 + 1
            if x_pos > 0:
                break 
Example 8
Source File: ssd1306_bouncing_ball.py    From Adafruit_CircuitPython_SSD1306 with MIT License 6 votes vote down vote up
def draw_circle(xpos0, ypos0, rad, col=1):
    x = rad - 1
    y = 0
    dx = 1
    dy = 1
    err = dx - (rad << 1)
    while x >= y:
        oled.pixel(xpos0 + x, ypos0 + y, col)
        oled.pixel(xpos0 + y, ypos0 + x, col)
        oled.pixel(xpos0 - y, ypos0 + x, col)
        oled.pixel(xpos0 - x, ypos0 + y, col)
        oled.pixel(xpos0 - x, ypos0 - y, col)
        oled.pixel(xpos0 - y, ypos0 - x, col)
        oled.pixel(xpos0 + y, ypos0 - x, col)
        oled.pixel(xpos0 + x, ypos0 - y, col)
        if err <= 0:
            y += 1
            err += dy
            dy += 2
        if err > 0:
            x -= 1
            dx += 2
            err += dx - (rad << 1)


# initial center of the circle 
Example 9
Source File: presets.py    From blender_autocomplete with GNU General Public License v3.0 6 votes vote down vote up
def draw_circle_2d(position: 'mathutils.Vector',
                   color,
                   radius: float,
                   segments: int = 32):
    '''Draw a circle. 

    :param position: Position where the circle will be drawn. 
    :type position: 'mathutils.Vector'
    :param color: Color of the circle. To use transparency GL_BLEND has to be enabled. 
    :param radius: Radius of the circle. 
    :type radius: float
    :param segments: How many segments will be used to draw the circle. Higher values give besser results but the drawing will take longer. 
    :type segments: int
    '''

    pass 
Example 10
Source File: partmodule.py    From pycalculix with Apache License 2.0 6 votes vote down vote up
def draw_circle(self, center_x, center_y, radius, num_arcs=4):
        """Draws a circle area and adds it to the part.

        Args:
            center_x (float): x-axis hole center
            center_y (float): y-axis hole center
            radius (float): hole radius
            num_arcs (int): number of arcs to use, must be >= 3

        Returns:
            loop (geometry.LineLoop): a LineLoop list of SignArc
        """
        center = geometry.Point(center_x, center_y)
        rvect = geometry.Point(0, radius)
        start = center + rvect
        self.goto(start.x, start.y)
        angles = np.linspace(360/num_arcs,360,num_arcs, endpoint=True)
        for ang in angles:
            point = geometry.Point(0, radius).rot_ccw_deg(ang)
            point = point + center
            self.draw_arc(point.x, point.y, center.x, center.y)
        loop = self.areas[-1].exlines
        self.__update()
        return loop 
Example 11
Source File: uArmRobot.py    From uArmProPython with GNU General Public License v3.0 6 votes vote down vote up
def drawCircle(self, centerX, centerY, Radius, Resolution, Speed, DrawingHeight, StartFinishedHeight):
        if (Resolution < 4):
            #ignore drwaing circle, to low resoution
            if (self.debug): print ("Ignoring drwaing circle, to low resolution requested")
            return
        if (self.debug): print ("Drwaing circle of {} radius in {} steps".format(Radius,Resolution))
        offsetx = centerX
        offsety = centerY 
        c = self.PointsInCircum(Radius,Resolution)
        bx,by = c[0]
        self.goto(offsetx+bx,offsety+by,StartFinishedHeight,Speed)

        for p in range(0,Resolution):
            x,y = c[p]
            self.goto(offsetx+x,offsety+y,DrawingHeight,Speed)

        self.goto(offsetx+bx,offsety+by,DrawingHeight,Speed)
        time.sleep(0.5)
        self.goto(offsetx+bx,offsety+by,StartFinishedHeight,Speed) 
Example 12
Source File: main.py    From python-examples with MIT License 6 votes vote down vote up
def draw_pattern_circle(x, y, r, count, radius, color='red'):
    rotation = 360 / count

    turtle.goto(x, y)

    for _ in range(count):
        # move from center to circle
        #turtle.pu()
        turtle.color('black')
        turtle.forward(radius)
        turtle.right(90)

        draw_circle(r, color)

        # move from circle to center
        #turtle.pu()
        turtle.color('black')
        turtle.left(90)
        turtle.backward(radius)

        # rotate in circle
        turtle.right(rotation) 
Example 13
Source File: geometry_viewer.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def draw_circle(self, center, normal, radius,
                    color='red', opacity=0.8):
        """ Draw a 2D circle into the scene

        Args:
            center (Vector[length, len=3]): center of the circle
            normal (Vector[len=3]): normal vector
            radius (Scalar[length]): radius of the circle
            color (str or int): color name or RGB hexadecimal
            opacity (float): sphere opacity

        Returns:
            dict: cylinder spec object
        """
        return self._draw3dmol_cylinder(color, center,
                                        np.array(center) + np.array(normal) * 0.01,
                                        True, True,
                                        opacity,
                                        radius) 
Example 14
Source File: skeleton_ui_draw.py    From object_alignment with GNU General Public License v3.0 6 votes vote down vote up
def draw_circle(self, world_loc, radius, inner_ratio, color_outside, color_inside):
        bgl.glDepthRange(0, 0.9999)     # squeeze depth just a bit
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glDepthMask(bgl.GL_FALSE)   # do not overwrite depth
        bgl.glEnable(bgl.GL_DEPTH_TEST)
        bgl.glDepthFunc(bgl.GL_LEQUAL)  # draw in front of geometry

        circleShader.enable()
        self.drawing.point_size(2.0 * radius)
        circleShader['uMVPMatrix'] = self.drawing.get_view_matrix_buffer()
        circleShader['uInOut']     = inner_ratio

        bgl.glBegin(bgl.GL_POINTS)
        circleShader['vOutColor'] = color_outside
        circleShader['vInColor']  = color_inside
        bgl.glVertex3f(*world_loc)
        bgl.glEnd()

        circleShader.disable()

        bgl.glDepthFunc(bgl.GL_LEQUAL)
        bgl.glDepthRange(0.0, 1.0)
        bgl.glDepthMask(bgl.GL_TRUE) 
Example 15
Source File: draw_shapes.py    From python-utils with MIT License 6 votes vote down vote up
def draw_circle(canvas, xy, r=1, stroke=None, fill=None, thickness=1, antialias=False):
    x,y = tuple(map(int, xy))
    line_type = cv2.LINE_AA if antialias else cv2.LINE_8
    if fill is not None:
        cv2.circle(canvas, (x,y), r, fill, -1, line_type)
    if stroke is not None:
        cv2.circle(canvas, (x,y), r, stroke, thickness, line_type)

# @njit
# def draw_circle(canvas, xy, r, fill):
#     x,y = xy
#     r2 = r * r
#     for i in range(canvas.shape[0]):
#         cy = i - y
#         cy2 = cy * cy
#         for j in range(canvas.shape[1]):
#             cx = j - x
#             ls = cx * cx + cy2
#             if ls < r2:
#                 canvas[i,j] = fill 
Example 16
Source File: functional.py    From pyray with MIT License 6 votes vote down vote up
def draw_functional_xygrid_in_circle(draw, r, shift=np.array([1000.0, 1000.0, 0.0]),
        scale=200.0, rgba=(0,255,0,120), fn=None, extent=10,
        saperatingPlane=np.array([-1,-1,4]), rgba2=None,radius=10):
    '''
    args:
        saperatingPlane: Take the dot product of this plane with [x,y,1]. If <0, draw lighter planes.
        rgba2: The color of the lighter portion of the plane.
    '''
    for i in range(-extent, extent, 1):
        for j in range(-extent, extent, 1):
            if i**2+j**2 < radius**2:
                poly = gridSquarePolygon(i, j, r, shift, scale, fn)
                if np.dot(np.array([i, j, 1]), saperatingPlane) > 0 or rgba2 is None:
                    draw.polygon(poly, rgba)
                else:
                    draw.polygon(poly, rgba2) 
Example 17
Source File: epd1in54b.py    From micropython-waveshare-epd with MIT License 6 votes vote down vote up
def draw_filled_circle(self, frame_buffer, x, y, radius, colored):
        # Bresenham algorithm
        x_pos = -radius
        y_pos = 0
        err = 2 - 2 * radius
        if (x >= self.width or y >= self.height):
            return
        while True:
            self.set_pixel(frame_buffer, x - x_pos, y + y_pos, colored)
            self.set_pixel(frame_buffer, x + x_pos, y + y_pos, colored)
            self.set_pixel(frame_buffer, x + x_pos, y - y_pos, colored)
            self.set_pixel(frame_buffer, x - x_pos, y - y_pos, colored)
            self.draw_horizontal_line(frame_buffer, x + x_pos, y + y_pos, 2 * (-x_pos) + 1, colored)
            self.draw_horizontal_line(frame_buffer, x + x_pos, y - y_pos, 2 * (-x_pos) + 1, colored)
            e2 = err
            if (e2 <= y_pos):
                y_pos += 1
                err += y_pos * 2 + 1
                if(-x_pos == y_pos and e2 <= x_pos):
                    e2 = 0
            if (e2 > x_pos):
                x_pos  += 1
                err += x_pos * 2 + 1
            if x_pos > 0:
                break 
Example 18
Source File: render_knob_scale.py    From knob-scale-generator with GNU General Public License v3.0 6 votes vote down vote up
def draw_circle_mark(self, x_offset, y_offset, radius, mark_angle, mark_length, parent):

        cx = x_offset + radius*cos(mark_angle)
        cy = y_offset + radius*sin(mark_angle)
        r = mark_length / 2.0

        style = {
                'stroke': '#000000',
                'stroke-width':'0',
                'fill': '#000000'
                }

        circ_attribs = {
                'style':str(inkex.Style(style)),
                'cx':str(cx),
                'cy':str(cy),
                'r':str(r)
                }
        circle = etree.SubElement(parent, inkex.addNS('circle','svg'), circ_attribs ) 
Example 19
Source File: mask_analysis.py    From deepgaze with MIT License 5 votes vote down vote up
def drawMaxAreaCircle(self, frame, mask, color=[0,255,0], thickness=3):
        """it draws the circle with largest area.
 
        @param frame the image to use as canvas
        @param mask the binary image to use in the function
        @param color the color of the circle
        @param thickness of the circle
        """
        x, y, r = self.returnMaxAreaCircle(mask)
        cv2.circle(frame, (x,y), r, color, thickness) 
Example 20
Source File: rendering.py    From rivuletpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_circle(self, radius=10, res=30, filled=True, **attrs):
        geom = make_circle(radius=radius, res=res, filled=filled)
        _add_attrs(geom, attrs)
        self.add_onetime(geom)
        return geom 
Example 21
Source File: ex_particle_filter_mouse_tracking.py    From deepgaze with MIT License 5 votes vote down vote up
def draw_circle(event,x,y,flags,param):
    #if event == cv2.EVENT_MOUSEMOVE:
    if event == cv2.EVENT_LBUTTONDOWN:

        #Predict the position of the pointer
        my_particle.predict(x_velocity=0, y_velocity=0, std=std)

        #Estimate the next position using the internal model
        x_estimated, y_estimated, _, _ = my_particle.estimate() 
 
        #Update the position of the particles based on the measurement.
        #Adding some noise to the measurement.
        noise_coefficient = np.random.uniform(low=0.0, high=10.0)
        x_measured = x + np.random.randn() * noise_coefficient
        y_measured = y + np.random.randn() * noise_coefficient
        my_particle.update(x_measured, y_measured)

        #Drawing the circles for the mouse position the
        #estimation and the particles.
        for i in range(0, tot_particles):
            x_particle, y_particle = my_particle.returnParticlesCoordinates(i)
            cv2.circle(img,(x_particle, y_particle),2,(0,0,255),-1) #RED: Particles
        cv2.circle(img,(x, y),2,(0,255,0),-1) #GREEN: Mouse position
        cv2.circle(img,(x_estimated, y_estimated),2,(255,0,0),-1) #BLUE: Filter estimation

        #Print general information
        print("Total Particles: " + str(tot_particles))
        print("Effective N: " + str(my_particle.returnParticlesContribution()))
        print("Measurement Noise: " + str(noise_coefficient) + "/10")
        print("x=" + str(x) + "; y=" + str(y) + " | " + 
              "x_measured=" + str(int(x_measured)) + "; y_measured=" + str(int(y_measured))  + " | " +
              "x_estimated=" + str(int(x_estimated)) + "; y_estimated=" + str(int(y_estimated)))
        #print(my_particle.weights) #uncomment to print the weights
        #print(my_particle.particles) #uncomment to print the particle position
        print("")

        #if(my_particle.returnParticlesContribution() < 8):
        my_particle.resample() 
Example 22
Source File: tft.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def drawCircle(self, x, y, radius, color = None):

        colorvect = self.colorvect if color is None else bytearray(color)

        f = 1 - radius
        ddF_x = 1
        ddF_y = -2 * radius
        x1 = 0
        y1 = radius

        self.drawPixel(x, y + radius, colorvect)
        self.drawPixel(x, y - radius, colorvect)
        self.drawPixel(x + radius, y, colorvect)
        self.drawPixel(x - radius, y, colorvect)

        while x1 < y1:
            if f >= 0:
	            y1 -= 1
	            ddF_y += 2
	            f += ddF_y
            x1 += 1
            ddF_x += 2
            f += ddF_x
            self.drawPixel(x + x1, y + y1, colorvect)
            self.drawPixel(x - x1, y + y1, colorvect)
            self.drawPixel(x + x1, y - y1, colorvect)
            self.drawPixel(x - x1, y - y1, colorvect)
            self.drawPixel(x + y1, y + x1, colorvect)
            self.drawPixel(x - y1, y + x1, colorvect)
            self.drawPixel(x + y1, y - x1, colorvect)
            self.drawPixel(x - y1, y - x1, colorvect)
#
# fill a circle at x, y with radius
# Straight port from the UTFT Library at Rinky-Dink Electronics
# Instead of calculating x = sqrt(r*r - y*y), it searches the x
# for r*r = x*x + x*x
# 
Example 23
Source File: mi_widget_select.py    From mifthtools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_circle_select(m_coords, radius = 16, p_col = (0.7,0.8,1.0,0.6), enabled = False, sub = False):
    if(enabled):
        f_col = p_col
        if sub:
            f_col = (1.0, 0.5, 0.4, 0.6)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBegin(bgl.GL_POLYGON)
        bgl.glColor4f(f_col[0], f_col[1], f_col[2], f_col[3]/3)

        point_x = m_coords[0]
        point_y = m_coords[1]

        radius = int(radius)

        for x in range(0, radius*2):
            bgl.glVertex2f(point_x + radius * math.cos(x * (360/(radius*2)) / 180 * 3.14159), point_y + radius * math.sin(x * (360/(radius*2)) / 180 * 3.14159))
        bgl.glEnd()

        bgl.glBegin(bgl.GL_LINES)
        bgl.glColor4f(f_col[0], f_col[1], f_col[2], f_col[3])
        for x in range(0, radius*2):
            bgl.glVertex2f(point_x + radius * math.cos(x * (360 / (radius * 2)) / 180 * 3.14159),
                           point_y + radius * math.sin(x * (360 / (radius * 2)) / 180 * 3.14159))

        bgl.glEnd()
        # restore opengl defaults
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0) 
Example 24
Source File: renderPDF.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def drawCircle(self, circle):
            self._canvas.circle(
                    circle.cx, circle.cy, circle.r,
                    fill=self._fill,
                    stroke=self._stroke
                    ) 
Example 25
Source File: ensemble_voting.py    From MTSAnomalyDetection with Apache License 2.0 5 votes vote down vote up
def draw_circle(ax, xy, radius):  # circle in the canvas coordinate
    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea
    from matplotlib.patches import Circle
    ada = AnchoredDrawingArea(20, 20, 0, 0,
                              loc=1, pad=0., frameon=False)
    p = Circle(xy, radius)
    ada.da.add_artist(p)
    ax.add_artist(ada) 
Example 26
Source File: mask_frame.py    From dials with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def DrawCircle(self, xc, yc, xedge, yedge):
        if self._mode_circle_layer:
            self._pyslip.DeleteLayer(self._mode_circle_layer)
            self._mode_circle_layer = None

        xc, yc = self._pyslip.ConvertView2Geo((xc, yc))
        xedge, yedge = self._pyslip.ConvertView2Geo((xedge, yedge))

        from scitbx import matrix

        center = matrix.col((xc, yc))
        edge = matrix.col((xedge, yedge))
        r = (center - edge).length()
        if r == 0:
            return

        e1 = matrix.col((1, 0))
        e2 = matrix.col((0, 1))
        circle_data = (
            center + r * (e1 + e2),
            center + r * (e1 - e2),
            center + r * (-e1 - e2),
            center + r * (-e1 + e2),
            center + r * (e1 + e2),
        )

        self._mode_circle_layer = self._pyslip.AddEllipseLayer(
            circle_data,
            map_rel=True,
            color="#00ffff",
            radius=5,
            visible=True,
            # show_levels=[3,4],
            name="<mode_circle_layer>",
        ) 
Example 27
Source File: create_dataset.py    From keras-autoencoder with GNU General Public License v3.0 5 votes vote down vote up
def draw_circle(img, x, y, radius):
	frame = img.copy()
	if radius > 10:
		# draw the circle and centroid on the frame,
		# then update the list of tracked points
		cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)

	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF
	if key == ord("q"):
		sys.exit(0) 
Example 28
Source File: utils.py    From multilabel-image-classification-tensorflow with MIT License 5 votes vote down vote up
def draw_circle(rgb, u, v, col, r):
  """Draws a simple anti-aliasing circle in-place.

  Args:
    rgb: Input image to be modified.
    u: Horizontal coordinate.
    v: Vertical coordinate.
    col: Color.
    r: Radius.
  """

  ir = int(math.ceil(r))
  for i in range(-ir-1, ir+2):
    for j in range(-ir-1, ir+2):
      nu = int(round(u + i))
      nv = int(round(v + j))
      if nu < 0 or nu >= rgb.shape[1] or nv < 0 or nv >= rgb.shape[0]:
        continue

      du = abs(nu - u)
      dv = abs(nv - v)

      # need sqrt to keep scale
      t = math.sqrt(du * du + dv * dv) - math.sqrt(r * r)
      if t < 0:
        rgb[nv, nu, :] = col
      else:
        t = 1 - t
        if t > 0:
          # t = t ** 0.3
          rgb[nv, nu, :] = col * t + rgb[nv, nu, :] * (1-t) 
Example 29
Source File: drawcircle.py    From Python-Project with Apache License 2.0 5 votes vote down vote up
def drawCircleTurle(x,y,r):
    # move to the start of circle
    turtle.up()
    turtle.setpos(x+r,y)
    turtle.down()


     # draw the circle
    for i in range(0,365,5):
        a=math.radians(i)
        turtle.setpos(x+r*math.cos(a),y+r*math.sin(a)) 
Example 30
Source File: joystick.py    From interbotix_ros_arms with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def drawCircle(self, pnt, color, fill=True):
        p = QPainter(self)
        p.setPen(color)
        if (fill):
            p.setBrush(QBrush(color))
        p.drawEllipse(pnt,3,3)

    ### @brief Draws a crosshair centered at the specified point
    ### @param pnt - QPoint specifying the point at which to draw the crosshair 
Example 31
Source File: render_knob_scale.py    From knob-scale-generator with GNU General Public License v3.0 5 votes vote down vote up
def draw_centering_circle(self, radius, parent):

        style = {   'stroke'        : '#000000',
                    'stroke-width'  : '1',
                    'fill'          : 'none'            }
        ell_attribs = {'style':str(inkex.Style(style)),
            inkex.addNS('cx','sodipodi')        :str(self.x_offset),
            inkex.addNS('cy','sodipodi')        :str(self.y_offset),
            inkex.addNS('rx','sodipodi')        :str(radius),
            inkex.addNS('ry','sodipodi')        :str(radius),
            inkex.addNS('type','sodipodi')      :'arc'
            }
        ell = etree.SubElement(parent, inkex.addNS('path','svg'), ell_attribs ) 
Example 32
Source File: img.py    From video-to-pose3D with MIT License 5 votes vote down vote up
def drawSmallCircle(img, pt, sigma):
    img = to_numpy(img)
    tmpSize = 3 * sigma
    # Check that any part of the gaussian is in-bounds
    ul = [int(pt[0] - tmpSize), int(pt[1] - tmpSize)]
    br = [int(pt[0] + tmpSize + 1), int(pt[1] + tmpSize + 1)]

    if (ul[0] >= img.shape[1] or ul[1] >= img.shape[0] or
            br[0] < 0 or br[1] < 0):
        # If not, just return the image as is
        return to_torch(img)

    # Generate gaussian
    size = 2 * tmpSize + 1
    x = np.arange(0, size, 1, float)
    y = x[:, np.newaxis]
    x0 = y0 = size // 2
    sigma = size / 4.0
    # The gaussian is not normalized, we want the center value to equal 1
    g = np.exp(- ((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))
    g[g > 0.5] = 1
    # Usable gaussian range
    g_x = max(0, -ul[0]), min(br[0], img.shape[1]) - ul[0]
    g_y = max(0, -ul[1]), min(br[1], img.shape[0]) - ul[1]
    # Image range
    img_x = max(0, ul[0]), min(br[0], img.shape[1])
    img_y = max(0, ul[1]), min(br[1], img.shape[0])

    img[img_y[0]:img_y[1], img_x[0]:img_x[1]] = g[g_y[0]:g_y[1], g_x[0]:g_x[1]]
    return to_torch(img) 
Example 33
Source File: img.py    From video-to-pose3D with MIT License 5 votes vote down vote up
def drawCircle(img, pt, sigma):
    img = to_numpy(img)
    tmpSize = 3 * sigma
    # Check that any part of the gaussian is in-bounds
    ul = [int(pt[0] - tmpSize), int(pt[1] - tmpSize)]
    br = [int(pt[0] + tmpSize + 1), int(pt[1] + tmpSize + 1)]

    if (ul[0] >= img.shape[1] or ul[1] >= img.shape[0] or
            br[0] < 0 or br[1] < 0):
        # If not, just return the image as is
        return to_torch(img)

    # Generate gaussian
    size = 2 * tmpSize + 1
    x = np.arange(0, size, 1, float)
    y = x[:, np.newaxis]
    x0 = y0 = size // 2
    sigma = size / 4.0
    # The gaussian is not normalized, we want the center value to equal 1
    g = np.exp(- ((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))
    g[g > 0] = 1
    # Usable gaussian range
    g_x = max(0, -ul[0]), min(br[0], img.shape[1]) - ul[0]
    g_y = max(0, -ul[1]), min(br[1], img.shape[0]) - ul[1]
    # Image range
    img_x = max(0, ul[0]), min(br[0], img.shape[1])
    img_y = max(0, ul[1]), min(br[1], img.shape[0])

    img[img_y[0]:img_y[1], img_x[0]:img_x[1]] = g[g_y[0]:g_y[1], g_x[0]:g_x[1]]
    return to_torch(img) 
Example 34
Source File: img.py    From video-to-pose3D with MIT License 5 votes vote down vote up
def drawBigCircle(img, pt, sigma):
    img = to_numpy(img)
    tmpSize = 3 * sigma
    # Check that any part of the gaussian is in-bounds
    ul = [int(pt[0] - tmpSize), int(pt[1] - tmpSize)]
    br = [int(pt[0] + tmpSize + 1), int(pt[1] + tmpSize + 1)]

    if (ul[0] >= img.shape[1] or ul[1] >= img.shape[0] or
            br[0] < 0 or br[1] < 0):
        # If not, just return the image as is
        return to_torch(img)

    # Generate gaussian
    size = 2 * tmpSize + 1
    x = np.arange(0, size, 1, float)
    y = x[:, np.newaxis]
    x0 = y0 = size // 2
    sigma = size / 4.0
    # The gaussian is not normalized, we want the center value to equal 1
    g = np.exp(- ((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))
    g[g > 0.4] = 1
    # Usable gaussian range
    g_x = max(0, -ul[0]), min(br[0], img.shape[1]) - ul[0]
    g_y = max(0, -ul[1]), min(br[1], img.shape[0]) - ul[1]
    # Image range
    img_x = max(0, ul[0]), min(br[0], img.shape[1])
    img_y = max(0, ul[1]), min(br[1], img.shape[0])

    img[img_y[0]:img_y[1], img_x[0]:img_x[1]] = g[g_y[0]:g_y[1], g_x[0]:g_x[1]]
    return to_torch(img) 
Example 35
Source File: img.py    From px2graph with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_circle(img, pt, color, radius):
    # Draw a circle
    # Mostly a convenient wrapper for skimage.draw.circle
    rr, cc = skimage.draw.circle(pt[1], pt[0], radius, img.shape)
    img[rr, cc] = color
    return img 
Example 36
Source File: primitive.py    From BlenderTools with GNU General Public License v2.0 5 votes vote down vote up
def draw_circle(radius, steps, mat, scs_globals):
    """
    Draw a horizontal circle of given radius and using given number of steps.
    :param radius:
    :param steps:
    :param mat:
    :param scs_globals:
    :return:
    """
    import math

    color = (
        scs_globals.locator_prefab_wire_color.r,
        scs_globals.locator_prefab_wire_color.g,
        scs_globals.locator_prefab_wire_color.b,
        1.0
    )

    first_a = 0
    append_line_vertex((mat @ Vector((0 + radius * math.cos(first_a), 0 + radius * math.sin(first_a), 0.0))), color)

    for step in range(steps - 1):
        a = (math.pi * 2 / steps) * (step + 1)
        append_line_vertex((mat @ Vector((0 + radius * math.cos(a), 0 + radius * math.sin(a), 0.0))), color, is_strip=True)

    append_line_vertex((mat @ Vector((0 + radius * math.cos(first_a), 0 + radius * math.sin(first_a), 0.0))), color) 
Example 37
Source File: epaper2in13b.py    From micropython-waveshare-epaper with MIT License 5 votes vote down vote up
def draw_filled_circle(self, frame_buffer, x, y, radius, colored):
        # Bresenham algorithm
        x_pos = -radius
        y_pos = 0
        err = 2 - 2 * radius
        if (x >= self.width or y >= self.height):
            return
        while True:
            self.set_pixel(frame_buffer, x - x_pos, y + y_pos, colored)
            self.set_pixel(frame_buffer, x + x_pos, y + y_pos, colored)
            self.set_pixel(frame_buffer, x + x_pos, y - y_pos, colored)
            self.set_pixel(frame_buffer, x - x_pos, y - y_pos, colored)
            self.draw_horizontal_line(frame_buffer, x + x_pos, y + y_pos, 2 * (-x_pos) + 1, colored)
            self.draw_horizontal_line(frame_buffer, x + x_pos, y - y_pos, 2 * (-x_pos) + 1, colored)
            e2 = err
            if (e2 <= y_pos):
                y_pos += 1
                err += y_pos * 2 + 1
                if(-x_pos == y_pos and e2 <= x_pos):
                    e2 = 0
            if (e2 > x_pos):
                x_pos  += 1
                err += x_pos * 2 + 1
            if x_pos > 0:
                break

    # to wake call reset() or init() 
Example 38
Source File: util.py    From M3D-RPN with MIT License 5 votes vote down vote up
def draw_circle(im, pos, radius=5, thickness=1, color=(250, 100, 100), fill=True):

    if fill: thickness = -1

    cv2.circle(im, (int(pos[0]), int(pos[1])), radius, color=color, thickness=thickness) 
Example 39
Source File: visualisation.py    From DeepVOG with GNU General Public License v3.0 5 votes vote down vote up
def draw_circle(output_frame, frame_shape, centre, radius, color=[255, 0, 0]):
    """
    Draw a circle on an image or video frame. Drawing will be discretized.

    Parameters
    ----------
    output_frame : numpy.darray
        Video frame to draw the circle. The value of video frame should be of type int [0, 255]
    frame_shape : list or tuple or numpy.darray
        Shape of the frame. For example, (240, 320)
    centre : list or tuple or numpy.darray
        x,y coordinate of the circle centre
    radius : int or float
        Radius of the circle to draw.
    color : tuple or list or numpy.darray
        RBG colors, e.g. [255, 0, 0] (red color), values of type int [0, 255]

    Returns
    -------
    output frame : numpy.darray
        Frame withe the circle drawn.
    """

    R, G, B = color
    rr_p1, cc_p1 = circle_perimeter(int(np.round(centre[0])), int(np.round(centre[1])), radius)
    rr_p1[rr_p1 > int(frame_shape[1]) - 1] = frame_shape[1] - 1
    cc_p1[cc_p1 > int(frame_shape[0]) - 1] = frame_shape[0] - 1
    rr_p1[rr_p1 < 0] = 0
    cc_p1[cc_p1 < 0] = 0
    output_frame[cc_p1, rr_p1, 0] = R
    output_frame[cc_p1, rr_p1, 1] = G
    output_frame[cc_p1, rr_p1, 2] = B
    return output_frame 
Example 40
Source File: shift_parameter.py    From Mastering-OpenCV-4-with-Python with MIT License 5 votes vote down vote up
def draw_float_circle(img, center, radius, color, thickness=1, lineType=8, shift=4):
    """Wrapper function to draw float-coordinate circles"""

    factor = 2 ** shift
    center = (int(round(center[0] * factor)), int(round(center[1] * factor)))
    radius = int(round(radius * factor))
    cv2.circle(img, center, radius, color, thickness, lineType, shift)


# Dictionary containing some colors: 
Example 41
Source File: run_create_annotation.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_circle(pos_center, radius, img_shape):
    """ create empty image and draw a circle with specific radius

    :param [int, int] pos_center:
    :param int radius:
    :param [int, int] img_shape:
    :return ndarray:
    """
    im = np.zeros(img_shape)
    x, y = draw.circle(pos_center[0], pos_center[1], radius, shape=im.shape[:2])
    im[x, y] = True
    return im 
Example 42
Source File: renderPDF.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def drawCircle(self, circle):
            self._canvas.circle(
                    circle.cx, circle.cy, circle.r,
                    fill=self._fill,
                    stroke=self._stroke
                    ) 
Example 43
Source File: gl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def draw_circle(x, y, radius, subdivide, poly=False):
    r = 0.0
    dr = math.pi * 2 / subdivide
    if poly:
        subdivide += 1
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        bgl.glVertex2f(x, y)
    else:
        bgl.glBegin(bgl.GL_LINE_LOOP)
    for i in range(subdivide):
        bgl.glVertex2f(x + radius * math.cos(r), y + radius * math.sin(r))
        r += dr
    bgl.glEnd() 
Example 44
Source File: create_mask_im.py    From PConv_in_tf with Apache License 2.0 5 votes vote down vote up
def draw_circle(imraw,num_cir):
    centers = np.random.randint(0,512,[num_cir,2])
    Rs = np.random.randint(0,30,num_cir)
    thick = np.random.randint(10,30,num_cir)
    for i in range(num_cir):
        cv2.circle(imraw,tuple(centers[i]),Rs[i],0,thick[i])
    return imraw 
Example 45
Source File: vehicle.py    From SDC-P5 with MIT License 5 votes vote down vote up
def drawClosingCircle(
            self, sweepLane, projectionFX, roadProjection,
            color=[0, 0, 255], sweepedcolor=[128, 128, 255],
            sweepThick=5, fullsweepFrame=20):
        if self.lane == sweepLane:
            ccolor = sweepedcolor
        else:
            ccolor = color
        if not self.sweepDone:
            # calculate sweep radius
            radius = (fullsweepFrame -
                      (self.sweepDeltaFrame % fullsweepFrame)) * 10
            self.sweepDeltaFrame += 1

            # closingCircle sweep
            cv2.circle(
                projectionFX, (int(self.xcenter), int(self.ycenter)),
                radius, ccolor, 10)
            cv2.circle(
                roadProjection, (int(self.xcenter), int(self.ycenter)),
                radius, ccolor, 10)

            if self.sweepDeltaFrame == fullsweepFrame:
                self.sweepDone = True
        else:
            if self.mode < 2:
                self.mode = 2
            radius = self.deltaX*2
            cv2.circle(
                roadProjection, (int(self.xcenter), int(self.ycenter)),
                radius, ccolor, 10) 
Example 46
Source File: anchored_artists.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_circle(ax):
    """
    Draw a circle in axis coordinates
    """
    from matplotlib.patches import Circle
    ada = AnchoredDrawingArea(20, 20, 0, 0,
                              loc='upper right', pad=0., frameon=False)
    p = Circle((10, 10), 10)
    ada.da.add_artist(p)
    ax.add_artist(ada) 
Example 47
Source File: screen_highlight.py    From iris with Mozilla Public License 2.0 5 votes vote down vote up
def draw_circle(self, circle: HighlightCircle):
        return self.canvas.draw_circle(
            circle.center_x,
            circle.center_y,
            circle.radius,
            outline=circle.color,
            width=circle.thickness,
        ) 
Example 48
Source File: template.py    From inkscape_extension_template with MIT License 5 votes vote down vote up
def draw_SVG_circle(parent, r, cx, cy, name, style):
    " structre an SVG circle entity under parent "
    circ_attribs = {'style': simplestyle.formatStyle(style),
                    'cx': str(cx), 'cy': str(cy), 
                    'r': str(r),
                    inkex.addNS('label','inkscape'): name}
    circle = inkex.etree.SubElement(parent, inkex.addNS('circle','svg'), circ_attribs )



### Your main function subclasses the inkex.Effect class