Python draw triangle

31 Python code examples are found related to " draw triangle". 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: backend_bases.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def draw_gouraud_triangle(self, gc, points, colors, transform):
        """
        Draw a Gouraud-shaded triangle.

        Parameters
        ----------
        points : array_like, shape=(3, 2)
            Array of (x, y) points for the triangle.

        colors : array_like, shape=(3, 4)
            RGBA colors for each point of the triangle.

        transform : `matplotlib.transforms.Transform`
            An affine transform to apply to the points.

        """
        raise NotImplementedError 
Example 2
Source File: main-5.py    From python-examples with MIT License 6 votes vote down vote up
def drawTriangle(self, event, qp, args):
        '''rysowanie trojkata'''
        x1 = args['x']
        y1 = args['y']+args['height']
        x2 = args['x']+args['width']
        y2 = y1
        x3 = x1+(args['width']/2)
        y3 = args['y']

        if args['color']:
            qp.setPen(QtGui.QColor(args['color']))
            
        if args['fill']:
            qp.setBrush(QtGui.QColor(args['fill']))
        else:
            qp.setBrush(QtCore.Qt.NoBrush)
            
        qp.drawLine(x1, y1, x2, y2)
        qp.drawLine(x1, y1, x3, y3)
        qp.drawLine(x2, y2, x3, y3) 
Example 3
Source File: opengl_dim.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def draw_triangle(v1, v2, v3):
    # noinspection PyBroadException
    try:
        if v1 is not None and v2 is not None and v3 is not None:
            bgl.glBegin(bgl.GL_TRIANGLES)
            bgl.glVertex2f(*v1)
            bgl.glVertex2f(*v2)
            bgl.glVertex2f(*v3)
            bgl.glEnd()
    except:
        pass 
Example 4
Source File: direction.py    From FrameNet with MIT License 5 votes vote down vote up
def DrawTriangle(v1,v2,v3,t1,t2,t3,n1,n2,n3,tex, color_image, z_image, intrinsics):
	dirlib.DrawTriangle(
		c_void_p(v1.ctypes.data),c_void_p(v2.ctypes.data),c_void_p(v3.ctypes.data),\
		c_void_p(t1.ctypes.data),c_void_p(t2.ctypes.data),c_void_p(t3.ctypes.data),\
		c_void_p(n1.ctypes.data),c_void_p(n2.ctypes.data),c_void_p(n3.ctypes.data),\
		c_void_p(tex.ctypes.data),c_void_p(color_image.ctypes.data),c_void_p(z_image.ctypes.data),\
		c_void_p(intrinsics.ctypes.data),\
		c_int(tex.shape[1]), c_int(tex.shape[0]), c_int(color_image.shape[1]), c_int(color_image.shape[0])) 
Example 5
Source File: v2m.py    From video2midi with GNU General Public License v3.0 5 votes vote down vote up
def DrawTriangle(x,y, s,r=0):
  glBegin(GL_TRIANGLES);
  if ( r == 0 ):
   glVertex2f(x , y-s);
   glVertex2f(x + s, y-s);
   glVertex2f(x + s*0.5, y);
  else:
   glVertex2f(x , y);
   glVertex2f(x + s,y);
   glVertex2f(x + s*0.5, y-s);
  glEnd();
  pass 
Example 6
Source File: pygame_functions.py    From Pygame_Functions with GNU General Public License v2.0 5 votes vote down vote up
def drawTriangle(x1, y1, x2, y2, x3, y3, colour, linewidth=0):
    global bgSurface
    colour = parseColour(colour)
    thisrect = pygame.draw.polygon(screen, colour, [(x1, y1), (x2, y2), (x3, y3)], linewidth)
    if screenRefresh:
        pygame.display.update(thisrect) 
Example 7
Source File: rendering.py    From RAVEN with GNU General Public License v3.0 5 votes vote down vote up
def draw_triangle(img, pts, color, width):
    # if filled
    if color != 0:
        # fill the interior
        cv2.fillConvexPoly(img, pts, color)
        # draw the edge
        cv2.polylines(img, [pts], True, 255, width)
    # if not filled
    else:
        cv2.polylines(img, [pts], True, 255, width) 
