Given corner points of a Sudoku, warps original selection to a square image.

    :param corner_points:
    :type: corner_points: list
    :param image:
    :type image:
    :return:
    :rtype:
967455
def warp_image_by_corner_points_projection(corner_points, image):
    
    # Clarify by storing in named variables.
    top_left, top_right, bottom_left, bottom_right = np.array(corner_points)

    top_edge = np.linalg.norm(top_right - top_left)
    bottom_edge = np.linalg.norm(bottom_right - bottom_left)
    left_edge = np.linalg.norm(top_left - bottom_left)
    right_edge = np.linalg.norm(top_right - bottom_right)

    L = int(np.ceil(max([top_edge, bottom_edge, left_edge, right_edge])))
    src = np.array([top_left, top_right, bottom_left, bottom_right])
    dst = np.array([[0, 0], [L - 1, 0], [0, L - 1], [L - 1, L - 1]])

    tr = ProjectiveTransform()
    tr.estimate(dst, src)
    warped_image = warp(image, tr, output_shape=(L, L))
    out = resize(warped_image, (500, 500))

    return out
451345
def cornersphere(self, x):
        """"""
        nconstr = len(x) - 0
        if any(x[:nconstr] < 1):
            return np.NaN
        return sum(x**2) - nconstr
960829
private void squaresToPositionList() {
		this.positionPatterns.reset();
		List<DetectPolygonFromContour.Info> infoList = squareDetector.getPolygonInfo();
		for (int i = 0; i < infoList.size(); i++) {
			DetectPolygonFromContour.Info info = infoList.get(i);

			// The test below has been commented out because the new external only contour
			// detector discards all information related to internal contours
			// squares with no internal contour cannot possibly be a finder pattern
//			if( !info.hasInternal() )
//				continue;

			// See if the appearance matches a finder pattern
			double grayThreshold = (info.edgeInside+info.edgeOutside)/2;
			if( !checkPositionPatternAppearance(info.polygon,(float)grayThreshold))
				continue;

			// refine the edge estimate
			squareDetector.refine(info);

			PositionPatternNode pp = this.positionPatterns.grow();
			pp.reset();
			pp.square = info.polygon;
			pp.grayThreshold = grayThreshold;

			graph.computeNodeInfo(pp);
		}
	}
1014153
def image_by_slice_pos(pos)
      # Step 1: Try for an (exact) match:
      image = @image_positions[pos.round(2)]
      # Step 2: If no match, try to search for a close match:
      # (A close match is defined as the given slice position being within 1/3 of the
      # slice distance from an existing image instance in the series)
      if !image && @images.length > 1
        proximity = @images.collect{|img| (img.pos_slice - pos).abs}
        if proximity.min < slice_spacing / 3.0
          index = proximity.index(proximity.min)
          image = @images[index]
        end
      end
      return image
    end
975207
def snapPointToCanvas(self, x, y):
        
        if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height():
            x = max(x, 0)
            y = max(y, 0)
            x = min(x, self.pixmap.width())
            y = min(y, self.pixmap.height())
            return x, y, True

        return x, y, False
695805
def handleSubRectangles(self, images, subRectangles):
        

        if isinstance(subRectangles, (tuple, list)):
            # xy given directly

            # Check xy
            xy = subRectangles
            if xy is None:
                xy = (0, 0)
            if hasattr(xy, '__len__'):
                if len(xy) == len(images):
                    xy = [xxyy for xxyy in xy]
                else:
                    raise ValueError("len(xy) doesn't match amount of images.")
            else:
                xy = [xy for im in images]
            xy[0] = (0, 0)

        else:
            # Calculate xy using some basic image processing

            # Check Numpy
            if np is None:
                raise RuntimeError("Need Numpy to use auto-subRectangles.")

            # First make numpy arrays if required
            for i in range(len(images)):
                im = images[i]
                if isinstance(im, Image.Image):
                    tmp = im.convert()  # Make without palette
                    a = np.asarray(tmp)
                    if len(a.shape) == 0:
                        raise MemoryError("Too little memory to convert PIL image to array")
                    images[i] = a

            # Determine the sub rectangles
            images, xy = self.getSubRectangles(images)

        # Done
        return images, xy
882492
public void queryCorners(Point2D[] corners) {
		if ((corners == null) || (corners.length < 4))
			throw new IllegalArgumentException();
		if (corners[0] != null)
			corners[0].setCoords(xmin, ymin);
		else
			corners[0] = new Point2D(xmin, ymin);

		if (corners[1] != null)
			corners[1].setCoords(xmin, ymax);
		else
			corners[1] = new Point2D(xmin, ymax);

		if (corners[2] != null)
			corners[2].setCoords(xmax, ymax);
		else
			corners[2] = new Point2D(xmax, ymax);

		if (corners[3] != null)
			corners[3].setCoords(xmax, ymin);
		else
			corners[3] = new Point2D(xmax, ymin);
	}
249796
def image_box(center, shape, box):
    ''''''
    return tuple(slice_create(c, b, stop=s)
                 for c, s, b in zip(center, shape, box))
1333350
def addPoints(self, points, board_size=None):
        '''
        
        '''
        self.opts['foundPattern'].append(True)
        self.findCount += 1
        if board_size is not None:
            self.objpoints.append(self._mkObjPoints(board_size))
        else:
            self.objpoints.append(self.objp)
        s0 = points.shape[0]

        self.opts['imgPoints'].append(np.asarray(points).reshape(
            s0, 1, 2).astype(np.float32))
