Draws a flat cube to show where the square fiducial is on the image
352614
public static void drawLabelCenter(Se3_F64 targetToCamera, CameraPinholeBrown intrinsic, String label,
									   Graphics2D g2 , double scale)
	{
		// Computer the center of the fiducial in pixel coordinates
		Point2D_F64 p = new Point2D_F64();
		Point3D_F64 c = new Point3D_F64();
		WorldToCameraToPixel worldToPixel = PerspectiveOps.createWorldToPixel(intrinsic, targetToCamera);
		worldToPixel.transform(c,p);

		drawLabel(p,label,g2,scale);
	}
1015180
def draw_boundary_images(glf, glb, v, f, vpe, fpe, camera):
    """"""
    glf.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glb.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    # Figure out which edges are on pairs of differently visible triangles
    from opendr.geometry import TriNormals
    tn = TriNormals(v, f).r.reshape((-1,3))
    campos = -cv2.Rodrigues(camera.rt.r)[0].T.dot(camera.t.r)
    rays_to_verts = v.reshape((-1,3)) - row(campos)
    rays_to_faces = rays_to_verts[f[:,0]] + rays_to_verts[f[:,1]] + rays_to_verts[f[:,2]]
    dps = np.sum(rays_to_faces * tn, axis=1)
    dps = dps[fpe[:,0]] * dps[fpe[:,1]]
    silhouette_edges = np.asarray(np.nonzero(dps<=0)[0], np.uint32)
    non_silhouette_edges = np.nonzero(dps>0)[0]
    lines_e = vpe[silhouette_edges]
    lines_v = v

    visibility = draw_edge_visibility(glb, lines_v, lines_e, f, hidden_wireframe=True)
    shape = visibility.shape
    visibility = visibility.ravel()
    visible = np.nonzero(visibility.ravel() != 4294967295)[0]
    visibility[visible] = silhouette_edges[visibility[visible]]
    result = visibility.reshape(shape)
    return result
1286044
function imageBounding(image) {
  var imageObj = element_object(image);
  if (!imageObj) return null;

  if (!imageObj.transform) imageObj.transform = 'matrix(1 0 0 1 0 0)';
  var matrix = helper.matrixStrToArr(imageObj.transform.trim());
  var width = imageObj.width;
  var height = imageObj.height;

  // The matrix variable contains 6 numbers, let's call them
  // a, b, c, d, e, f
  var a = matrix[0];
  var b = matrix[1];
  var c = matrix[2];
  var d = matrix[3];
  var e = matrix[4];
  var f = matrix[5];

  // The original top left point of the image is unknown. The e and f
  // in the matrix is the transformed top left point.
  // Now assume translate is applied to the image first, we have the
  // following points: (e, f), (e+w, f), (e+w, f+h), (e, f+h)
  var points1 = [e, f, e + width, f, e + width, f + height, e, f + height];

  // Then apply trasform matrix (a b c d 0 0) to these points, the
  // formula is newX = a*x + c*y, newY = b*x + d*y
  var points2 = [];
  for (var i = 0; i < points1.length; i += 2) {
    points2[i] = a * points1[i] + c * points1[i + 1];
    points2[i + 1] = b * points1[i] + d * points1[i + 1];
  }

  // Find the delta of the top left point and apply it to all the points
  var dx = points2[0] - points1[0];
  var dy = points2[1] - points1[1];
  var points = [e, f];
  for (var i = 2; i < points1.length; i += 2) {
    points[i] = points2[i] - dx;
    points[i + 1] = points2[i + 1] - dy;
  }

  var left = Number.POSITIVE_INFINITY;
  var right = Number.NEGATIVE_INFINITY;
  var top = Number.POSITIVE_INFINITY;
  var bottom = Number.NEGATIVE_INFINITY;

  for (var i = 0; i < points.length; i += 2) {
    if (points[i] < left) left = points[i];
    if (points[i] > right) right = points[i];
    if (points[i + 1] < top) top = points[i + 1];
    if (points[i + 1] > bottom) bottom = points[i + 1];
  }

  return {
    left: left,
    right: right,
    top: top,
    bottom: bottom,
    width: right - left,
    height: bottom - top
  };
}
1020755
def correctGrid(self, img, grid):
        '''
        
        '''

        self.img = imread(img)
        h = self.homography  # TODO: cleanup only needed to get newBorder attr.

        if self.opts['do_correctIntensity']:
            self.img = self.img / self._getTiltFactor(self.img.shape)

        s0, s1 = grid.shape[:2]
        n0, n1 = s0 - 1, s1 - 1

        snew = self._newBorders
        b = self.opts['border']

        sx, sy = (snew[0] - 2 * b) // n0, (snew[1] - 2 * b) // n1

        out = np.empty(snew[::-1], dtype=self.img.dtype)

        def warp(ix, iy, objP, outcut):
            shape = outcut.shape[::-1]
            quad = grid[ix:ix + 2,
                        iy:iy + 2].reshape(4, 2)[np.array([0, 2, 3, 1])]
            hcell = cv2.getPerspectiveTransform(
                quad.astype(np.float32), objP)
            cv2.warpPerspective(self.img, hcell, shape, outcut,
                                flags=cv2.INTER_LANCZOS4,
                                **self.opts['cv2_opts'])
            return quad

        objP = np.array([[0, 0],
                         [sx, 0],
                         [sx, sy],
                         [0, sy]], dtype=np.float32)
        # INNER CELLS
        for ix in range(1, n0 - 1):
            for iy in range(1, n1 - 1):
                sub = out[iy * sy + b: (iy + 1) * sy + b,
                          ix * sx + b: (ix + 1) * sx + b]