Example 8
Source File: venn.py    From pyvenn with The Unlicense 5 votes vote down vote up
def draw_triangle(fig, ax, x1, y1, x2, y2, x3, y3, fillcolor):
    xy = [
        (x1, y1),
        (x2, y2),
        (x3, y3),
    ]
    polygon = patches.Polygon(
        xy=xy,
        closed=True,
        color=fillcolor)
    ax.add_patch(polygon) 
Example 9
Source File: backend_bases.py    From ImageFusion with MIT License 5 votes vote down vote up
def draw_gouraud_triangle(self, gc, points, colors, transform):
        """
        Draw a Gouraud-shaded triangle.

        *points* is a 3x2 array of (x, y) points for the triangle.

        *colors* is a 3x4 array of RGBA colors for each point of the
        triangle.

        *transform* is an affine transform to apply to the points.
        """
        raise NotImplementedError 
Example 10
Source File: canvas.py    From rasterizer.py with Apache License 2.0 5 votes vote down vote up
def draw_triangle(self, v1, v2, v3):
        """
        :type v1: Vertex
        :type v2: Vertex
        :type v3: Vertex
        """
        a, b, c = sorted([v1, v2, v3], key=lambda k: k.position.y)
        middle_factor = 0
        if c.position.y - a.position.y != 0:
            middle_factor = (b.position.y - a.position.y) / (c.position.y - a.position.y)
        middle = interpolate(a, c, middle_factor)

        start_y = int(a.position.y)
        end_y = int(b.position.y)
        for y in range(start_y, end_y + 1):
            factor = (y - start_y) / (end_y - start_y) if end_y != start_y else 0
            va = interpolate(a, b, factor)
            vb = interpolate(a, middle, factor)
            self.draw_scanline(va, vb, y)

        start_y = int(b.position.y)
        end_y = int(c.position.y)
        for y in range(start_y, end_y + 1):
            factor = (y - start_y) / (end_y - start_y) if end_y != start_y else 0
            va = interpolate(b, c, factor)
            vb = interpolate(middle, c, factor)
            self.draw_scanline(va, vb, y) 
Example 11
Source File: 6.04.py    From Tkinter-GUI-Application-Development-Blueprints-Second-Edition with MIT License 5 votes vote down vote up
def draw_triangle(self):
        dx = self.end_x - self.start_x
        dy = self.end_y - self.start_y
        z = complex(dx, dy)
        radius, angle0 = cmath.polar(z)
        edges = 3   # nb of edges in circle
        points = list()
        for edge in range(edges):
            angle = angle0 + edge * (2 * math.pi) / edges
            points.append(self.start_x + radius * math.cos(angle)) # x coordinate
            points.append(self.start_y + radius * math.sin(angle)) # y coordinate
        self.current_item = self.canvas.create_polygon(
            points, outline=self.outline, fill=self.fill,
            width=self.width) 
Example 12
Source File: gl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def draw_triangle_get_vectors(base, base_length, top_relative):
    # triangle_relative_to_vertsの書き直し
    # base左, base右, top
    v0 = Vector(base)
    v = (Vector([-top_relative[1], top_relative[0]])).normalized()
    v *= base_length / 2
    v1 = v0 + v
    v2 = v0 - v
    v3 = v0 + Vector(top_relative)
    return v1, v2, v3 
Example 13
Source File: matrix_drawing.py    From BiblioPixel with MIT License 5 votes vote down vote up
def draw_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False):
    """Draw triangle with points x0,y0 - x1,y1 - x2,y2"""
    draw_line(setter, x0, y0, x1, y1, color, aa)
    draw_line(setter, x1, y1, x2, y2, color, aa)
    draw_line(setter, x2, y2, x0, y0, color, aa) 
Example 14
Source File: gl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def draw_triangle_relative(top, base_relative, base_length,
                           mode=bgl.GL_TRIANGLES):
    v1, v2, v3 = triangle_relative_to_verts(top, base_relative, base_length)
    bgl.glBegin(mode)
    bgl.glVertex2f(*v1)
    bgl.glVertex2f(*v2)
    bgl.glVertex2f(*v3)
    bgl.glEnd() 
Example 15
Source File: triangles_two.py    From generative-art with MIT License 5 votes vote down vote up
def draw_triangle(ctx, p1, p2, p3, color, outline=False):
    ctx.move_to(*p1)
    ctx.line_to(*p2)
    ctx.line_to(*p3)
    ctx.set_source_rgb(*color)
    ctx.fill() 
