Extracts a column from the camera matrix and puts it into the geometric 3-tuple.
540473
public static void extractColumn(DMatrixRMaj P, int col, GeoTuple3D_F64 a) {
		a.x = P.unsafe_get(0,col);
		a.y = P.unsafe_get(1,col);
		a.z = P.unsafe_get(2,col);
	}
1147319
def to_gltf(self, scene):
        
        # geometry is an OrderedDict
        # {geometry key : index}
        mesh_index = {name: i for i, name
                      in enumerate(scene.geometry.keys())}
        # save the output
        gltf = collections.deque([])
        for node in self.nodes:
            # don't include edge for base frame
            if node == self.base_frame:
                continue
            # get the transform and geometry from the graph
            transform, geometry = self.get(
                frame_to=node, frame_from=self.base_frame)

            gltf.append({
                'matrix': transform.T.reshape(-1).tolist(),
                'name': node})
            # assign geometry if it exists
            if geometry is not None:
                gltf[-1]['mesh'] = mesh_index[geometry]

            if node == scene.camera.name:
                gltf[-1]['camera'] = 0

        # we have flattened tree, so all nodes will be child of world
        gltf.appendleft({
            'name': self.base_frame,
            'children': list(range(1, 1 + len(gltf)))
        })
        result = {'nodes': list(gltf)}

        return result
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)
677195
def to_nibabel(image):
    
    if image.dimension != 3:
        raise ValueError('Only 3D images currently supported')

    import nibabel as nib
    array_data = image.numpy()
    affine = np.hstack([image.direction*np.diag(image.spacing),np.array(image.origin).reshape(3,1)])
    affine = np.vstack([affine, np.array([0,0,0,1.])])
    affine[:2,:] *= -1
    new_img = nib.Nifti1Image(array_data, affine)
    return new_img
758857
def point_cloud(df, columns=[0, 1, 2]):
    """"""
    df = df if isinstance(df, pd.DataFrame) else pd.DataFrame(df)
    if not all(c in df.columns for c in columns):
        columns = list(df.columns)[:3]

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')  # noqa
    Axes3D.scatter(*[df[columns[i]] for i in range(3)], zdir='z', s=20, c=None, depthshade=True)
    return ax
938054
void estimateTranslation( DMatrixRMaj R , List<AssociatedPair> points , Vector3D_F64 T )
	{
		final int N = points.size();
		W.reshape(N*2,3);
		y.reshape(N*2,1);
		Wty.reshape(3,1);

		DMatrix3x3 Rtmp = new DMatrix3x3();
		ConvertDMatrixStruct.convert(R,Rtmp);

		int indexY = 0,indexW = 0;
		for (int i = 0; i < N; i++) {
			AssociatedPair p = points.get(i);

			// rotate into camera frame
			double u1 = Rtmp.a11*p.p1.x + Rtmp.a12*p.p1.y;
			double u2 = Rtmp.a21*p.p1.x + Rtmp.a22*p.p1.y;
			double u3 = Rtmp.a31*p.p1.x + Rtmp.a32*p.p1.y;

			W.data[indexW++] = 1;
			W.data[indexW++] = 0;
			W.data[indexW++] = -p.p2.x;
			W.data[indexW++] = 0;
			W.data[indexW++] = 1;
			W.data[indexW++] = -p.p2.y;

			y.data[indexY++] = p.p2.x*u3 - u1;
			y.data[indexY++] = p.p2.y*u3 - u2;
		}

		//======= Compute Pseudo Inverse
		// WW = inv(W^T*W)
		CommonOps_DDRM.multTransA(W,W,WW);
		CommonOps_DDRM.invert(WW);

		// W^T*y
		CommonOps_DDRM.multTransA(W,y,Wty);

		// translation = inv(W^T*W)*W^T*y
		W.reshape(3,1);
		CommonOps_DDRM.mult(WW,Wty,W);

		T.x = W.data[0];
		T.y = W.data[1];
		T.z = W.data[2];
	}
977204
public static void inplaceAdjustCameraMatrix( double sx , double sy , double tx , double ty , DMatrixRMaj P ) {
		// multiply each column one at a time. Because of the zeros everything is decoupled
		for (int col = 0; col < 4; col++) {
			int row0 = col;
			int row1 = 4 + row0;
			int row2 = 4 + row1;
			P.data[row0] = P.data[row0]*sx + tx*P.data[row2];
			P.data[row1] = P.data[row1]*sy + ty*P.data[row2];
		}
	}
1143223
def make_pose(translation, rotation):
    
    pose = np.zeros((4, 4))
    pose[:3, :3] = rotation
    pose[:3, 3] = translation
    pose[3, 3] = 1.0
    return pose