#                 warp(ix, iy, objP, sub)

                shape = sub.shape[::-1]
                quad = grid[ix:ix + 2,
                            iy:iy + 2].reshape(4, 2)[np.array([0, 2, 3, 1])]
#                 print(quad, objP)

                hcell = cv2.getPerspectiveTransform(
                    quad.astype(np.float32), objP)
                cv2.warpPerspective(self.img, hcell, shape, sub,
                                    flags=cv2.INTER_LANCZOS4,
                                    **self.opts['cv2_opts'])

#         return out
        # TOP CELLS
        objP[:, 1] += b
        for ix in range(1, n0 - 1):
            warp(ix, 0, objP, out[: sy + b,
                                  ix * sx + b: (ix + 1) * sx + b])
        # BOTTOM CELLS
        objP[:, 1] -= b
        for ix in range(1, n0 - 1):
            iy = (n1 - 1)
            y = iy * sy + b
            x = ix * sx + b
            warp(ix, iy, objP, out[y: y + sy + b, x: x + sx])
        # LEFT CELLS
        objP[:, 0] += b
        for iy in range(1, n1 - 1):
            y = iy * sy + b
            warp(0, iy, objP, out[y: y + sy, : sx + b])
        # RIGHT CELLS
        objP[:, 0] -= b
        ix = (n0 - 1)
        x = ix * sx + b
        for iy in range(1, n1 - 1):
            y = iy * sy + b
            warp(ix, iy, objP, out[y: y + sy, x: x + sx + b])
        # BOTTOM RIGHT CORNER
        warp(n0 - 1, n1 - 1, objP, out[-sy - b - 1:, x: x + sx + b])
#         #TOP LEFT CORNER
        objP += (b, b)
        warp(0, 0, objP, out[0: sy + b, 0: sx + b])
        # TOP RIGHT CORNER
        objP[:, 0] -= b
#         x = (n0-1)*sx+b
        warp(n0 - 1, 0, objP, out[: sy + b, x: x + sx + b])
#         #BOTTOM LEFT CORNER
        objP += (b, -b)
        warp(0, n1 - 1, objP, out[-sy - b - 1:, : sx + b])
        return out