Example 16
Source File: mixed_len_generator.py    From CSGNet with MIT License 5 votes vote down vote up
def draw_triangle(self, center: List, length: int):
        """
        Draw a triangle
        :param center: center of the triangle
        :param radius: radius of the triangle
        :return:
        """
        arr = np.zeros(self.canvas_shape, dtype=bool)
        length = 1.732 * length
        rows = [
            int(center[1] + length / (2 * 1.732)),
            int(center[1] + length / (2 * 1.732)),
            int(center[1] - length / 1.732)
        ]
        cols = [
            int(center[0] - length / 2.0),
            int(center[0] + length / 2.0), center[0]
        ]

        rr_inner, cc_inner = draw.polygon(rows, cols, shape=self.canvas_shape)
        rr_boundary, cc_boundary = draw.polygon_perimeter(
            rows, cols, shape=self.canvas_shape)

        ROWS = np.concatenate((rr_inner, rr_boundary))
        COLS = np.concatenate((cc_inner, cc_boundary))
        arr[ROWS, COLS] = True
        return arr 
Example 17
Source File: draw.py    From blender-power-sequencer with GNU General Public License v3.0 5 votes vote down vote up
def draw_triangle(shader, point_1, point_2, point_3, color=(1.0, 1.0, 1.0, 1.0)):
    vertices = (point_1, point_2, point_3)
    indices = ((0, 1, 2),)
    batch = batch_for_shader(shader, "TRIS", {"pos": vertices}, indices=indices)
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader) 
Example 18
Source File: draw.py    From blender-power-sequencer with GNU General Public License v3.0 5 votes vote down vote up
def draw_triangle_equilateral(shader, center, radius, rotation=0.0, color=(1.0, 1.0, 1.0, 1.0)):
    points = []
    for i in range(3):
        angle = i * math.pi * 2 / 3 + rotation
        offset = Vector((radius * math.cos(angle), radius * math.sin(angle)))
        points.append(center + offset)
    draw_triangle(shader, *points, color) 
Example 19
Source File: draw.py    From snowy with MIT License 5 votes vote down vote up
def draw_triangle(target: np.ndarray, source: np.ndarray,
                  vertices: np.ndarray):
    """Draw a textured triangle into the target image.
    
    The vertices are specified with a 3x5 array where each row is XYWUV.
    The UV coordinates address the source image in [0,+1] with +V going
    downward. The XY coordinates are in the range [-1,+1] and their
    domain is the entire target image with +Y going upward. The W
    coordinate is to allow for perspective-correct interpolation. If you
    don't know what that means, then set W to 1.
    """
    assert len(target.shape) == 3, 'Target shape must be 3D.'
    assert target.shape[2] == 4, 'Target must be RGBA.'
    assert len(source.shape) == 3, 'Source shape must be 3D.'
    assert source.shape[2] == 4, 'Source must be RGBA.'
    assert vertices.shape == (3, 5), 'Vertices must be 3x5.'

    vertices = np.copy(vertices)
    xy = vertices[:, :2]
    w = vertices[:, 2:3]
    uv = vertices[:, 3:]

    w = 1.0 / w
    xy *= w
    uv *= w
    w = w[:, 0]

    height, width, _ = target.shape
    xy[:, 0] = (xy[:, 0] + 1.0) * 0.5 * width
    xy[:, 1] = height - 1 -(xy[:, 1] + 1.0) * 0.5 * height

    v0, v1, v2 = xy
    area = 1 / edge(v0, v1, v2)

    source = source.astype(target.dtype, copy=False)
    v0 = v0.astype(np.float32, copy=False)
    v1 = v1.astype(np.float32, copy=False)
    v2 = v2.astype(np.float32, copy=False)
    uv = uv.astype(np.float32, copy=False)
    w = w.astype(np.float32, copy=False)
    _rasterize(target, source, area, v0, v1, v2, uv, w) 
Example 20
Source File: summary.py    From lingvo with Apache License 2.0 5 votes vote down vote up
def DrawHeadingTriangle(draw, x, y, heading, color, scale=25):
  """Draw a triangle indicating `heading` at `x`, `y` with `color`."""
  ch = scale * math.cos(heading)
  sh = scale * math.sin(heading)
  lead_point = (x - ch, y - sh)
  anchor_1 = (x - sh / 3, y + ch / 3)
  anchor_2 = (x + sh / 3, y - ch / 3)
  draw.line([anchor_1, lead_point, anchor_2], fill=color, width=4) 
