Horn Schunck legacy OpenCV function requires we use these old-fashioned cv matrices, not numpy array
14985
def setupuv(rc):
    
    if cv is not None:
        (r, c) = rc
        u = cv.CreateMat(r, c, cv.CV_32FC1)
        v = cv.CreateMat(r, c, cv.CV_32FC1)
        return (u, v)
    else:
        return [None]*2
1334158
def zoom_cv(x,z):
    
    if z==0: return x
    r,c,*_ = x.shape
    M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.)
    return cv2.warpAffine(x,M,(c,r))
839623
def genericCameraMatrix(shape, angularField=60):
    '''
    
    '''
    # http://nghiaho.com/?page_id=576
    # assume that the optical centre is in the middle:
    cy = int(shape[0] / 2)
    cx = int(shape[1] / 2)

    # assume that the FOV is 60 DEG (webcam)
    fx = fy = cx / np.tan(angularField / 2 * np.pi /
                          180)  # camera focal length
    # see
    # http://docs.opencv.org/doc/tutorials/calib3d/camera_calibration/camera_calibration.html
    return np.array([[fx, 0, cx],
                     [0, fy, cy],
                     [0, 0, 1]
                     ], dtype=np.float32)
912238
def validation_scatter(self, log_lam, b, masks, pre_v, gp, flux,
                           time, med):
        '''
        

        '''

        # Update the lambda matrix
        self.lam[b] = 10 ** log_lam

        # Validation set scatter
        scatter = [None for i in range(len(masks))]
        for i in range(len(masks)):
            model = self.cv_compute(b, *pre_v[i])
            try:
                gpm, _ = gp.predict(flux - model - med, time[masks[i]])
            except ValueError:
                # Sometimes the model can have NaNs if
                # `lambda` is a crazy value
                return 1.e30
            fdet = (flux - model)[masks[i]] - gpm
            scatter[i] = 1.e6 * (1.4826 * np.nanmedian(np.abs(fdet / med -
                                 np.nanmedian(fdet / med))) /
                                 np.sqrt(len(masks[i])))

        return np.max(scatter)
415157
def convert_to_cvxpy(sdp):
    
    from cvxpy import Minimize, Problem, Variable
    row_offsets = [0]
    cumulative_sum = 0
    for block_size in sdp.block_struct:
        cumulative_sum += block_size ** 2
        row_offsets.append(cumulative_sum)
    x = Variable(sdp.n_vars)
    # The moment matrices are the first blocks of identical size
    constraints = []
    for idx, bs in enumerate(sdp.block_struct):
        nonzero_set = set()
        F = [lil_matrix((bs, bs)) for _ in range(sdp.n_vars+1)]
        for ri, row in enumerate(sdp.F.rows[row_offsets[idx]:
                                            row_offsets[idx+1]],
                                 row_offsets[idx]):
            block_index, i, j = convert_row_to_sdpa_index(sdp.block_struct,
                                                          row_offsets, ri)
            for col_index, k in enumerate(row):
                value = sdp.F.data[ri][col_index]
                F[k][i, j] = value
                F[k][j, i] = value
                nonzero_set.add(k)
        if bs > 1:
            sum_ = sum(F[k]*x[k-1] for k in nonzero_set if k > 0)
            if not isinstance(sum_, (int, float)):
                if F[0].getnnz() > 0:
                    sum_ += F[0]
                constraints.append(sum_ >> 0)
        else:
            sum_ = sum(F[k][0, 0]*x[k-1] for k in nonzero_set if k > 0)
            if not isinstance(sum_, (int, float)):
                sum_ += F[0][0, 0]
                constraints.append(sum_ >= 0)
    obj = sum(ci*xi for ci, xi in zip(sdp.obj_facvar, x) if ci != 0)
    problem = Problem(Minimize(obj), constraints)
    return problem
1361461
def eighCovarianceMatrix(cfile):
    
    # precompute eigenvalue decomposition
    K = np.loadtxt(cfile+'.cov')
    K+= 1e-4*sp.eye(K.shape[0])
    S,U = la.eigh(K); S=S[::-1]; U=U[:,::-1]
    np.savetxt(cfile+'.cov.eval',S,fmt='%.6f')
    np.savetxt(cfile+'.cov.evec',U,fmt='%.6f')