432224
function drawCell(cell, canvas, loc, fill) {
  // Also takes in a number and outputs a cell.
  if (typeof loc == 'undefined') loc = {x: 0, y: 0};
  if (typeof fill == 'undefined') fill = '#8ED6FF';

  var quadrant_width = 50;
  // Given a number in a quadrant and a location specifying the top left corner of
  // the quadrant, draw the relevant shape.
  function drawQuadrant(n, q, loc) {
    // draw upper triangle going certain direction at location
    function drawUpperTriangle(d, loc) {
      if (d == "r") {
        var first = {x: 50, y: 0};
        var second = {x: 50, y: 50};
      } else {
        var first = {x: 50, y: 0};
        var second = {x: 0, y: 50};
      }
      context.beginPath();
      context.moveTo(loc.x, loc.y);
      context.lineTo(loc.x + first.x, loc.y + first.y);
      context.lineTo(loc.x + second.x, loc.y + second.y);
      context.lineTo(loc.x, loc.y);
      context.lineWidth = 1;
      context.strokeStyle = 'black';
      context.stroke();
      context.fillStyle = fill;
      context.fill();
      context.closePath();
    }
    function drawLowerTriangle(d, loc) {
      if (d == "r") {
        loc = {x: loc.x + 50, y: loc.y};
        var first = {x: 0, y: 50};
        var second = {x: -50, y: 50};
      } else {
        var first = {x: 50, y: 50};
        var second = {x: 0, y: 50};
      }
      context.beginPath();
      context.moveTo(loc.x, loc.y);
      context.lineTo(loc.x + first.x, loc.y + first.y);
      context.lineTo(loc.x + second.x, loc.y + second.y);
      context.lineTo(loc.x, loc.y);
      context.lineWidth = 1;
      context.strokeStyle = 'black';
      context.stroke();
      context.fillStyle = fill;
      context.fill();
      context.closePath();
    }
    function drawTileOutline(loc) {
      context.beginPath();
      context.moveTo(loc.x, loc.y);
      context.lineTo(loc.x + 50, loc.y);
      context.lineTo(loc.x + 50, loc.y + 50);
      context.lineTo(loc.x, loc.y + 50);
      context.lineTo(loc.x, loc.y);
      context.lineWidth = 1;
      context.strokeStyle = 'black';
      context.stroke();
      context.closePath();
    }
    // blank space, just draw outline without filling.
    if (n == 0) {
      drawTileOutline(loc);
    } else if (n == 1) { // tile.
      context.beginPath();
      context.moveTo(loc.x, loc.y);
      context.lineTo(loc.x + 50, loc.y);
      context.lineTo(loc.x + 50, loc.y + 50);
      context.lineTo(loc.x, loc.y + 50);
      context.lineTo(loc.x, loc.y);
      context.lineWidth = 1;
      context.strokeStyle = 'black';
      context.stroke();
      context.fillStyle = fill;
      context.fill();
      context.closePath();
    } else if (n == 2) {
      drawTileOutline(loc);
      if (q == 0 || q == 2) {
        drawLowerTriangle("l", loc);
      } else {
        drawLowerTriangle("r", loc);
      }
    } else if (n == 3) {
      drawTileOutline(loc);
      if (q == 0 || q == 2) {
        drawUpperTriangle("r", loc);
      } else {
        drawUpperTriangle("l", loc);
      }
    }
  }
  var context = canvas.getContext('2d');
  var offsets = [
    {x: 0, y: 0},
    {x: 50, y: 0},
    {x: 50, y: 50},
    {x: 0, y: 50}
  ];

  // number at element, quadrant
  cell.array.forEach(function(n, q) {
    var offset = offsets[q];
    var new_loc = {x: loc.x + offset.x, y: loc.y + offset.y};
    drawQuadrant(n, q, new_loc);
  });
}
166692
def makedraw(self):
        
        if self.draw == None:
            self.draw = imdw.Draw(self.pilimage)