870696
def handle_sub_rectangles(self, images, sub_rectangles):
        
        image_info = [im.info for im in images]
        if isinstance(sub_rectangles, (tuple, list)):
            # xy given directly

            # Check xy
            xy = sub_rectangles
            if xy is None:
                xy = (0, 0)
            if hasattr(xy, '__len__'):
                if len(xy) == len(images):
                    xy = [xxyy for xxyy in xy]
                else:
                    raise ValueError("len(xy) doesn't match amount of images.")
            else:
                xy = [xy for im in images]
            xy[0] = (0, 0)

        else:
            # Calculate xy using some basic image processing

            # Check Numpy
            if np is None:
                raise RuntimeError("Need Numpy to use auto-sub_rectangles.")

            # First make numpy arrays if required
            for i in range(len(images)):
                im = images[i]
                if isinstance(im, Image.Image):
                    tmp = im.convert()  # Make without palette
                    a = np.asarray(tmp)
                    if len(a.shape) == 0:
                        raise MemoryError("Too little memory to convert PIL image to array")
                    images[i] = a

            # Determine the sub rectangles
            images, xy = self.get_sub_rectangles(images)

        # Done
        return images, xy, image_info
534083
def to_rectangular(image):
    
    # xy image, vertical scaled to 360 degrees
    xy = pyvips.Image.xyz(image.width, image.height)
    xy *= [1, 360.0 / image.height]

    index = xy.rect()

    # scale to image rect
    scale = min(image.width, image.height) / float(image.width)
    index *= scale / 2.0
    index += [image.width / 2.0, image.height / 2.0]

    return image.mapim(index)
21396
public synchronized void process(GrayF32 image, List<Point2D_F64> sides) {
		if( sides.size() != 4 )
			throw new IllegalArgumentException("Expected 4 sidesCollision");

		updateScore(image,sides);

		if( currentScore < bestScore ) {
			bestScore = currentScore;
			if( bestImage == null ) {
				bestImage = new BufferedImage(image.getWidth(), image.getHeight(),BufferedImage.TYPE_INT_RGB);
			}
			ConvertBufferedImage.convertTo(image,bestImage);
		}
	}
159450
def generate_unit_squares(image_width, image_height):
    """"""
    # Iterate over the required rows and cells.  The for loops (x, y)
    # give the coordinates of the top left-hand corner of each square:
    #
    #      (x, y) +-----+ (x + 1, y)
    #             |     |
    #             |     |
    #             |     |
    #  (x, y + 1) +-----+ (x + 1, y + 1)
    #
    for x in range(image_width):
        for y in range(image_height):
            yield [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)]
89829
def rectangles_from_points(S):
    
    answ = 0
    pairs = {}
    for j in range(len(S)):
        for i in range(j):
            px, py = S[i]
            qx, qy = S[j]
            center = (px + qx, py + qy)
            dist = (px - qx) ** 2 + (py - qy) ** 2
            sign = (center, dist)
            if sign in pairs:
                answ += len(pairs[sign])
                pairs[sign].append((i, j))
            else:
                pairs[sign] = [(i, j)]
    return answ
307808
int selectCorner( GridInfo info ) {

		info.lookupGridCorners(cornerList);

		int bestCorner = -1;
		double bestScore = Double.MAX_VALUE;
		boolean bestIsCornerSquare = false;

		for (int i = 0; i < cornerList.size(); i++) {
			Node n = cornerList.get(i);

			boolean corner = isCornerValidOrigin(n);

			// If there are no corner points which are valid corners, then any corner can be the origin if
			// allowNoCorner is true
			if( corner || (allowNoCorner && !bestIsCornerSquare) ) {
				// sanity check the shape
				if( checkShape != null ) {
					if( i%2==0 ) {
						if( !checkShape.isValidShape(info.rows,info.cols)) {
							continue;
						}
					} else {
						if( !checkShape.isValidShape(info.cols,info.rows)) {
							continue;
						}
					}
				}

				// If the distance is to (0,0) pixel is smaller or this is a corner square and the other best
				// is not a corner square
				double distance = n.normSq();
				if( distance < bestScore || (!bestIsCornerSquare && corner )) {
					bestIsCornerSquare |= corner;
					bestScore = distance;
					bestCorner = i;
				}
			}
		}
		info.hasCornerSquare = bestIsCornerSquare;
		return bestCorner;
	}
897224
function getRectangleFromImagePlane(imagePlane) {
  // Get the points
  const topLeft = imagePointToPatientPoint(
    {
      x: 0,
      y: 0,
    },
    imagePlane
  );
  const topRight = imagePointToPatientPoint(
    {
      x: imagePlane.columns,
      y: 0,
    },
    imagePlane
  );
  const bottomLeft = imagePointToPatientPoint(
    {
      x: 0,
      y: imagePlane.rows,
    },
    imagePlane
  );
  const bottomRight = imagePointToPatientPoint(
    {
      x: imagePlane.columns,
      y: imagePlane.rows,
    },
    imagePlane
  );

  // Get each side as a vector
  const rect = {
    top: new external.cornerstoneMath.Line3(topLeft, topRight),
    left: new external.cornerstoneMath.Line3(topLeft, bottomLeft),
    right: new external.cornerstoneMath.Line3(topRight, bottomRight),
    bottom: new external.cornerstoneMath.Line3(bottomLeft, bottomRight),
  };

  return rect;
}
1210025
def slices(img, shape=[3, 4]):
    
    sh = np.asarray(shape)
    i_max = np.prod(sh)
    allimg = np.zeros(img.shape[-2:] * sh)

    for i in range(0, i_max):
        # i = 0
        islice = round((img.shape[0] / float(i_max)) * i)
        #         print(islice)
        imgi = img[islice, :, :]
        coords = index_to_coords(i, sh)
        aic = np.asarray(img.shape[-2:]) * coords

        allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi

    #     plt.imshow(imgi)
    #     print(imgi.shape)
    #     print(img.shape)
    return allimg