1162252
private void extractTransform( DMatrixRMaj U , DMatrixRMaj V , DMatrixRMaj S ,
								   Se3_F64 se , boolean optionA , boolean optionB )
	{
		DMatrixRMaj R = se.getR();
		Vector3D_F64 T = se.getT();

		// extract rotation
		if( optionA )
			CommonOps_DDRM.mult(U,Rz,temp);
		else
			CommonOps_DDRM.multTransB(U,Rz,temp);
		CommonOps_DDRM.multTransB(temp,V,R);

		// extract screw symmetric translation matrix
		if( optionB )
			CommonOps_DDRM.multTransB(U,Rz,temp);
		else
			CommonOps_DDRM.mult(U,Rz,temp);
		CommonOps_DDRM.mult(temp,S,temp2);
		CommonOps_DDRM.multTransB(temp2,U,temp);

		T.x = temp.get(2,1);
		T.y = temp.get(0,2);
		T.z = temp.get(1,0);
	}
474265
public void processInternal( double[] input, DMatrix leftPoint, DMatrix rightView) {
		int numRows = getNumOfOutputsM();
		int numPointParam = structure.points.length*lengthPoint;
		int numViewParam = numParameters-numPointParam; // view + camera

		((ReshapeMatrix)leftPoint).reshape(numRows,numPointParam);
		((ReshapeMatrix)rightView).reshape(numRows,numViewParam);
		leftPoint.zero();
		rightView.zero();

		int observationIndex = 0;
		// first decode the transformation
		for( int viewIndex = 0; viewIndex < structure.views.length; viewIndex++ ) {
			SceneStructureProjective.View view = structure.views[viewIndex];

			if( !view.known ) {
				int paramIndex = viewParameterIndexes[viewIndex]+indexFirstView;
				for (int i = 0; i < 12; i++) {
					worldToView.data[i] = input[paramIndex++];
				}
			} else {
				worldToView.set(view.worldToView);
			}

			SceneObservations.View obsView = observations.views[viewIndex];

			for (int i = 0; i < obsView.size(); i++) {
				int featureIndex = obsView.point.get(i);
				int columnOfPointInJac = featureIndex*lengthPoint;

				worldPt.x = input[columnOfPointInJac];
				worldPt.y = input[columnOfPointInJac+1];
				worldPt.z = input[columnOfPointInJac+2];
				if( structure.isHomogenous() ) {
					worldPt.w = input[columnOfPointInJac+3];
				}

				PerspectiveOps.renderPixel(worldToView,worldPt,cameraPt);


				if (view.known) {
					if( structure.isHomogenous())
						partialCameraModelH(worldPt.x, worldPt.y, worldPt.z, worldPt.w,
								worldToView, pointGradX, pointGradY, null, null);
					else
						partialCameraModel(worldPt.x, worldPt.y, worldPt.z,
								worldToView, pointGradX, pointGradY, null, null);
				} else {
					if( structure.isHomogenous())
						partialCameraModelH(worldPt.x, worldPt.y, worldPt.z, worldPt.w,
								worldToView, pointGradX, pointGradY, camGradX, camGradY);
					else
						partialCameraModel(worldPt.x, worldPt.y, worldPt.z,
								worldToView, pointGradX, pointGradY, camGradX, camGradY);
				}

				jacRowX = observationIndex*2;
				jacRowY = jacRowX+1;

				//============ Partial of worldPt
				// partial of x' = (1/z)*P*X with respect to X is a 2 by 3|4 matrix
				addToJacobian(leftPoint,columnOfPointInJac,lengthPoint,pointGradX,pointGradY);

				if( !view.known ) {
					// partial of x' = (1/z)*P*X with respect to P is a 2 by 12 matrix
					int col = viewParameterIndexes[viewIndex];
					addToJacobian(rightView,col,12,camGradX,camGradY);
				}

				observationIndex++;
			}
		}

//		left.print();
//		right.print();
//		System.out.println("Asdads");
	}
627690
def crop_coords(img, padding):
    """"""

    coords = np.nonzero(img)
    empty_axis_exists = np.any([len(arr) == 0 for arr in coords])
    if empty_axis_exists:
        end_coords = img.shape
        beg_coords = np.zeros((1, img.ndim)).astype(int).flatten()
    else:
        min_coords = np.array([arr.min() for arr in coords])
        max_coords = np.array([arr.max() for arr in coords])
        beg_coords = np.fmax(0, min_coords - padding)
        end_coords = np.fmin(img.shape, max_coords + padding)

    return beg_coords, end_coords
1021625
def gauss_fltr_opencv(dem, size=3, sigma=1):
    
    import cv2
    dem = malib.checkma(dem)
    dem_cv = cv2.GaussianBlur(dem.filled(np.nan), (size, size), sigma)
    out = np.ma.fix_invalid(dem_cv)
    out.set_fill_value(dem.fill_value)
    return out
400094
def getPixmap(self, matrix=None, colorspace=None, alpha=0, clip=None):
        """"""
        return _fitz.DisplayList_getPixmap(self, matrix, colorspace, alpha, clip)