1124383
def Draw(self, grid, attr, dc, rect, row, col, isSelected):
        """"""

        key = row, col, grid.current_table

        # If cell is merge draw the merging cell if invisibile
        if grid.code_array.cell_attributes[key]["merge_area"]:
            key = self.get_merging_cell(grid, key)

        drawn_rect = self._get_drawn_rect(grid, key, rect)
        if drawn_rect is None:
            return

        cell_cache_key = self._get_draw_cache_key(grid, key, drawn_rect,
                                                  isSelected)

        mdc = wx.MemoryDC()

        if vlc is not None and key in self.video_cells and \
           grid.code_array.cell_attributes[key]["panel_cell"]:
            # Update video position of previously created video panel
            self.video_cells[key].SetClientRect(drawn_rect)

        elif cell_cache_key in self.cell_cache:
            mdc.SelectObject(self.cell_cache[cell_cache_key])

        else:
            code = grid.code_array(key)
            if vlc is not None and code is not None and \
               grid.code_array.cell_attributes[key]["panel_cell"]:
                try:
                    # A panel is to be displayed
                    panel_cls = grid.code_array[key]

                    # Assert that we have a subclass of a wxPanel that we
                    # can instantiate
                    assert issubclass(panel_cls, wx.Panel)

                    video_panel = panel_cls(grid)
                    video_panel.SetClientRect(drawn_rect)
                    # Register video cell
                    self.video_cells[key] = video_panel

                    return

                except Exception, err:
                    # Someting is wrong with the panel to be displayed
                    post_command_event(grid.main_window, self.StatusBarMsg,
                                       text=unicode(err))
                    bmp = self._get_cairo_bmp(mdc, key, drawn_rect, isSelected,
                                              grid._view_frozen)
            else:
                bmp = self._get_cairo_bmp(mdc, key, drawn_rect, isSelected,
                                          grid._view_frozen)

            # Put resulting bmp into cache
            self.cell_cache[cell_cache_key] = bmp

        dc.Blit(drawn_rect.x, drawn_rect.y,
                drawn_rect.width, drawn_rect.height,
                mdc, 0, 0, wx.COPY)

        # Draw cursor
        if grid.actions.cursor[:2] == (row, col):
            self.update_cursor(dc, grid, row, col)
740604
def brain(
    draw=True, show=True, fiducial=True, flat=True, inflated=True, subject='S1', interval=1000, uv=True, color=None
):
    
    import ipyvolume as ipv

    try:
        import cortex
    except:
        warnings.warn("it seems pycortex is not installed, which is needed for this example")
        raise
    xlist, ylist, zlist = [], [], []
    polys_list = []

    def add(pts, polys):
        xlist.append(pts[:, 0])
        ylist.append(pts[:, 1])
        zlist.append(pts[:, 2])
        polys_list.append(polys)

    def n(x):
        return (x - x.min()) / x.ptp()

    if fiducial or color is True:
        pts, polys = cortex.db.get_surf('S1', 'fiducial', merge=True)
        x, y, z = pts.T
        r = n(x)
        g = n(y)
        b = n(z)
        if color is True:
            color = np.array([r, g, b]).T.copy()
        else:
            color = None
        if fiducial:
            add(pts, polys)
    else:
        if color is False:
            color = None
    if inflated:
        add(*cortex.db.get_surf('S1', 'inflated', merge=True, nudge=True))
    u = v = None
    if flat or uv:
        pts, polys = cortex.db.get_surf('S1', 'flat', merge=True, nudge=True)
        x, y, z = pts.T
        u = n(x)
        v = n(y)
        if flat:
            add(pts, polys)

    polys_list.sort(key=lambda x: len(x))
    polys = polys_list[0]
    if draw:
        if color is None:
            mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, u=u, v=v)
        else:
            mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, color=color, u=u, v=v)
        if show:
            if len(x) > 1:
                ipv.animation_control(mesh, interval=interval)
            ipv.squarelim()
            ipv.show()
        return mesh
    else:
        return xlist, ylist, zlist, polys