Example 21
Source File: matrix.py    From BiblioPixel with MIT License 5 votes vote down vote up
def drawTriangle(self, x0, y0, x1, y1, x2, y2, color=None, aa=False):
        """
        Draw triangle with vertices (x0, y0), (x1, y1) and (x2, y2)

        :param aa: if True, use Bresenham's algorithm for line drawing;
            Otherwise use Xiaolin Wu's algorithm
        """
        md.draw_triangle(self.set, x0, y0, x1, y1, x2, y2, color, aa) 
Example 22
Source File: example.py    From NodeGraphQt with MIT License 4 votes vote down vote up
def draw_triangle_port(painter, rect, info):
    """
    Custom paint function for drawing a Triangle shaped port.

    Args:
        painter (QtGui.QPainter): painter object.
        rect (QtCore.QRectF): port rect used to describe parameters
                              needed to draw.
        info (dict): information describing the ports current state.
            {
                'port_type': 'in',
                'color': (0, 0, 0),
                'border_color': (255, 255, 255),
                'multi_connection': False,
                'connected': False,
                'hovered': False,
            }
    """
    painter.save()

    size = int(rect.height() / 2)
    triangle = QtGui.QPolygonF()
    triangle.append(QtCore.QPointF(-size, size))
    triangle.append(QtCore.QPointF(0.0, -size))
    triangle.append(QtCore.QPointF(size, size))

    transform = QtGui.QTransform()
    transform.translate(rect.center().x(), rect.center().y())
    port_poly = transform.map(triangle)

    # mouse over port color.
    if info['hovered']:
        color = QtGui.QColor(14, 45, 59)
        border_color = QtGui.QColor(136, 255, 35)
    # port connected color.
    elif info['connected']:
        color = QtGui.QColor(195, 60, 60)
        border_color = QtGui.QColor(200, 130, 70)
    # default port color
    else:
        color = QtGui.QColor(*info['color'])
        border_color = QtGui.QColor(*info['border_color'])

    pen = QtGui.QPen(border_color, 1.8)
    pen.setJoinStyle(QtCore.Qt.MiterJoin)

    painter.setPen(pen)
    painter.setBrush(color)
    painter.drawPolygon(port_poly)

    painter.restore() 
Example 23
Source File: core.py    From render-py with MIT License 4 votes vote down vote up
def draw_triangle(v1, v2, v3, canvas, color, wireframe=False):
    """
    Draw a triangle with 3 ordered vertices

    http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html
    """
    _draw_line = partial(draw_line, canvas=canvas, color=color)

    if wireframe:
        _draw_line(v1, v2)
        _draw_line(v2, v3)
        _draw_line(v1, v3)
        return

    def sort_vertices_asc_by_y(vertices):
        return sorted(vertices, key=lambda v: v.y)

    def fill_bottom_flat_triangle(v1, v2, v3):
        invslope1 = (v2.x - v1.x) / (v2.y - v1.y)
        invslope2 = (v3.x - v1.x) / (v3.y - v1.y)

        x1 = x2 = v1.x
        y = v1.y

        while y <= v2.y:
            _draw_line(Vec2d(x1, y), Vec2d(x2, y))
            x1 += invslope1
            x2 += invslope2
            y += 1

    def fill_top_flat_triangle(v1, v2, v3):
        invslope1 = (v3.x - v1.x) / (v3.y - v1.y)
        invslope2 = (v3.x - v2.x) / (v3.y - v2.y)

        x1 = x2 = v3.x
        y = v3.y

        while y > v2.y:
            _draw_line(Vec2d(x1, y), Vec2d(x2, y))
            x1 -= invslope1
            x2 -= invslope2
            y -= 1

    v1, v2, v3 = sort_vertices_asc_by_y((v1, v2, v3))

    # 填充
    if v1.y == v2.y == v3.y:
        pass
    elif v2.y == v3.y:
        fill_bottom_flat_triangle(v1, v2, v3)
    elif v1.y == v2.y:
        fill_top_flat_triangle(v1, v2, v3)
    else:
        v4 = Vec2d(int(v1.x + (v2.y - v1.y) / (v3.y - v1.y) * (v3.x - v1.x)), v2.y)
        fill_bottom_flat_triangle(v1, v2, v4)
        fill_top_flat_triangle(v2, v4, v3)


# 3D part