643781
def fit_transform(
        self,
        X,
        projection="sum",
        scaler=preprocessing.MinMaxScaler(),
        distance_matrix=False,
    ):
        

        projections = projection
        scalers = scaler
        distance_matrices = distance_matrix

        # Turn single projection arguments into a pipeline
        if isinstance(projection, list) and isinstance(projection[0], int):
            projections = [projection]

        if not isinstance(projection, list):
            projections = [projection]

        # Turn single scaler arguments into a pipeline
        if not isinstance(scaler, list):
            scalers = [scaler]

        # Turn single distance matrix arguments into a pipeline
        if not isinstance(distance_matrix, list):
            distance_matrices = [distance_matrix]

        # set defaults to first list item, if not (correctly) set by the user
        if len(scalers) != len(projections):
            scalers = [scalers[0]] * len(projections)

        if len(distance_matrices) != len(projections):
            distance_matrices = [distance_matrices[0]] * len(projections)

        if self.verbose > 0:
            print("..Composing projection pipeline of length %s:" % (len(projections)))
            print("\tProjections: %s" % ("\n\t\t".join(map(str, projections))))
            print("\tDistance matrices: %s" % ("\n".join(map(str, distance_matrices))))
            print("\tScalers: %s" % ("\n".join(map(str, scalers))))

        # Pipeline Stack the projection functions
        lens = X
        for projection, scaler, distance_matrix in zip(
            projections, scalers, distance_matrices
        ):
            lens = self.project(
                lens,
                projection=projection,
                scaler=scaler,
                distance_matrix=distance_matrix,
            )

        return lens
519200
def undistortPoints(self, points, keepSize=False):
        '''
        
        '''
        s = self.img.shape
        cam = self.coeffs['cameraMatrix']
        d = self.coeffs['distortionCoeffs']

        pts = np.asarray(points, dtype=np.float32)
        if pts.ndim == 2:
            pts = np.expand_dims(pts, axis=0)

        (newCameraMatrix, roi) = cv2.getOptimalNewCameraMatrix(cam,
                                                               d, s[::-1], 1,
                                                               s[::-1])
        if not keepSize:
            xx, yy = roi[:2]
            pts[0, 0] -= xx
            pts[0, 1] -= yy

        return cv2.undistortPoints(pts,
                                   cam, d, P=newCameraMatrix)
584137
def linear_response_matrix(self, kwargs_lens=None, kwargs_source=None, kwargs_lens_light=None, kwargs_ps=None):
        
        A = self._response_matrix(self.ImageNumerics.ra_grid_ray_shooting, self.ImageNumerics.dec_grid_ray_shooting,
                                      kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, self.ImageNumerics.mask)
        return A
613224
function coordMatrixToCoordArray(coordMatrix) {
                var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);
                var k = 0;
                for (var i = 0; i < coordMatrix[0].length; ++i) {
                    for (var j = 0; j < coordMatrix.length; ++j) {
                        coodinatesArray[k] = coordMatrix[j][i];
                        ++k;
                    }
                }

                return coodinatesArray;
            }
715864
def from_numpy(cls, 
      arr, vol_path='file:///tmp/image/'+generate_random_string(),
      resolution=(4,4,40), voxel_offset=(0,0,0), 
      chunk_size=(128,128,64), layer_type=None, max_mip=0,
      encoding='raw', compress=None
    ):
    
    if not layer_type:
      if arr.dtype in (np.bool, np.uint32, np.uint64, np.uint16):
        layer_type = 'segmentation'
      elif np.issubdtype(arr.dtype, np.integer) \
                        or np.issubdtype(arr.dtype, np.floating):
        layer_type = 'image'
      else:
        raise NotImplementedError

    if arr.ndim == 3:
      num_channels = 1
    elif arr.ndim == 4:
      num_channels = arr.shape[-1]
    else:
      raise NotImplementedError

    info = cls.create_new_info(num_channels, layer_type, arr.dtype.name, encoding, resolution, 
                               voxel_offset, arr.shape[:3], chunk_size=chunk_size, max_mip=max_mip)
    vol = CloudVolume(vol_path, info=info, bounded=True, compress=compress) 
    # save the info file
    vol.commit_info()
    vol.provenance.processing.append({
      'method': 'from_numpy',
      'date': strftime('%Y-%m-%d %H:%M %Z')
    })
    vol.commit_provenance()
    # save the numpy array
    vol[:,:,:] = arr
    return vol
320729
function svdPack() {
                var result = lapack$1.sgesvd('A', 'A', this.elements);

                return {
                    U: $M(result.U),
                    S: $M(result.S).column(1).toDiagonalMatrix(),
            	V: $M(result.VT).transpose()
                };
            }