737608
def show(self, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
        color:str='white', **kwargs):
        ""
        if ax is None: _,ax = plt.subplots(figsize=figsize)
        bboxes, lbls = self._compute_boxes()
        h,w = self.flow.size
        bboxes.add_(1).mul_(torch.tensor([h/2, w/2, h/2, w/2])).long()
        for i, bbox in enumerate(bboxes):
            if lbls is not None: text = str(lbls[i])
            else: text=None
            _draw_rect(ax, bb2hw(bbox), text=text, color=color)
1060852
function square() {
   var v = [1,1], off; var a = arguments, p = a[0];
   if(p&&!p.size) v = [p,p];
   if(p&&p.length) v = a[0], p = a[1];
   if(p&&p.size&&p.size.length) v = p.size;

   off = [v[0]/2,v[1]/2];
   if(p&&p.center==true) off = [0,0];

   var o = CAG.rectangle({center:off,radius:[v[0]/2,v[1]/2]});

   return o;
}
1164992
def show_xys(self, xs, ys, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
        ""
        super().show_xys(ys, xs, imgsize=imgsize, figsize=figsize, **kwargs)
1134842
function drawScene() {
  // Clear the canvas before we start drawing on it.
  gl.clearColor(0, 0, 0, 1);
  gl.clearDepth(1.0);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  // Establish the perspective with which we want to view the
  // scene. Our field of view is 45 degrees, with a width/height
  // ratio of 640:480, and we only want to see objects between 0.1 units
  // and 100 units away from the camera.

  perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);

  // Set the drawing position to the "identity" point, which is
  // the center of the scene.

  loadIdentity();

  // Now move the drawing position a bit to where we want to start
  // drawing the cube.

  mvTranslate([-0.0, 0.0, -6.0]);

  // Save the current matrix, then rotate before we draw.

  mvPushMatrix();
  mvRotate(cubeRotation, [1, 0, 1]);
  mvTranslate([cubeXOffset, cubeYOffset, cubeZOffset]);

  // Draw the cube by binding the array buffer to the cube's vertices
  // array, setting attributes, and pushing it to GL.

  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer);
  gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);

  // Draw the cube.

  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
  setMatrixUniforms();

  var pUniform = gl.getUniformLocation(shaderProgram, "uniformArray");
  gl.uniform2fv(pUniform, new Float32Array([1,0.2,0.4,1]));

  gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);

  // Restore the original matrix

  mvPopMatrix();

  // Update the rotation for the next draw, if it's time to do so.

  var currentTime = (new Date).getTime();
  if (lastCubeUpdateTime) {
    var delta = currentTime - lastCubeUpdateTime;

    cubeRotation += (30 * delta) / 1000.0;
    cubeXOffset += xIncValue * ((30 * delta) / 1000.0);
    cubeYOffset += yIncValue * ((30 * delta) / 1000.0);
    cubeZOffset += zIncValue * ((30 * delta) / 1000.0);

    if (Math.abs(cubeYOffset) > 2.5) {
      xIncValue = -xIncValue;
      yIncValue = -yIncValue;
      zIncValue = -zIncValue;
    }
  }

  lastCubeUpdateTime = currentTime;

  window.requestAnimationFrame(function() {
        drawScene();
  });
}
431218
def squarelim():
    """"""
    fig = gcf()
    xmin, xmax = fig.xlim
    ymin, ymax = fig.ylim
    zmin, zmax = fig.zlim
    width = max([abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin)])
    xc = (xmin + xmax) / 2
    yc = (ymin + ymax) / 2
    zc = (zmin + zmax) / 2
    xlim(xc - width / 2, xc + width / 2)
    ylim(yc - width / 2, yc + width / 2)
    zlim(zc - width / 2, zc + width / 2)