1265464
def draw3dCoordAxis(self, img=None, thickness=8):
        '''
        
        '''
        if img is None:
            img = self.img
        elif img is False:
            img = np.zeros(shape=self.img.shape, dtype=self.img.dtype)
        else:
            img = imread(img)
        # project 3D points to image plane:
        # self.opts['obj_width_mm'], self.opts['obj_height_mm']
        w, h = self.opts['new_size']
        axis = np.float32([[0.5 * w, 0.5 * h, 0],
                           [w, 0.5 * h, 0],
                           [0.5 * w, h, 0],
                           [0.5 * w, 0.5 * h, -0.5 * w]])
        t, r = self.pose()
        imgpts = cv2.projectPoints(axis, r, t,
                                   self.opts['cameraMatrix'],
                                   self.opts['distCoeffs'])[0]

        mx = int(img.max())
        origin = tuple(imgpts[0].ravel())
        cv2.line(img, origin, tuple(imgpts[1].ravel()), (0, 0, mx), thickness)
        cv2.line(img, origin, tuple(imgpts[2].ravel()), (0, mx, 0), thickness)
        cv2.line(
            img, origin, tuple(imgpts[3].ravel()), (mx, 0, 0), thickness * 2)
        return img
185707
private boolean extractCalibration(DMatrixRMaj x , CameraPinhole calibration) {
		double s = x.data[5];

		double cx = calibration.cx = x.data[2]/s;
		double cy = calibration.cy = x.data[4]/s;
		double fy = calibration.fy = Math.sqrt(x.data[3]/s-cy*cy);
		double sk = calibration.skew = (x.data[1]/s-cx*cy)/fy;
		calibration.fx = Math.sqrt(x.data[0]/s - sk*sk - cx*cx);

		if( calibration.fx < 0 || calibration.fy < 0 )
			return false;
		if(UtilEjml.isUncountable(fy) || UtilEjml.isUncountable(calibration.fx))
			return false;
		if(UtilEjml.isUncountable(sk))
			return false;
		return true;
	}
1000743
def imag(self):
        """"""
        return matrix(self.tt.imag(), n=self.n, m=self.m)
598054
def processFrame(frame):
    """"""
    # The pixels are grey-scale values from 0-255 - white = 255, black = 0
    # We want to turn the image into two values, one for the left "sensor" and one for the right.
    # There are many possible ways to do this. The very simplest way would be
    # to examine the values of two pixels - one in the centre of the left half of the image,
    # and one in the centre of the right half. What are the obvious problems with this?

    # NB: The pixels are stored in a flat (1 dimensional) array, so to calculate the index of the pixels
    # at (x,y), we do:
    # index = x + (y * width)

    width = frame.width
    height = frame.height
    pixels = frame.pixels

    USE_SIMPLE_APPROACH = False  # Change this to False to use more sophisticated approach.

    if USE_SIMPLE_APPROACH:
        # Simplest approach.
        left_centre_x = int(width / 4)      # Centre of left half
        right_centre_x = int(3 * width / 4) # Centre of right half
        centre_y = int(height / 2)          # Middle row
        left_pixel_index = left_centre_x + (centre_y * width)
        right_pixel_index = right_centre_x + (centre_y * width)
        left_sensor = float(pixels[left_pixel_index]) / 255.0
        right_sensor = float(pixels[right_pixel_index]) / 255.0
    else:
        # Obviously, the simple approach misses a lot of data, and is very susceptible to noise.
        # A better approach would be to consider more pixels.
        # You could take the average of all the pixels - it's slower but better.
        # Or you could use the median value, which is less noisy than the mean.
        # Here we calculate both, and estimate the median using histograms:
        left_total = 0
        right_total = 0
        left_hist = [0 for i in range(256)]
        right_hist = [0 for i in range(256)]
        # Create a histogram for each half of the image:
        for y in range(height):
            for x in range(int(width/2)):
                i = pixels[x + y*width]
                left_hist[i] += 1
                left_total += float(i)/255.0
            for x in range(int(width/2), width):
                i = pixels[x + y*width]
                right_hist[i] += 1
                right_total += float(i)/255.0
        # Calculate the mean values:
        left_mean, right_mean = left_total / (width*height/2), right_total / (width*height/2)
        # Now use the histogram to estimate the median value
        left_total, right_total = 0, 0
        pixels_per_half = width * height / 2
        cut_off_value = pixels_per_half / 2
        left_cut_off_point, right_cut_off_point = 0, 0
        while (left_total < cut_off_value):
            left_total += left_hist[left_cut_off_point]
            left_cut_off_point += 1
        while(right_total < cut_off_value):
            right_total += right_hist[right_cut_off_point]
            right_cut_off_point += 1
        left_median, right_median = left_cut_off_point / 255.0, right_cut_off_point / 255.0
        
        # Use the median values:
        left_sensor, right_sensor = left_median, right_median
        # Or uncomment this line to use the mean values:
        # left_sensor, right_sensor = left_mean, right_mean
    
    # In our gloomy arena, we never get particularly bright, so the sensor values tend to be low.
    # To get more action from our vehicle, we can scale up (keeping 1.0 as the max).
    # What values work well for GAIN? What happens if it's too high or too low?
    GAIN = 1.8
    left_sensor = min(1, left_sensor * GAIN)
    right_sensor = min(1, right_sensor * GAIN)
    # Done - return the values:
    return left_sensor, right_sensor