1337126
def stretch_cv(x,sr,sc,interpolation=cv2.INTER_AREA):
    
    if sr==0 and sc==0: return x
    r,c,*_ = x.shape
    x = cv2.resize(x, None, fx=sr+1, fy=sc+1, interpolation=interpolation)
    nr,nc,*_ = x.shape
    cr = (nr-r)//2; cc = (nc-c)//2
    return x[cr:r+cr, cc:c+cc]
809291
def no_crop(im, min_sz=None, interpolation=cv2.INTER_AREA):
    
    r,c,*_ = im.shape
    if min_sz is None: min_sz = min(r,c)
    return cv2.resize(im, (min_sz, min_sz), interpolation=interpolation)
1219553
public static void convolveHV(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, int edgeAction) {
		int index = 0;
		float[] matrix = kernel.getKernelData( null );
		int rows = kernel.getHeight();
		int cols = kernel.getWidth();
		int rows2 = rows/2;
		int cols2 = cols/2;

		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				float r = 0, g = 0, b = 0, a = 0;

				for (int row = -rows2; row <= rows2; row++) {
					int iy = y+row;
					int ioffset;
					if (0 <= iy && iy < height)
						ioffset = iy*width;
					else if ( edgeAction == CLAMP_EDGES )
						ioffset = y*width;
					else if ( edgeAction == WRAP_EDGES )
						ioffset = ((iy+height) % height) * width;
					else
						continue;
					int moffset = cols*(row+rows2)+cols2;
					for (int col = -cols2; col <= cols2; col++) {
						float f = matrix[moffset+col];

						if (f != 0) {
							int ix = x+col;
							if (!(0 <= ix && ix < width)) {
								if ( edgeAction == CLAMP_EDGES )
									ix = x;
								else if ( edgeAction == WRAP_EDGES )
									ix = (x+width) % width;
								else
									continue;
							}
							int rgb = inPixels[ioffset+ix];
							a += f * ((rgb >> 24) & 0xff);
							r += f * ((rgb >> 16) & 0xff);
							g += f * ((rgb >> 8) & 0xff);
							b += f * (rgb & 0xff);
						}
					}
				}
				int ia = alpha ? PixelUtils.clamp((int)(a+0.5)) : 0xff;
				int ir = PixelUtils.clamp((int)(r+0.5));
				int ig = PixelUtils.clamp((int)(g+0.5));
				int ib = PixelUtils.clamp((int)(b+0.5));
				outPixels[index++] = (ia << 24) | (ir << 16) | (ig << 8) | ib;
			}
		}
	}
720996
function getShapeOne(x,y,options,modules,mod_matrix){

  var EOL = '\r\n';
  var width = options.width;
  var height = options.height;
  var length = modules.length;
  var style = options.style;
  var xsize = width / (length + 2 * options.padding);
  var ysize = height / (length + 2 * options.padding);
  var px = (x * xsize + options.padding * xsize);
  var py = (y * ysize + options.padding * ysize);

  var orientation = 0;
  if(mod_matrix.right){orientation=90;}
  else if(mod_matrix.bottom){orientation=180;}
  else if(mod_matrix.left){orientation=270;}

  //Returning a 1b
  switch(options.style){
    case 'square':
      return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')"  x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
    case 'circle':
      return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')"  rx="'+xsize+'" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
    case 'sharp-edge':
      return '<path transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')" d="M'+px+' '+py+' L'+(px+xsize)+' '+py+' L'+(px+(xsize/2))+' '+(py+ysize)+' Z" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
  }
}
315240
def cv_compute(self, b, A, B, C, mK, f, m1, m2):
        '''
        

        '''

        A = np.sum([l * a for l, a in zip(self.lam[b], A)
                    if l is not None], axis=0)
        B = np.sum([l * b for l, b in zip(self.lam[b], B)
                    if l is not None], axis=0)
        W = np.linalg.solve(mK + A + C, f)
        if self.transit_model is None:
            model = np.dot(B, W)
        else:
            w_pld = np.concatenate([l * np.dot(self.X(n, m2).T, W)
                                    for n, l in enumerate(self.lam[b])
                                    if l is not None])
            model = np.dot(np.hstack(
                [self.X(n, m1) for n, l in enumerate(self.lam[b])
                 if l is not None]), w_pld)
        model -= np.nanmedian(model)

        return model