656216
def visualize(hog, grid=(10, 10), radCircle=None):
    '''
    
    '''
    s0, s1, nang = hog.shape
    angles = np.linspace(0, np.pi, nang + 1)[:-1]
    # center of each sub array:
    cx, cy = s0 // (2 * grid[0]), s1 // (2 * grid[1])
    # max. radius of polynomial around cenetr:
    rx, ry = cx, cy
    # for drawing a position indicator (circle):
    if radCircle is None:
        radCircle = max(1, rx // 10)
    # output array:
    out = np.zeros((s0, s1), dtype=np.uint8)
    # point of polynomial:
    pts = np.empty(shape=(1, 2 * nang, 2), dtype=np.int32)
    # takes grid[0]*grid[1] sample HOG values:
    samplesHOG = subCell2DFnArray(hog, lambda arr: arr[cx, cy], grid)
    mxHOG = samplesHOG.max()
    # sub array slices:
    slices = list(subCell2DSlices(out, grid))
    m = 0
    for m, hhh in enumerate(samplesHOG.reshape(grid[0] * grid[1], nang)):
        hhmax = hhh.max()
        hh = hhh / hhmax
        sout = out[slices[m][2:4]]
        for n, (o, a) in enumerate(zip(hh, angles)):
            pts[0, n, 0] = cx + np.cos(a) * o * rx
            pts[0, n, 1] = cy + np.sin(a) * o * ry
            pts[0, n + nang, 0] = cx + np.cos(a + np.pi) * o * rx
            pts[0, n + nang, 1] = cy + np.sin(a + np.pi) * o * ry

        cv2.fillPoly(sout, pts, int(255 * hhmax / mxHOG))
        cv2.circle(sout, (cx, cy), radCircle, 0, thickness=-1)

    return out
953668
def draw(surface, z_order, colour)
      surface.draw_rectangle(position, size, z_order, colour)
    end
434286
def draw_tile(x = 0, y = 0, opts = {})

      opts[:canvas] ||= @canvas
      opts[:sx] ||= 0
      opts[:sy] ||= 0
      opts[:swidth] ||= width - opts[:sx]
      opts[:sheight] ||= height - opts[:sy]
      opts[:dwidth] ||= opts[:swidth]
      opts[:dheight] ||= opts[:sheight]

      %x{
        #{opts[:canvas].context}.drawImage(
          #{@img},
          #{opts[:sx]},
          #{opts[:sy]},
          #{opts[:swidth]},
          #{opts[:sheight]},
          #{x},
          #{y},
          #{opts[:dwidth]},
          #{opts[:dheight]}
        );
      }
    end
855910
function(hexDimensions, radius) {
  var positionArray = [];
  var pixelCoordinates;

  //For every hex, place an instance of the original mesh. The symbol fills in 3 of the 6 lines, the other 3 being shared with an adjacent hex

  //Make a hexagonal grid of hexagons since it is approximately circular.
  var u = 0;
  var v = 0;
  //For each radius
  positionArray.push({ y: 0, x: 0 });
  for (var i = 1; i < radius + 1; i++) {
    //Hold u constant as the radius, add an instance for each v
    for (v = -i; v <= 0; v++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(i, v);

      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold u constant as negative the radius, add an instance for each v
    for (v = 0; v <= i; v++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(-i, v);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold v constant as the radius, add an instance for each u
    for (u = -i + 1; u <= 0; u++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(u, i);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold v constant as negative the radius, add an instance for each u
    for (u = 0; u < i; u++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(u, -i);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold w constant as the radius, add an instance for each u + v = -i
    for (u = -i + 1, v = -1; v > -i; u++, v--) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(u, v);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold w constant as the negative radius, add an instance for each u + v = i
    for (u = i - 1, v = 1; v < i; u--, v++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(u, v);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }
  }

  return positionArray;
}