idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
27,700
public static Kernel2D_F64 gaussianWidth ( double sigma , int width ) { if ( sigma <= 0 ) sigma = sigmaForRadius ( width / 2 , 0 ) ; else if ( width <= 0 ) throw new IllegalArgumentException ( "Must specify the width since it doesn't know if it should be even or odd" ) ; if ( width % 2 == 0 ) { int r = width / 2 - 1 ; Kernel2D_F64 ret = new Kernel2D_F64 ( width ) ; double sum = 0 ; for ( int y = 0 ; y < width ; y ++ ) { double dy = y <= r ? Math . abs ( y - r ) + 0.5 : Math . abs ( y - r - 1 ) + 0.5 ; for ( int x = 0 ; x < width ; x ++ ) { double dx = x <= r ? Math . abs ( x - r ) + 0.5 : Math . abs ( x - r - 1 ) + 0.5 ; double d = Math . sqrt ( dx * dx + dy * dy ) ; double val = UtilGaussian . computePDF ( 0 , sigma , d ) ; ret . set ( x , y , val ) ; sum += val ; } } for ( int i = 0 ; i < ret . data . length ; i ++ ) { ret . data [ i ] /= sum ; } return ret ; } else { return gaussian2D_F64 ( sigma , width / 2 , true , true ) ; } }
Create a gaussian kernel based on its width . Supports kernels of even or odd widths .
27,701
public boolean process ( List < AssociatedTriple > associated , int width , int height ) { init ( width , height ) ; if ( ! robustFitTrifocal ( associated ) ) return false ; if ( ! estimateProjectiveScene ( ) ) return false ; if ( ! projectiveToMetric ( ) ) return false ; setupMetricBundleAdjustment ( inliers ) ; bundleAdjustment = FactoryMultiView . bundleSparseMetric ( configSBA ) ; findBestValidSolution ( bundleAdjustment ) ; pruneOutliers ( bundleAdjustment ) ; return true ; }
Determines the metric scene . The principle point is assumed to be zero in the passed in pixel coordinates . Typically this is done by subtracting the image center from each pixel coordinate for each view .
27,702
private boolean robustFitTrifocal ( List < AssociatedTriple > associated ) { ransac . process ( associated ) ; inliers = ransac . getMatchSet ( ) ; TrifocalTensor model = ransac . getModelParameters ( ) ; if ( verbose != null ) verbose . println ( "Remaining after RANSAC " + inliers . size ( ) + " / " + associated . size ( ) ) ; if ( ! trifocalEstimator . process ( inliers , model ) ) { if ( verbose != null ) { verbose . println ( "Trifocal estimator failed" ) ; } return false ; } return true ; }
Fits a trifocal tensor to the list of matches features using a robust method
27,703
private void pruneOutliers ( BundleAdjustment < SceneStructureMetric > bundleAdjustment ) { if ( pruneFraction == 1.0 ) return ; PruneStructureFromSceneMetric pruner = new PruneStructureFromSceneMetric ( structure , observations ) ; pruner . pruneObservationsByErrorRank ( pruneFraction ) ; pruner . pruneViews ( 10 ) ; pruner . prunePoints ( 1 ) ; bundleAdjustment . setParameters ( structure , observations ) ; bundleAdjustment . optimize ( structure ) ; if ( verbose != null ) { verbose . println ( "\nCamera" ) ; for ( int i = 0 ; i < structure . cameras . length ; i ++ ) { verbose . println ( structure . cameras [ i ] . getModel ( ) . toString ( ) ) ; } verbose . println ( "\n\nworldToView" ) ; for ( int i = 0 ; i < structure . views . length ; i ++ ) { verbose . println ( structure . views [ i ] . worldToView . toString ( ) ) ; } verbose . println ( "Fit Score: " + bundleAdjustment . getFitScore ( ) ) ; } }
Prunes the features with the largest reprojection error
27,704
private boolean estimateProjectiveScene ( ) { List < AssociatedTriple > inliers = ransac . getMatchSet ( ) ; TrifocalTensor model = ransac . getModelParameters ( ) ; MultiViewOps . extractCameraMatrices ( model , P2 , P3 ) ; RefineThreeViewProjective refineP23 = FactoryMultiView . threeViewRefine ( null ) ; if ( ! refineP23 . process ( inliers , P2 , P3 , P2 , P3 ) ) { if ( verbose != null ) { verbose . println ( "Can't refine P2 and P3!" ) ; } return false ; } return true ; }
Estimate the projective scene from the trifocal tensor
27,705
private void setupMetricBundleAdjustment ( List < AssociatedTriple > inliers ) { structure = new SceneStructureMetric ( false ) ; observations = new SceneObservations ( 3 ) ; structure . initialize ( 3 , 3 , inliers . size ( ) ) ; for ( int i = 0 ; i < listPinhole . size ( ) ; i ++ ) { CameraPinhole cp = listPinhole . get ( i ) ; BundlePinholeSimplified bp = new BundlePinholeSimplified ( ) ; bp . f = cp . fx ; structure . setCamera ( i , false , bp ) ; structure . setView ( i , i == 0 , worldToView . get ( i ) ) ; structure . connectViewToCamera ( i , i ) ; } for ( int i = 0 ; i < inliers . size ( ) ; i ++ ) { AssociatedTriple t = inliers . get ( i ) ; observations . getView ( 0 ) . add ( i , ( float ) t . p1 . x , ( float ) t . p1 . y ) ; observations . getView ( 1 ) . add ( i , ( float ) t . p2 . x , ( float ) t . p2 . y ) ; observations . getView ( 2 ) . add ( i , ( float ) t . p3 . x , ( float ) t . p3 . y ) ; structure . connectPointToView ( i , 0 ) ; structure . connectPointToView ( i , 1 ) ; structure . connectPointToView ( i , 2 ) ; } triangulatePoints ( structure , observations ) ; }
Using the initial metric reconstruction provide the initial configurations for bundle adjustment
27,706
private boolean checkBehindCamera ( SceneStructureMetric structure ) { int totalBehind = 0 ; Point3D_F64 X = new Point3D_F64 ( ) ; for ( int i = 0 ; i < structure . points . length ; i ++ ) { structure . points [ i ] . get ( X ) ; if ( X . z < 0 ) totalBehind ++ ; } if ( verbose != null ) { verbose . println ( "points behind " + totalBehind + " / " + structure . points . length ) ; } return totalBehind > structure . points . length / 2 ; }
Checks to see if a solution was converged to where the points are behind the camera . This is pysically impossible
27,707
private static void flipAround ( SceneStructureMetric structure , SceneObservations observations ) { for ( int i = 1 ; i < structure . views . length ; i ++ ) { Se3_F64 w2v = structure . views [ i ] . worldToView ; w2v . set ( w2v . invert ( null ) ) ; } triangulatePoints ( structure , observations ) ; }
Flip the camera pose around . This seems to help it converge to a valid solution if it got it backwards even if it s not technically something which can be inverted this way
27,708
public void setImage ( II grayII , Planar < II > colorII ) { InputSanityCheck . checkSameShape ( grayII , colorII ) ; if ( colorII . getNumBands ( ) != numBands ) throw new IllegalArgumentException ( "Expected planar images to have " + numBands + " not " + colorII . getNumBands ( ) ) ; this . grayII = grayII ; this . colorII = colorII ; }
Specifies input image shapes .
27,709
public static void hsvToRgb ( double h , double s , double v , double [ ] rgb ) { if ( s == 0 ) { rgb [ 0 ] = v ; rgb [ 1 ] = v ; rgb [ 2 ] = v ; return ; } h /= d60_F64 ; int h_int = ( int ) h ; double remainder = h - h_int ; double p = v * ( 1 - s ) ; double q = v * ( 1 - s * remainder ) ; double t = v * ( 1 - s * ( 1 - remainder ) ) ; if ( h_int < 1 ) { rgb [ 0 ] = v ; rgb [ 1 ] = t ; rgb [ 2 ] = p ; } else if ( h_int < 2 ) { rgb [ 0 ] = q ; rgb [ 1 ] = v ; rgb [ 2 ] = p ; } else if ( h_int < 3 ) { rgb [ 0 ] = p ; rgb [ 1 ] = v ; rgb [ 2 ] = t ; } else if ( h_int < 4 ) { rgb [ 0 ] = p ; rgb [ 1 ] = q ; rgb [ 2 ] = v ; } else if ( h_int < 5 ) { rgb [ 0 ] = t ; rgb [ 1 ] = p ; rgb [ 2 ] = v ; } else { rgb [ 0 ] = v ; rgb [ 1 ] = p ; rgb [ 2 ] = q ; } }
Convert HSV color into RGB color
27,710
public void configure ( CameraPinholeBrown intrinsic , Se3_F64 planeToCamera , double centerX , double centerY , double cellSize , int overheadWidth , int overheadHeight ) { this . overheadWidth = overheadWidth ; this . overheadHeight = overheadHeight ; Point2Transform2_F64 normToPixel = LensDistortionFactory . narrow ( intrinsic ) . distort_F64 ( false , true ) ; int overheadPixels = overheadHeight * overheadWidth ; if ( mapPixels == null || mapPixels . length < overheadPixels ) { mapPixels = new Point2D_F32 [ overheadPixels ] ; } points . reset ( ) ; Point2D_F64 pixel = new Point2D_F64 ( ) ; Point3D_F64 pt_plane = new Point3D_F64 ( ) ; Point3D_F64 pt_cam = new Point3D_F64 ( ) ; int indexOut = 0 ; for ( int i = 0 ; i < overheadHeight ; i ++ ) { pt_plane . x = - ( i * cellSize - centerY ) ; for ( int j = 0 ; j < overheadWidth ; j ++ , indexOut ++ ) { pt_plane . z = j * cellSize - centerX ; SePointOps_F64 . transform ( planeToCamera , pt_plane , pt_cam ) ; if ( pt_cam . z > 0 ) { normToPixel . compute ( pt_cam . x / pt_cam . z , pt_cam . y / pt_cam . z , pixel ) ; float x = ( float ) pixel . x ; float y = ( float ) pixel . y ; if ( BoofMiscOps . checkInside ( intrinsic . width , intrinsic . height , x , y ) ) { Point2D_F32 p = points . grow ( ) ; p . set ( x , y ) ; mapPixels [ indexOut ] = p ; } else { mapPixels [ indexOut ] = null ; } } } } }
Specifies camera configurations .
27,711
public boolean detect ( T input ) { detections . reset ( ) ; detector . process ( input ) ; FastQueue < FoundFiducial > found = detector . getFound ( ) ; for ( int i = 0 ; i < found . size ( ) ; i ++ ) { FoundFiducial fid = found . get ( i ) ; int gridIndex = isExpected ( fid . id ) ; if ( gridIndex >= 0 ) { Detection d = lookupDetection ( fid . id , gridIndex ) ; d . location . set ( fid . distortedPixels ) ; d . numDetected ++ ; } } for ( int i = detections . size - 1 ; i >= 0 ; i -- ) { if ( detections . get ( i ) . numDetected != 1 ) { detections . remove ( i ) ; } } return detections . size > 0 ; }
Searches for the fiducial inside the image . If at least a partial match is found true is returned .
27,712
private int isExpected ( long found ) { int bestHamming = 2 ; int bestNumber = - 1 ; for ( int i = 0 ; i < numbers . length ; i ++ ) { int hamming = DescriptorDistance . hamming ( ( int ) found ^ ( int ) numbers [ i ] ) ; if ( hamming < bestHamming ) { bestHamming = hamming ; bestNumber = i ; } } return bestNumber ; }
Checks to see if the provided ID number is expected or not
27,713
private Detection lookupDetection ( long found , int gridIndex ) { for ( int i = 0 ; i < detections . size ( ) ; i ++ ) { Detection d = detections . get ( i ) ; if ( d . id == found ) { return d ; } } Detection d = detections . grow ( ) ; d . reset ( ) ; d . id = found ; d . gridIndex = gridIndex ; return d ; }
Looks up a detection given the fiducial ID number . If not seen before the gridIndex is saved and a new instance returned .
27,714
public void process ( GrayU8 binary , GrayS32 labeled ) { labeled . reshape ( binary . width , binary . height ) ; if ( border . width != binary . width + 2 || border . height != binary . height + 2 ) { border . reshape ( binary . width + 2 , binary . height + 2 ) ; ImageMiscOps . fillBorder ( border , 0 , 1 ) ; } border . subimage ( 1 , 1 , border . width - 1 , border . height - 1 , null ) . setTo ( binary ) ; ImageMiscOps . fill ( labeled , 0 ) ; binary = border ; packedPoints . reset ( ) ; contours . reset ( ) ; tracer . setInputs ( binary , labeled , packedPoints ) ; int endY = binary . height - 1 , enxX = binary . width - 1 ; for ( y = 1 ; y < endY ; y ++ ) { indexIn = binary . startIndex + y * binary . stride + 1 ; indexOut = labeled . startIndex + ( y - 1 ) * labeled . stride ; x = 1 ; int delta = scanForOne ( binary . data , indexIn , indexIn + enxX - x ) - indexIn ; x += delta ; indexIn += delta ; indexOut += delta ; while ( x < enxX ) { int label = labeled . data [ indexOut ] ; boolean handled = false ; if ( label == 0 && binary . data [ indexIn - binary . stride ] != 1 ) { handleStep1 ( ) ; handled = true ; label = contours . size ; } if ( binary . data [ indexIn + binary . stride ] == 0 ) { handleStep2 ( labeled , label ) ; handled = true ; } if ( ! handled ) { if ( labeled . data [ indexOut ] == 0 ) labeled . data [ indexOut ] = labeled . data [ indexOut - 1 ] ; } delta = scanForOne ( binary . data , indexIn + 1 , indexIn + enxX - x ) - indexIn ; x += delta ; indexIn += delta ; indexOut += delta ; } } }
Processes the binary image to find the contour of and label blobs .
27,715
private int scanForOne ( byte [ ] data , int index , int end ) { while ( index < end && data [ index ] != 1 ) { index ++ ; } return index ; }
Faster when there s a specialized function which searches for one pixels
27,716
public static < T extends ImageGray < T > > QrCodePreciseDetector < T > qrcode ( ConfigQrCode config , Class < T > imageType ) { if ( config == null ) config = new ConfigQrCode ( ) ; config . checkValidity ( ) ; InputToBinary < T > inputToBinary = FactoryThresholdBinary . threshold ( config . threshold , imageType ) ; DetectPolygonBinaryGrayRefine < T > squareDetector = FactoryShapeDetector . polygon ( config . polygon , imageType ) ; QrCodePositionPatternDetector < T > detectPositionPatterns = new QrCodePositionPatternDetector < > ( squareDetector , config . versionMaximum ) ; return new QrCodePreciseDetector < > ( inputToBinary , detectPositionPatterns , config . forceEncoding , false , imageType ) ; }
Returns a QR Code detector
27,717
public void initialize ( T image , int x0 , int y0 , int x1 , int y1 ) { if ( imagePyramid == null || imagePyramid . getInputWidth ( ) != image . width || imagePyramid . getInputHeight ( ) != image . height ) { int minSize = ( config . trackerFeatureRadius * 2 + 1 ) * 5 ; int scales [ ] = selectPyramidScale ( image . width , image . height , minSize ) ; imagePyramid = FactoryPyramid . discreteGaussian ( scales , - 1 , 1 , true , image . getImageType ( ) ) ; } imagePyramid . process ( image ) ; reacquiring = false ; targetRegion . set ( x0 , y0 , x1 , y1 ) ; createCascadeRegion ( image . width , image . height ) ; template . reset ( ) ; fern . reset ( ) ; tracking . initialize ( imagePyramid ) ; variance . setImage ( image ) ; template . setImage ( image ) ; fern . setImage ( image ) ; adjustRegion . init ( image . width , image . height ) ; learning . initialLearning ( targetRegion , cascadeRegions ) ; strongMatch = true ; previousTrackArea = targetRegion . area ( ) ; }
Starts tracking the rectangular region .
27,718
private void createCascadeRegion ( int imageWidth , int imageHeight ) { cascadeRegions . reset ( ) ; int rectWidth = ( int ) ( targetRegion . getWidth ( ) + 0.5 ) ; int rectHeight = ( int ) ( targetRegion . getHeight ( ) + 0.5 ) ; for ( int scaleInt = - config . scaleSpread ; scaleInt <= config . scaleSpread ; scaleInt ++ ) { double scale = Math . pow ( 1.2 , scaleInt ) ; int actualWidth = ( int ) ( rectWidth * scale ) ; int actualHeight = ( int ) ( rectHeight * scale ) ; if ( actualWidth < config . detectMinimumSide || actualHeight < config . detectMinimumSide ) continue ; if ( actualWidth >= imageWidth || actualHeight >= imageHeight ) continue ; int stepWidth = ( int ) ( rectWidth * scale * 0.1 ) ; int stepHeight = ( int ) ( rectHeight * scale * 0.1 ) ; if ( stepWidth < 1 ) stepWidth = 1 ; if ( stepHeight < 1 ) stepHeight = 1 ; int maxX = imageWidth - actualWidth ; int maxY = imageHeight - actualHeight ; for ( int y0 = 1 ; y0 < maxY ; y0 += stepHeight ) { for ( int x0 = 1 ; x0 < maxX ; x0 += stepWidth ) { ImageRectangle r = cascadeRegions . grow ( ) ; r . x0 = x0 ; r . y0 = y0 ; r . x1 = x0 + actualWidth ; r . y1 = y0 + actualHeight ; } } } }
Creates a list containing all the regions which need to be tested
27,719
public boolean track ( T image ) { boolean success = true ; valid = false ; imagePyramid . process ( image ) ; template . setImage ( image ) ; variance . setImage ( image ) ; fern . setImage ( image ) ; if ( reacquiring ) { detection . detectionCascade ( cascadeRegions ) ; if ( detection . isSuccess ( ) && ! detection . isAmbiguous ( ) ) { TldRegion region = detection . getBest ( ) ; reacquiring = false ; valid = false ; ImageRectangle r = region . rect ; targetRegion . set ( r . x0 , r . y0 , r . x1 , r . y1 ) ; tracking . initialize ( imagePyramid ) ; checkNewTrackStrong ( region . confidence ) ; } else { success = false ; } } else { detection . detectionCascade ( cascadeRegions ) ; trackerRegion . set ( targetRegion ) ; boolean trackingWorked = tracking . process ( imagePyramid , trackerRegion ) ; trackingWorked &= adjustRegion . process ( tracking . getPairs ( ) , trackerRegion ) ; TldHelperFunctions . convertRegion ( trackerRegion , trackerRegion_I32 ) ; if ( hypothesisFusion ( trackingWorked , detection . isSuccess ( ) ) ) { if ( valid && performLearning ) { learning . updateLearning ( targetRegion ) ; } } else { reacquiring = true ; success = false ; } } if ( strongMatch ) { previousTrackArea = targetRegion . area ( ) ; } return success ; }
Updates track region .
27,720
protected boolean hypothesisFusion ( boolean trackingWorked , boolean detectionWorked ) { valid = false ; boolean uniqueDetection = detectionWorked && ! detection . isAmbiguous ( ) ; TldRegion detectedRegion = detection . getBest ( ) ; double confidenceTarget ; if ( trackingWorked ) { double scoreTrack = template . computeConfidence ( trackerRegion_I32 ) ; double scoreDetected = 0 ; if ( uniqueDetection ) { scoreDetected = detectedRegion . confidence ; } double adjustment = strongMatch ? 0.07 : 0.02 ; if ( uniqueDetection && scoreDetected > scoreTrack + adjustment ) { TldHelperFunctions . convertRegion ( detectedRegion . rect , targetRegion ) ; confidenceTarget = detectedRegion . confidence ; checkNewTrackStrong ( scoreDetected ) ; } else { targetRegion . set ( trackerRegion ) ; confidenceTarget = scoreTrack ; strongMatch |= confidenceTarget > config . confidenceThresholdStrong ; if ( strongMatch && confidenceTarget >= config . confidenceThresholdLower ) { valid = true ; } } } else if ( uniqueDetection ) { detectedRegion = detection . getBest ( ) ; TldHelperFunctions . convertRegion ( detectedRegion . rect , targetRegion ) ; confidenceTarget = detectedRegion . confidence ; strongMatch = confidenceTarget > config . confidenceThresholdStrong ; } else { return false ; } return confidenceTarget >= config . confidenceAccept ; }
Combines hypotheses from tracking and detection .
27,721
public static int [ ] selectPyramidScale ( int imageWidth , int imageHeight , int minSize ) { int w = Math . max ( imageWidth , imageHeight ) ; int maxScale = w / minSize ; int n = 1 ; int scale = 1 ; while ( scale * 2 < maxScale ) { n ++ ; scale *= 2 ; } int ret [ ] = new int [ n ] ; scale = 1 ; for ( int i = 0 ; i < n ; i ++ ) { ret [ i ] = scale ; scale *= 2 ; } return ret ; }
Selects the scale for the image pyramid based on image size and feature size
27,722
public void imageToGrid ( Point2D_F64 pixel , Point2D_F64 grid ) { transformGrid . imageToGrid ( pixel . x , pixel . y , grid ) ; }
Converts a pixel coordinate into a grid coordinate .
27,723
public int readBit ( int row , int col ) { float center = 0.5f ; transformGrid . gridToImage ( row + center - 0.2f , col + center , pixel ) ; float pixel01 = interpolate . get ( pixel . x , pixel . y ) ; transformGrid . gridToImage ( row + center + 0.2f , col + center , pixel ) ; float pixel21 = interpolate . get ( pixel . x , pixel . y ) ; transformGrid . gridToImage ( row + center , col + center - 0.2f , pixel ) ; float pixel10 = interpolate . get ( pixel . x , pixel . y ) ; transformGrid . gridToImage ( row + center , col + center + 0.2f , pixel ) ; float pixel12 = interpolate . get ( pixel . x , pixel . y ) ; transformGrid . gridToImage ( row + center , col + center , pixel ) ; float pixel00 = interpolate . get ( pixel . x , pixel . y ) ; int total = 0 ; if ( pixel01 < threshold ) total ++ ; if ( pixel21 < threshold ) total ++ ; if ( pixel10 < threshold ) total ++ ; if ( pixel12 < threshold ) total ++ ; if ( pixel00 < threshold ) total ++ ; if ( total >= 3 ) return 1 ; else return 0 ; }
Reads a bit from the qr code s data matrix while adjusting for location distortions using known feature locations .
27,724
public static Webcam openDefault ( int desiredWidth , int desiredHeight ) { Webcam webcam = Webcam . getDefault ( ) ; adjustResolution ( webcam , desiredWidth , desiredHeight ) ; webcam . open ( ) ; return webcam ; }
Opens the default camera while adjusting its resolution
27,725
public void process ( List < EllipseInfo > ellipses , List < List < Node > > output ) { init ( ellipses ) ; connect ( ellipses ) ; output . clear ( ) ; for ( int i = 0 ; i < clusters . size ( ) ; i ++ ) { List < Node > c = clusters . get ( i ) ; removeSingleConnections ( c ) ; if ( c . size ( ) >= minimumClusterSize ) { output . add ( c ) ; } } }
Processes the ellipses and creates clusters .
27,726
static void removeSingleConnections ( List < Node > cluster ) { List < Node > open = new ArrayList < > ( ) ; List < Node > future = new ArrayList < > ( ) ; open . addAll ( cluster ) ; while ( ! open . isEmpty ( ) ) { for ( int i = open . size ( ) - 1 ; i >= 0 ; i -- ) { Node n = open . get ( i ) ; if ( n . connections . size == 1 ) { int index = findNode ( n . which , cluster ) ; cluster . remove ( index ) ; int parent = findNode ( n . connections . get ( 0 ) , cluster ) ; n . connections . reset ( ) ; if ( parent == - 1 ) throw new RuntimeException ( "BUG!" ) ; Node p = cluster . get ( parent ) ; int edge = p . connections . indexOf ( n . which ) ; if ( edge == - 1 ) throw new RuntimeException ( "BUG!" ) ; p . connections . remove ( edge ) ; if ( p . connections . size == 1 ) { future . add ( p ) ; } } } open . clear ( ) ; List < Node > tmp = open ; open = future ; future = tmp ; } }
Removes stray connections that are highly likely to be noise . If a node has one connection it then removed . Then it s only connection is considered for removal .
27,727
void init ( List < EllipseInfo > ellipses ) { nodes . resize ( ellipses . size ( ) ) ; clusters . reset ( ) ; for ( int i = 0 ; i < ellipses . size ( ) ; i ++ ) { Node n = nodes . get ( i ) ; n . connections . reset ( ) ; n . which = i ; n . cluster = - 1 ; } nn . setPoints ( ellipses , true ) ; }
Recycles and initializes all internal data structures
27,728
void joinClusters ( int mouth , int food ) { List < Node > listMouth = clusters . get ( mouth ) ; List < Node > listFood = clusters . get ( food ) ; for ( int i = 0 ; i < listFood . size ( ) ; i ++ ) { listMouth . add ( listFood . get ( i ) ) ; listFood . get ( i ) . cluster = mouth ; } listFood . clear ( ) ; }
Moves all the members of food into mouth
27,729
public void set ( int x , int y , int value ) { if ( ! isInBounds ( x , y ) ) throw new ImageAccessException ( "Requested pixel is out of bounds: " + x + " " + y ) ; data [ getIndex ( x , y ) ] = ( byte ) value ; }
Sets the value of the specified pixel .
27,730
public static void process ( GrayU8 orig , GrayS16 derivX , GrayS16 derivY ) { final byte [ ] data = orig . data ; final short [ ] imgX = derivX . data ; final short [ ] imgY = derivY . data ; final int width = orig . getWidth ( ) ; final int height = orig . getHeight ( ) - 1 ; for ( int y = 1 ; y < height ; y ++ ) { int endX = width * y + width - 1 ; for ( int index = width * y + 1 ; index < endX ; index ++ ) { int v = ( data [ index + width + 1 ] & 0xFF ) - ( data [ index - width - 1 ] & 0xFF ) ; int w = ( data [ index + width - 1 ] & 0xFF ) - ( data [ index - width + 1 ] & 0xFF ) ; imgY [ index ] = ( short ) ( ( ( data [ index + width ] & 0xFF ) - ( data [ index - width ] & 0xFF ) ) * 2 + v + w ) ; imgX [ index ] = ( short ) ( ( ( data [ index + 1 ] & 0xFF ) - ( data [ index - 1 ] & 0xFF ) ) * 2 + v - w ) ; } } }
Computes derivative of GrayU8 . None of the images can be sub - images .
27,731
public static void process_sub ( GrayU8 orig , GrayS16 derivX , GrayS16 derivY ) { final byte [ ] data = orig . data ; final short [ ] imgX = derivX . data ; final short [ ] imgY = derivY . data ; final int width = orig . getWidth ( ) ; final int height = orig . getHeight ( ) - 1 ; final int strideSrc = orig . getStride ( ) ; for ( int y = 1 ; y < height ; y ++ ) { int indexSrc = orig . startIndex + orig . stride * y + 1 ; final int endX = indexSrc + width - 2 ; int indexX = derivX . startIndex + derivX . stride * y + 1 ; int indexY = derivY . startIndex + derivY . stride * y + 1 ; for ( ; indexSrc < endX ; indexSrc ++ ) { int v = ( data [ indexSrc + strideSrc + 1 ] & 0xFF ) - ( data [ indexSrc - strideSrc - 1 ] & 0xFF ) ; int w = ( data [ indexSrc + strideSrc - 1 ] & 0xFF ) - ( data [ indexSrc - strideSrc + 1 ] & 0xFF ) ; imgY [ indexY ++ ] = ( short ) ( ( ( data [ indexSrc + strideSrc ] & 0xFF ) - ( data [ indexSrc - strideSrc ] & 0xFF ) ) * 2 + v + w ) ; imgX [ indexX ++ ] = ( short ) ( ( ( data [ indexSrc + 1 ] & 0xFF ) - ( data [ indexSrc - 1 ] & 0xFF ) ) * 2 + v - w ) ; } } }
Computes derivative of GrayU8 . Inputs can be sub - images .
27,732
public void setScaleFactors ( double ... scaleFactors ) { if ( scale != null && scale . length == scaleFactors . length ) { boolean theSame = true ; for ( int i = 0 ; i < scale . length ; i ++ ) { if ( scale [ i ] != scaleFactors [ i ] ) { theSame = false ; break ; } } if ( theSame ) return ; } bottomWidth = bottomHeight = 0 ; this . scale = scaleFactors . clone ( ) ; checkScales ( ) ; }
Specifies the pyramid s structure .
27,733
public static double variance ( int [ ] histogram , double mean , int N ) { return variance ( histogram , mean , count ( histogram , N ) , N ) ; }
Computes the variance of pixel intensity values for a GrayU8 image represented by the given histogram .
27,734
public static double variance ( int [ ] histogram , double mean , int counts , int N ) { double sum = 0.0 ; for ( int i = 0 ; i < N ; i ++ ) { double d = i - mean ; sum += ( d * d ) * histogram [ i ] ; } return sum / counts ; }
Computes the variance of elements in the histogram
27,735
public static int count ( int [ ] histogram , int N ) { int counts = 0 ; for ( int i = 0 ; i < N ; i ++ ) { counts += histogram [ i ] ; } return counts ; }
Counts sum of all the bins inside the histogram
27,736
public static void maxf ( Planar < GrayF32 > inX , Planar < GrayF32 > inY , GrayF32 outX , GrayF32 outY ) { InputSanityCheck . checkSameShape ( inX , inY ) ; InputSanityCheck . reshapeOneIn ( inX , outX , outY ) ; InputSanityCheck . checkIndexing ( inX , inY ) ; InputSanityCheck . checkIndexing ( outX , outY ) ; for ( int y = 0 ; y < inX . height ; y ++ ) { int indexIn = inX . startIndex + inX . stride * y ; int indexOut = outX . startIndex + outX . stride * y ; for ( int x = 0 ; x < inX . width ; x ++ , indexIn ++ , indexOut ++ ) { float maxValueX = inX . bands [ 0 ] . data [ indexIn ] ; float maxValueY = inY . bands [ 0 ] . data [ indexIn ] ; float maxNorm = maxValueX * maxValueX + maxValueY * maxValueY ; for ( int band = 1 ; band < inX . bands . length ; band ++ ) { float valueX = inX . bands [ band ] . data [ indexIn ] ; float valueY = inY . bands [ band ] . data [ indexIn ] ; float n = valueX * valueX + valueY * valueY ; if ( n > maxNorm ) { maxNorm = n ; maxValueX = valueX ; maxValueY = valueY ; } } outX . data [ indexOut ] = maxValueX ; outY . data [ indexOut ] = maxValueY ; } } }
Reduces the number of bands by selecting the band with the largest Frobenius norm and using its gradient to be the output gradient on a pixel - by - pixel basis
27,737
public static void histogram ( ) { BufferedImage buffered = UtilImageIO . loadImage ( UtilIO . pathExample ( imagePath ) ) ; GrayU8 gray = ConvertBufferedImage . convertFrom ( buffered , ( GrayU8 ) null ) ; GrayU8 adjusted = gray . createSameShape ( ) ; int histogram [ ] = new int [ 256 ] ; int transform [ ] = new int [ 256 ] ; ListDisplayPanel panel = new ListDisplayPanel ( ) ; ImageStatistics . histogram ( gray , 0 , histogram ) ; EnhanceImageOps . equalize ( histogram , transform ) ; EnhanceImageOps . applyTransform ( gray , transform , adjusted ) ; panel . addImage ( ConvertBufferedImage . convertTo ( adjusted , null ) , "Global" ) ; EnhanceImageOps . equalizeLocal ( gray , 50 , adjusted , 256 , null ) ; panel . addImage ( ConvertBufferedImage . convertTo ( adjusted , null ) , "Local" ) ; panel . addImage ( ConvertBufferedImage . convertTo ( gray , null ) , "Original" ) ; panel . setPreferredSize ( new Dimension ( gray . width , gray . height ) ) ; mainPanel . addItem ( panel , "Histogram" ) ; }
Histogram adjustment algorithms aim to spread out pixel intensity values uniformly across the allowed range . This if an image is dark it will have greater contrast and be brighter .
27,738
public static void sharpen ( ) { BufferedImage buffered = UtilImageIO . loadImage ( UtilIO . pathExample ( imagePath ) ) ; GrayU8 gray = ConvertBufferedImage . convertFrom ( buffered , ( GrayU8 ) null ) ; GrayU8 adjusted = gray . createSameShape ( ) ; ListDisplayPanel panel = new ListDisplayPanel ( ) ; EnhanceImageOps . sharpen4 ( gray , adjusted ) ; panel . addImage ( ConvertBufferedImage . convertTo ( adjusted , null ) , "Sharpen-4" ) ; EnhanceImageOps . sharpen8 ( gray , adjusted ) ; panel . addImage ( ConvertBufferedImage . convertTo ( adjusted , null ) , "Sharpen-8" ) ; panel . addImage ( ConvertBufferedImage . convertTo ( gray , null ) , "Original" ) ; panel . setPreferredSize ( new Dimension ( gray . width , gray . height ) ) ; mainPanel . addItem ( panel , "Sharpen" ) ; }
When an image is sharpened the intensity of edges are made more extreme while flat regions remain unchanged .
27,739
public boolean process ( T image ) { tracker . process ( image ) ; tick ++ ; inlierTracks . clear ( ) ; if ( first ) { addNewTracks ( ) ; first = false ; } else { if ( ! estimateMotion ( ) ) { return false ; } dropUnusedTracks ( ) ; int N = motionEstimator . getMatchSet ( ) . size ( ) ; if ( thresholdAdd <= 0 || N < thresholdAdd ) { changePoseToReference ( ) ; addNewTracks ( ) ; } } return true ; }
Estimates the motion given the left camera image . The latest information required by ImagePixelTo3D should be passed to the class before invoking this function .
27,740
private void addNewTracks ( ) { tracker . spawnTracks ( ) ; List < PointTrack > spawned = tracker . getNewTracks ( null ) ; for ( PointTrack t : spawned ) { Point2D3DTrack p = t . getCookie ( ) ; if ( p == null ) { t . cookie = p = new Point2D3DTrack ( ) ; } if ( ! pixelTo3D . process ( t . x , t . y ) || pixelTo3D . getW ( ) == 0 ) { tracker . dropTrack ( t ) ; } else { Point3D_F64 X = p . getLocation ( ) ; double w = pixelTo3D . getW ( ) ; X . set ( pixelTo3D . getX ( ) / w , pixelTo3D . getY ( ) / w , pixelTo3D . getZ ( ) / w ) ; p . lastInlier = tick ; pixelToNorm . compute ( t . x , t . y , p . observation ) ; } } }
Detects new features and computes their 3D coordinates
27,741
private boolean estimateMotion ( ) { List < PointTrack > active = tracker . getActiveTracks ( null ) ; List < Point2D3D > obs = new ArrayList < > ( ) ; for ( PointTrack t : active ) { Point2D3D p = t . getCookie ( ) ; pixelToNorm . compute ( t . x , t . y , p . observation ) ; obs . add ( p ) ; } if ( ! motionEstimator . process ( obs ) ) return false ; if ( doublePass ) { if ( ! performSecondPass ( active , obs ) ) return false ; } tracker . finishTracking ( ) ; Se3_F64 keyToCurr ; if ( refine != null ) { keyToCurr = new Se3_F64 ( ) ; refine . fitModel ( motionEstimator . getMatchSet ( ) , motionEstimator . getModelParameters ( ) , keyToCurr ) ; } else { keyToCurr = motionEstimator . getModelParameters ( ) ; } keyToCurr . invert ( currToKey ) ; int N = motionEstimator . getMatchSet ( ) . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int index = motionEstimator . getInputIndex ( i ) ; Point2D3DTrack t = active . get ( index ) . getCookie ( ) ; t . lastInlier = tick ; inlierTracks . add ( t ) ; } return true ; }
Estimates motion from the set of tracks and their 3D location
27,742
double scoreForTriangulation ( Motion motion ) { DMatrixRMaj H = new DMatrixRMaj ( 3 , 3 ) ; View viewA = motion . viewSrc ; View viewB = motion . viewDst ; pairs . reset ( ) ; for ( int i = 0 ; i < motion . associated . size ( ) ; i ++ ) { AssociatedIndex ai = motion . associated . get ( i ) ; pairs . grow ( ) . set ( viewA . observationPixels . get ( ai . src ) , viewB . observationPixels . get ( ai . dst ) ) ; } if ( ! computeH . process ( pairs . toList ( ) , H ) ) return - 1 ; if ( ! refineH . fitModel ( pairs . toList ( ) , H , H ) ) return - 1 ; MultiViewOps . errorsHomographySymm ( pairs . toList ( ) , H , null , errors ) ; errors . sort ( ) ; return errors . getFraction ( 0.5 ) * Math . max ( 5 , pairs . size - 20 ) ; }
Compute score to decide which motion to initialize structure from . A homography is fit to the observations and the error compute . The homography should be a poor fit if the scene had 3D structure . The 50% homography error is then scaled by the number of pairs to bias the score good matches
27,743
public void configure ( LensDistortionNarrowFOV distortion , Se3_F64 worldToCamera ) { this . worldToCamera = worldToCamera ; normToPixel = distortion . distort_F64 ( false , true ) ; }
Specifies intrinsic camera parameters and the transform from world to camera .
27,744
public boolean transform ( Point3D_F64 worldPt , Point2D_F64 pixelPt ) { SePointOps_F64 . transform ( worldToCamera , worldPt , cameraPt ) ; if ( cameraPt . z <= 0 ) return false ; normToPixel . compute ( cameraPt . x / cameraPt . z , cameraPt . y / cameraPt . z , pixelPt ) ; return true ; }
Computes the observed location of the specified point in world coordinates in the camera pixel . If the object can t be viewed because it is behind the camera then false is returned .
27,745
public Point2D_F64 transform ( Point3D_F64 worldPt ) { Point2D_F64 out = new Point2D_F64 ( ) ; if ( transform ( worldPt , out ) ) return out ; else return null ; }
Computes location of 3D point in world as observed in the camera . Point is returned if visible or null if not visible .
27,746
protected void splitPixels ( int indexStart , int length ) { if ( length < minimumSideLengthPixel ) return ; int indexEnd = ( indexStart + length ) % N ; int splitOffset = selectSplitOffset ( indexStart , length ) ; if ( splitOffset >= 0 ) { splitPixels ( indexStart , splitOffset ) ; int indexSplit = ( indexStart + splitOffset ) % N ; splits . add ( indexSplit ) ; splitPixels ( indexSplit , circularDistance ( indexSplit , indexEnd ) ) ; } }
Recursively splits pixels between indexStart to indexStart + length . A split happens if there is a pixel more than the desired distance away from the two end points . Results are placed into splits
27,747
protected boolean mergeSegments ( ) { if ( splits . size ( ) <= 3 ) return false ; boolean change = false ; work . reset ( ) ; for ( int i = 0 ; i < splits . size ; i ++ ) { int start = splits . data [ i ] ; int end = splits . data [ ( i + 2 ) % splits . size ] ; if ( selectSplitOffset ( start , circularDistance ( start , end ) ) < 0 ) { change = true ; } else { work . add ( splits . data [ ( i + 1 ) % splits . size ] ) ; } } GrowQueue_I32 tmp = work ; work = splits ; splits = tmp ; return change ; }
Merges lines together if the common corner is close to a common line
27,748
protected boolean splitSegments ( ) { boolean change = false ; work . reset ( ) ; for ( int i = 0 ; i < splits . size - 1 ; i ++ ) { change |= checkSplit ( change , i , i + 1 ) ; } change |= checkSplit ( change , splits . size - 1 , 0 ) ; GrowQueue_I32 tmp = work ; work = splits ; splits = tmp ; return change ; }
Splits a line in two if there is a point that is too far away
27,749
protected int circularDistance ( int start , int end ) { if ( end >= start ) return end - start ; else return N - start + end ; }
Distance the two points are apart in clockwise direction
27,750
public static void horizontal ( GrayF32 src , GrayF32 dst ) { if ( src . width < dst . width ) throw new IllegalArgumentException ( "src width must be >= dst width" ) ; if ( src . height != dst . height ) throw new IllegalArgumentException ( "src height must equal dst height" ) ; float scale = src . width / ( float ) dst . width ; for ( int y = 0 ; y < dst . height ; y ++ ) { int indexDst = dst . startIndex + y * dst . stride ; for ( int x = 0 ; x < dst . width - 1 ; x ++ , indexDst ++ ) { float srcX0 = x * scale ; float srcX1 = ( x + 1 ) * scale ; int isrcX0 = ( int ) srcX0 ; int isrcX1 = ( int ) srcX1 ; int index = src . getIndex ( isrcX0 , y ) ; float startWeight = ( 1.0f - ( srcX0 - isrcX0 ) ) ; float start = src . data [ index ++ ] ; float middle = 0 ; for ( int i = isrcX0 + 1 ; i < isrcX1 ; i ++ ) { middle += src . data [ index ++ ] ; } float endWeight = ( srcX1 % 1 ) ; float end = src . data [ index ] ; dst . data [ indexDst ] = ( start * startWeight + middle + end * endWeight ) / scale ; } int x = dst . width - 1 ; float srcX0 = x * scale ; int isrcX0 = ( int ) srcX0 ; int isrcX1 = src . width - 1 ; int index = src . getIndex ( isrcX0 , y ) ; float startWeight = ( 1.0f - ( srcX0 - isrcX0 ) ) ; float start = src . data [ index ++ ] ; float middle = 0 ; for ( int i = isrcX0 + 1 ; i < isrcX1 ; i ++ ) { middle += src . data [ index ++ ] ; } float end = isrcX1 != isrcX0 ? src . data [ index ] : 0 ; dst . data [ indexDst ] = ( start * startWeight + middle + end ) / scale ; } }
Down samples the image along the x - axis only . Image height s must be the same .
27,751
public static void vertical ( GrayF32 src , GrayF32 dst ) { if ( src . height < dst . height ) throw new IllegalArgumentException ( "src height must be >= dst height" ) ; if ( src . width != dst . width ) throw new IllegalArgumentException ( "src width must equal dst width" ) ; float scale = src . height / ( float ) dst . height ; for ( int x = 0 ; x < dst . width ; x ++ ) { int indexDst = dst . startIndex + x ; for ( int y = 0 ; y < dst . height - 1 ; y ++ ) { float srcY0 = y * scale ; float srcY1 = ( y + 1 ) * scale ; int isrcY0 = ( int ) srcY0 ; int isrcY1 = ( int ) srcY1 ; int index = src . getIndex ( x , isrcY0 ) ; float startWeight = ( 1.0f - ( srcY0 - isrcY0 ) ) ; float start = src . data [ index ] ; index += src . stride ; float middle = 0 ; for ( int i = isrcY0 + 1 ; i < isrcY1 ; i ++ ) { middle += src . data [ index ] ; index += src . stride ; } float endWeight = ( srcY1 % 1 ) ; float end = src . data [ index ] ; dst . data [ indexDst ] = ( float ) ( ( start * startWeight + middle + end * endWeight ) / scale ) ; indexDst += dst . stride ; } int y = dst . height - 1 ; float srcY0 = y * scale ; int isrcY0 = ( int ) srcY0 ; int isrcY1 = src . height - 1 ; int index = src . getIndex ( x , isrcY0 ) ; float startWeight = ( 1.0f - ( srcY0 - isrcY0 ) ) ; float start = src . data [ index ] ; index += src . stride ; float middle = 0 ; for ( int i = isrcY0 + 1 ; i < isrcY1 ; i ++ ) { middle += src . data [ index ] ; index += src . stride ; } float end = isrcY1 != isrcY0 ? src . data [ index ] : 0 ; dst . data [ indexDst ] = ( float ) ( ( start * startWeight + middle + end ) / scale ) ; } }
Down samples the image along the y - axis only . Image width s must be the same .
27,752
protected void drawFeatures ( float scale , int offsetX , int offsetY , FastQueue < Point2D_F64 > all , FastQueue < Point2D_F64 > inliers , Homography2D_F64 currToGlobal , Graphics2D g2 ) { Point2D_F64 distPt = new Point2D_F64 ( ) ; for ( int i = 0 ; i < all . size ; i ++ ) { HomographyPointOps_F64 . transform ( currToGlobal , all . get ( i ) , distPt ) ; distPt . x = offsetX + distPt . x * scale ; distPt . y = offsetY + distPt . y * scale ; VisualizeFeatures . drawPoint ( g2 , ( int ) distPt . x , ( int ) distPt . y , Color . RED ) ; } for ( int i = 0 ; i < inliers . size ; i ++ ) { HomographyPointOps_F64 . transform ( currToGlobal , inliers . get ( i ) , distPt ) ; distPt . x = offsetX + distPt . x * scale ; distPt . y = offsetY + distPt . y * scale ; VisualizeFeatures . drawPoint ( g2 , ( int ) distPt . x , ( int ) distPt . y , Color . BLUE ) ; } }
Draw features after applying a homography transformation .
27,753
public void update ( ImageGray image ) { if ( approximateHistogram ) { for ( int i = 0 ; i < bins . length ; i ++ ) bins [ i ] = 0 ; if ( image instanceof GrayF32 ) update ( ( GrayF32 ) image ) ; else if ( GrayI . class . isAssignableFrom ( image . getClass ( ) ) ) update ( ( GrayI ) image ) ; else throw new IllegalArgumentException ( "Image type not yet supported" ) ; } else { GImageStatistics . histogram ( image , 0 , bins ) ; } }
Update s the histogram . Must only be called in UI thread
27,754
public void addImage ( BufferedImage image , String name ) { addImage ( image , name , ScaleOptions . DOWN ) ; }
Displays a new image in the list .
27,755
public synchronized void addItem ( final JComponent panel , final String name ) { Dimension panelD = panel . getPreferredSize ( ) ; final boolean sizeChanged = bodyWidth != panelD . width || bodyHeight != panelD . height ; bodyWidth = ( int ) Math . max ( bodyWidth , panelD . getWidth ( ) ) ; bodyHeight = ( int ) Math . max ( bodyHeight , panelD . getHeight ( ) ) ; panels . add ( panel ) ; SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { listModel . addElement ( name ) ; if ( listModel . size ( ) == 1 ) { listPanel . setSelectedIndex ( 0 ) ; } Dimension d = listPanel . getMinimumSize ( ) ; listPanel . setPreferredSize ( new Dimension ( d . width + scroll . getVerticalScrollBar ( ) . getWidth ( ) , d . height ) ) ; if ( sizeChanged ) { Component old = ( ( BorderLayout ) bodyPanel . getLayout ( ) ) . getLayoutComponent ( BorderLayout . CENTER ) ; if ( old != null ) { old . setPreferredSize ( new Dimension ( bodyWidth , bodyHeight ) ) ; } } validate ( ) ; } } ) ; }
Displays a new JPanel in the list .
27,756
public static RectangleLength2D_F64 centerBoxInside ( int srcWidth , int srcHeight , PixelTransform < Point2D_F64 > transform , Point2D_F64 work ) { List < Point2D_F64 > points = computeBoundingPoints ( srcWidth , srcHeight , transform , work ) ; Point2D_F64 center = new Point2D_F64 ( ) ; UtilPoint2D_F64 . mean ( points , center ) ; double x0 , x1 , y0 , y1 ; double bx0 , bx1 , by0 , by1 ; x0 = x1 = y0 = y1 = 0 ; bx0 = bx1 = by0 = by1 = Double . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double dx = p . x - center . x ; double dy = p . y - center . y ; double adx = Math . abs ( dx ) ; double ady = Math . abs ( dy ) ; if ( adx < ady ) { if ( dy < 0 ) { if ( adx < by0 ) { by0 = adx ; y0 = dy ; } } else { if ( adx < by1 ) { by1 = adx ; y1 = dy ; } } } else { if ( dx < 0 ) { if ( ady < bx0 ) { bx0 = ady ; x0 = dx ; } } else { if ( ady < bx1 ) { bx1 = ady ; x1 = dx ; } } } } return new RectangleLength2D_F64 ( x0 + center . x , y0 + center . y , x1 - x0 , y1 - y0 ) ; }
Attempts to center the box inside . It will be approximately fitted too .
27,757
public static void roundInside ( RectangleLength2D_F64 bound ) { double x0 = Math . ceil ( bound . x0 ) ; double y0 = Math . ceil ( bound . y0 ) ; double x1 = Math . floor ( bound . x0 + bound . width ) ; double y1 = Math . floor ( bound . y0 + bound . height ) ; bound . x0 = x0 ; bound . y0 = y0 ; bound . width = x1 - x0 ; bound . height = y1 - y0 ; }
Adjust bound to ensure the entire image is contained inside otherwise there might be single pixel wide black regions
27,758
public boolean isInBounds ( int c_x , int c_y ) { return BoofMiscOps . checkInside ( image , c_x , c_y , radiusWidth , radiusHeight ) ; }
The entire region must be inside the image because any outside pixels will change the statistics
27,759
private GrowQueue_I32 findCommonTracks ( SeedInfo target ) { boolean visibleAll [ ] = new boolean [ target . seed . totalFeatures ] ; Arrays . fill ( visibleAll , true ) ; boolean visibleMotion [ ] = new boolean [ target . seed . totalFeatures ] ; for ( int idxMotion = 0 ; idxMotion < target . motions . size ; idxMotion ++ ) { PairwiseImageGraph2 . Motion m = target . seed . connections . get ( target . motions . get ( idxMotion ) ) ; boolean seedIsSrc = m . src == target . seed ; Arrays . fill ( visibleMotion , false ) ; for ( int i = 0 ; i < m . inliers . size ; i ++ ) { AssociatedIndex a = m . inliers . get ( i ) ; visibleMotion [ seedIsSrc ? a . src : a . dst ] = true ; } for ( int i = 0 ; i < target . seed . totalFeatures ; i ++ ) { visibleAll [ i ] &= visibleMotion [ i ] ; } } GrowQueue_I32 common = new GrowQueue_I32 ( target . seed . totalFeatures / 10 + 1 ) ; for ( int i = 0 ; i < target . seed . totalFeatures ; i ++ ) { if ( visibleAll [ i ] ) { common . add ( i ) ; } } return common ; }
Finds the indexes of tracks which are common to all views
27,760
private SeedInfo score ( View target ) { SeedInfo output = new SeedInfo ( ) ; output . seed = target ; scoresMotions . reset ( ) ; for ( int i = 0 ; i < target . connections . size ; i ++ ) { PairwiseImageGraph2 . Motion m = target . connections . get ( i ) ; if ( ! m . is3D ) continue ; scoresMotions . grow ( ) . set ( score ( m ) , i ) ; } Collections . sort ( scoresMotions . toList ( ) ) ; for ( int i = Math . min ( 2 , scoresMotions . size ) ; i >= 0 ; i -- ) { output . motions . add ( scoresMotions . get ( i ) . index ) ; output . score += scoresMotions . get ( i ) . score ; } return output ; }
Score a view for how well it could be a seed based on the the 3 best 3D motions associated with it
27,761
public static double score ( PairwiseImageGraph2 . Motion m ) { double score = Math . min ( 5 , m . countF / ( double ) ( m . countH + 1 ) ) ; score *= m . countF ; return score ; }
Scores the motion for its ability to capture 3D structure
27,762
public void process ( D derivX , D derivY , GrayU8 binaryEdges ) { InputSanityCheck . checkSameShape ( derivX , derivY , binaryEdges ) ; int w = derivX . width - regionSize + 1 ; int h = derivY . height - regionSize + 1 ; foundLines . reshape ( derivX . width / regionSize , derivX . height / regionSize ) ; foundLines . reset ( ) ; for ( int y = 0 ; y < h ; y += regionSize ) { int gridY = y / regionSize ; int index = binaryEdges . startIndex + y * binaryEdges . stride ; for ( int x = 0 ; x < w ; x += regionSize , index += regionSize ) { int gridX = x / regionSize ; detectEdgels ( index , x , y , derivX , derivY , binaryEdges ) ; findLinesInRegion ( foundLines . get ( gridX , gridY ) ) ; } } }
Detects line segments through the image inside of grids .
27,763
private void findLinesInRegion ( List < LineSegment2D_F32 > gridLines ) { List < Edgel > list = edgels . copyIntoList ( null ) ; int iterations = 0 ; while ( iterations ++ < maxDetectLines ) { if ( ! robustMatcher . process ( list ) ) break ; List < Edgel > matchSet = robustMatcher . getMatchSet ( ) ; if ( matchSet . size ( ) < minInlierSize ) break ; for ( Edgel e : matchSet ) { list . remove ( e ) ; } gridLines . add ( convertToLineSegment ( matchSet , robustMatcher . getModelParameters ( ) ) ) ; } }
Searches for lines inside inside the region ..
27,764
private LineSegment2D_F32 convertToLineSegment ( List < Edgel > matchSet , LinePolar2D_F32 model ) { float minT = Float . MAX_VALUE ; float maxT = - Float . MAX_VALUE ; LineParametric2D_F32 line = UtilLine2D_F32 . convert ( model , ( LineParametric2D_F32 ) null ) ; Point2D_F32 p = new Point2D_F32 ( ) ; for ( Edgel e : matchSet ) { p . set ( e . x , e . y ) ; float t = ClosestPoint2D_F32 . closestPointT ( line , e ) ; if ( minT > t ) minT = t ; if ( maxT < t ) maxT = t ; } LineSegment2D_F32 segment = new LineSegment2D_F32 ( ) ; segment . a . x = line . p . x + line . slope . x * minT ; segment . a . y = line . p . y + line . slope . y * minT ; segment . b . x = line . p . x + line . slope . x * maxT ; segment . b . y = line . p . y + line . slope . y * maxT ; return segment ; }
Lines are found in polar form and this coverts them into line segments by finding the extreme points of points on the line .
27,765
public TldFernFeature lookupFern ( int value ) { TldFernFeature found = table [ value ] ; if ( found == null ) { found = createFern ( ) ; found . init ( value ) ; table [ value ] = found ; } return found ; }
Looks up the fern with the specified value . If non exist a new one is created and returned .
27,766
public double lookupPosterior ( int value ) { TldFernFeature found = table [ value ] ; if ( found == null ) { return 0 ; } return found . posterior ; }
Looks up the posterior probability of the specified fern . If a fern is found its posterior is returned otherwise - 1 is returned .
27,767
void handleAdd ( ) { BoofSwingUtil . checkGuiThread ( ) ; java . util . List < File > paths = browser . getSelectedFiles ( ) ; for ( int i = 0 ; i < paths . size ( ) ; i ++ ) { File f = paths . get ( i ) ; if ( f . isDirectory ( ) ) { java . util . List < String > files = UtilIO . listAll ( f . getPath ( ) ) ; Collections . sort ( files ) ; for ( int j = 0 ; j < files . size ( ) ; j ++ ) { File p = new File ( files . get ( j ) ) ; if ( p . isFile ( ) ) { selected . addPath ( p ) ; } } } else { selected . addPath ( f ) ; } } }
Add all selected files
27,768
void handleOK ( ) { String [ ] selected = this . selected . paths . toArray ( new String [ 0 ] ) ; listener . selectedImages ( selected ) ; }
OK button pressed
27,769
void showPreview ( String path ) { synchronized ( lockPreview ) { if ( path == null ) { pendingPreview = null ; } else if ( previewThread == null ) { pendingPreview = path ; previewThread = new PreviewThread ( ) ; previewThread . start ( ) ; } else { pendingPreview = path ; } } }
Start a new preview thread if one isn t already running . Carefully manipulate variables due to threading
27,770
public static List < Point2D_F64 > createLayout ( int numRows , int numCols , double squareWidth , double spaceWidth ) { List < Point2D_F64 > all = new ArrayList < > ( ) ; double width = ( numCols * squareWidth + ( numCols - 1 ) * spaceWidth ) ; double height = ( numRows * squareWidth + ( numRows - 1 ) * spaceWidth ) ; double startX = - width / 2 ; double startY = - height / 2 ; for ( int i = numRows - 1 ; i >= 0 ; i -- ) { double y = startY + i * ( squareWidth + spaceWidth ) + squareWidth ; List < Point2D_F64 > top = new ArrayList < > ( ) ; List < Point2D_F64 > bottom = new ArrayList < > ( ) ; for ( int j = 0 ; j < numCols ; j ++ ) { double x = startX + j * ( squareWidth + spaceWidth ) ; top . add ( new Point2D_F64 ( x , y ) ) ; top . add ( new Point2D_F64 ( x + squareWidth , y ) ) ; bottom . add ( new Point2D_F64 ( x , y - squareWidth ) ) ; bottom . add ( new Point2D_F64 ( x + squareWidth , y - squareWidth ) ) ; } all . addAll ( top ) ; all . addAll ( bottom ) ; } return all ; }
Creates a target that is composed of squares . The squares are spaced out and each corner provides a calibration point .
27,771
public void process ( FastQueue < PositionPatternNode > pps , T gray ) { gridReader . setImage ( gray ) ; storageQR . reset ( ) ; successes . clear ( ) ; failures . clear ( ) ; for ( int i = 0 ; i < pps . size ; i ++ ) { PositionPatternNode ppn = pps . get ( i ) ; for ( int j = 3 , k = 0 ; k < 4 ; j = k , k ++ ) { if ( ppn . edges [ j ] != null && ppn . edges [ k ] != null ) { QrCode qr = storageQR . grow ( ) ; qr . reset ( ) ; setPositionPatterns ( ppn , j , k , qr ) ; computeBoundingBox ( qr ) ; if ( decode ( gray , qr ) ) { successes . add ( qr ) ; } else { failures . add ( qr ) ; } } } } }
Detects QR Codes inside image using position pattern graph
27,772
static void computeBoundingBox ( QrCode qr ) { qr . bounds . get ( 0 ) . set ( qr . ppCorner . get ( 0 ) ) ; qr . bounds . get ( 1 ) . set ( qr . ppRight . get ( 1 ) ) ; Intersection2D_F64 . intersection ( qr . ppRight . get ( 1 ) , qr . ppRight . get ( 2 ) , qr . ppDown . get ( 3 ) , qr . ppDown . get ( 2 ) , qr . bounds . get ( 2 ) ) ; qr . bounds . get ( 3 ) . set ( qr . ppDown . get ( 3 ) ) ; }
3 or the 4 corners are from the position patterns . The 4th is extrapolated using the position pattern sides .
27,773
private boolean extractFormatInfo ( QrCode qr ) { for ( int i = 0 ; i < 2 ; i ++ ) { if ( i == 0 ) readFormatRegion0 ( qr ) ; else readFormatRegion1 ( qr ) ; int bitField = this . bits . read ( 0 , 15 , false ) ; bitField ^= QrCodePolynomialMath . FORMAT_MASK ; int message ; if ( QrCodePolynomialMath . checkFormatBits ( bitField ) ) { message = bitField >> 10 ; } else { message = QrCodePolynomialMath . correctFormatBits ( bitField ) ; } if ( message >= 0 ) { QrCodePolynomialMath . decodeFormatMessage ( message , qr ) ; return true ; } } return false ; }
Reads format info bits from the image and saves the results in qr
27,774
private boolean readFormatRegion0 ( QrCode qr ) { gridReader . setSquare ( qr . ppCorner , ( float ) qr . threshCorner ) ; bits . resize ( 15 ) ; bits . zero ( ) ; for ( int i = 0 ; i < 6 ; i ++ ) { read ( i , i , 8 ) ; } read ( 6 , 7 , 8 ) ; read ( 7 , 8 , 8 ) ; read ( 8 , 8 , 7 ) ; for ( int i = 0 ; i < 6 ; i ++ ) { read ( 9 + i , 8 , 5 - i ) ; } return true ; }
Reads the format bits near the corner position pattern
27,775
private boolean readFormatRegion1 ( QrCode qr ) { gridReader . setSquare ( qr . ppRight , ( float ) qr . threshRight ) ; bits . resize ( 15 ) ; bits . zero ( ) ; for ( int i = 0 ; i < 8 ; i ++ ) { read ( i , 8 , 6 - i ) ; } gridReader . setSquare ( qr . ppDown , ( float ) qr . threshDown ) ; for ( int i = 0 ; i < 6 ; i ++ ) { read ( i + 8 , i , 8 ) ; } return true ; }
Read the format bits on the right and bottom patterns
27,776
private boolean readRawData ( QrCode qr ) { QrCode . VersionInfo info = QrCode . VERSION_INFO [ qr . version ] ; qr . rawbits = new byte [ info . codewords ] ; bits . resize ( info . codewords * 8 ) ; List < Point2D_I32 > locationBits = QrCode . LOCATION_BITS [ qr . version ] ; for ( int i = 0 ; i < bits . size ; i ++ ) { Point2D_I32 b = locationBits . get ( i ) ; readDataMatrix ( i , b . y , b . x , qr . mask ) ; } System . arraycopy ( bits . data , 0 , qr . rawbits , 0 , qr . rawbits . length ) ; return true ; }
Read the raw data from input memory
27,777
private void read ( int bit , int row , int col ) { int value = gridReader . readBit ( row , col ) ; if ( value == - 1 ) { value = 0 ; } bits . set ( bit , value ) ; }
Reads a bit from the image .
27,778
boolean extractVersionInfo ( QrCode qr ) { int version = estimateVersionBySize ( qr ) ; if ( version >= QrCode . VERSION_ENCODED_AT ) { readVersionRegion0 ( qr ) ; int version0 = decodeVersion ( ) ; readVersionRegion1 ( qr ) ; int version1 = decodeVersion ( ) ; if ( version0 < 1 && version1 < 1 ) { version = - 1 ; } else if ( version0 < 1 ) { version = version1 ; } else if ( version1 < 1 ) { version = version0 ; } else if ( version0 != version1 ) { version = - 1 ; } else { version = version0 ; } } else if ( version <= 0 ) { version = - 1 ; } qr . version = version ; return version >= 1 && version <= QrCode . MAX_VERSION ; }
Determine the QR code s version . For QR codes version < 7 it can be determined using the marker s size alone . Otherwise the version is read from the image itself
27,779
int decodeVersion ( ) { int bitField = this . bits . read ( 0 , 18 , false ) ; int message ; if ( QrCodePolynomialMath . checkVersionBits ( bitField ) ) { message = bitField >> 12 ; } else { message = QrCodePolynomialMath . correctVersionBits ( bitField ) ; } if ( message > QrCode . MAX_VERSION || message < QrCode . VERSION_ENCODED_AT ) return - 1 ; return message ; }
Decode version information from read in bits
27,780
int estimateVersionBySize ( QrCode qr ) { gridReader . setMarkerUnknownVersion ( qr , 0 ) ; gridReader . imageToGrid ( qr . ppRight . get ( 0 ) , grid ) ; if ( Math . abs ( grid . y / grid . x ) >= 0.3 ) return - 1 ; double versionX = ( ( grid . x + 7 ) - 17 ) / 4 ; gridReader . imageToGrid ( qr . ppDown . get ( 0 ) , grid ) ; if ( Math . abs ( grid . x / grid . y ) >= 0.3 ) return - 1 ; double versionY = ( ( grid . y + 7 ) - 17 ) / 4 ; if ( Math . abs ( versionX - versionY ) / Math . max ( versionX , versionY ) > 0.4 ) return - 1 ; return ( int ) ( ( versionX + versionY ) / 2.0 + 0.5 ) ; }
Attempts to estimate the qr - code s version based on distance between position patterns . If it can t estimate it based on distance return - 1
27,781
private boolean readVersionRegion0 ( QrCode qr ) { gridReader . setSquare ( qr . ppRight , ( float ) qr . threshRight ) ; bits . resize ( 18 ) ; bits . zero ( ) ; for ( int i = 0 ; i < 18 ; i ++ ) { int row = i / 3 ; int col = i % 3 ; read ( i , row , col - 4 ) ; } return true ; }
Reads the version bits near the right position pattern
27,782
private boolean readVersionRegion1 ( QrCode qr ) { gridReader . setSquare ( qr . ppDown , ( float ) qr . threshDown ) ; bits . resize ( 18 ) ; bits . zero ( ) ; for ( int i = 0 ; i < 18 ; i ++ ) { int row = i % 3 ; int col = i / 3 ; read ( i , row - 4 , col ) ; } return true ; }
Reads the version bits near the bottom position pattern
27,783
public static void hessianBorder ( GrayF32 integral , int skip , int size , GrayF32 intensity ) { final int w = intensity . width ; final int h = intensity . height ; IntegralKernel kerXX = DerivativeIntegralImage . kernelDerivXX ( size , null ) ; IntegralKernel kerYY = DerivativeIntegralImage . kernelDerivYY ( size , null ) ; IntegralKernel kerXY = DerivativeIntegralImage . kernelDerivXY ( size , null ) ; int radiusFeature = size / 2 ; final int borderOrig = radiusFeature + 1 + ( skip - ( radiusFeature + 1 ) % skip ) ; final int border = borderOrig / skip ; float norm = 1.0f / ( size * size ) ; BoofConcurrency . loopFor ( 0 , h , y -> { int yy = y * skip ; for ( int x = 0 ; x < border ; x ++ ) { int xx = x * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } for ( int x = w - border ; x < w ; x ++ ) { int xx = x * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } } ) ; BoofConcurrency . loopFor ( border , w - border , x -> { int xx = x * skip ; for ( int y = 0 ; y < border ; y ++ ) { int yy = y * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } for ( int y = h - border ; y < h ; y ++ ) { int yy = y * skip ; computeHessian ( integral , intensity , kerXX , kerYY , kerXY , norm , y , yy , x , xx ) ; } } ) ; }
Only computes the fast hessian along the border using a brute force approach
27,784
public static GrayU8 logicAnd ( GrayU8 inputA , GrayU8 inputB , GrayU8 output ) { InputSanityCheck . checkSameShape ( inputA , inputB ) ; output = InputSanityCheck . checkDeclare ( inputA , output ) ; if ( BoofConcurrency . USE_CONCURRENT ) { ImplBinaryImageOps_MT . logicAnd ( inputA , inputB , output ) ; } else { ImplBinaryImageOps . logicAnd ( inputA , inputB , output ) ; } return output ; }
For each pixel it applies the logical and operator between two images .
27,785
public static GrayU8 invert ( GrayU8 input , GrayU8 output ) { output = InputSanityCheck . checkDeclare ( input , output ) ; if ( BoofConcurrency . USE_CONCURRENT ) { ImplBinaryImageOps_MT . invert ( input , output ) ; } else { ImplBinaryImageOps . invert ( input , output ) ; } return output ; }
Inverts each pixel from true to false and vis - versa .
27,786
public static GrayU8 thin ( GrayU8 input , int maxIterations , GrayU8 output ) { output = InputSanityCheck . checkDeclare ( input , output ) ; output . setTo ( input ) ; BinaryThinning thinning = new BinaryThinning ( ) ; thinning . apply ( output , maxIterations ) ; return output ; }
Applies a morphological thinning operation to the image . Also known as skeletonization .
27,787
public static List < Contour > contourExternal ( GrayU8 input , ConnectRule rule ) { BinaryContourFinder alg = FactoryBinaryContourFinder . linearExternal ( ) ; alg . setConnectRule ( rule ) ; alg . process ( input ) ; return convertContours ( alg ) ; }
Finds the external contours only in the image
27,788
public static void relabel ( GrayS32 input , int labels [ ] ) { if ( BoofConcurrency . USE_CONCURRENT ) { ImplBinaryImageOps_MT . relabel ( input , labels ) ; } else { ImplBinaryImageOps . relabel ( input , labels ) ; } }
Used to change the labels in a labeled binary image .
27,789
public static GrayU8 labelToBinary ( GrayS32 labelImage , GrayU8 binaryImage ) { binaryImage = InputSanityCheck . checkDeclare ( labelImage , binaryImage , GrayU8 . class ) ; if ( BoofConcurrency . USE_CONCURRENT ) { ImplBinaryImageOps_MT . labelToBinary ( labelImage , binaryImage ) ; } else { ImplBinaryImageOps . labelToBinary ( labelImage , binaryImage ) ; } return binaryImage ; }
Converts a labeled image into a binary image by setting any non - zero value to one .
27,790
public static List < List < Point2D_I32 > > labelToClusters ( GrayS32 labelImage , int numLabels , FastQueue < Point2D_I32 > queue ) { List < List < Point2D_I32 > > ret = new ArrayList < > ( ) ; for ( int i = 0 ; i < numLabels + 1 ; i ++ ) { ret . add ( new ArrayList < Point2D_I32 > ( ) ) ; } if ( queue == null ) { queue = new FastQueue < > ( numLabels , Point2D_I32 . class , true ) ; } else queue . reset ( ) ; for ( int y = 0 ; y < labelImage . height ; y ++ ) { int start = labelImage . startIndex + y * labelImage . stride ; int end = start + labelImage . width ; for ( int index = start ; index < end ; index ++ ) { int v = labelImage . data [ index ] ; if ( v > 0 ) { Point2D_I32 p = queue . grow ( ) ; p . set ( index - start , y ) ; ret . get ( v ) . add ( p ) ; } } } if ( ret . get ( 0 ) . size ( ) != 0 ) throw new RuntimeException ( "BUG!" ) ; ret . remove ( 0 ) ; return ret ; }
Scans through the labeled image and adds the coordinate of each pixel that has been labeled to a list specific to its label .
27,791
public static void clusterToBinary ( List < List < Point2D_I32 > > clusters , GrayU8 binary ) { ImageMiscOps . fill ( binary , 0 ) ; for ( List < Point2D_I32 > l : clusters ) { for ( Point2D_I32 p : l ) { binary . set ( p . x , p . y , 1 ) ; } } }
Sets each pixel in the list of clusters to one in the binary image .
27,792
public static int [ ] selectRandomColors ( int numBlobs , Random rand ) { int colors [ ] = new int [ numBlobs + 1 ] ; colors [ 0 ] = 0 ; int B = 100 ; for ( int i = 1 ; i < colors . length ; i ++ ) { int c ; while ( true ) { c = rand . nextInt ( 0xFFFFFF ) ; if ( ( c & 0xFF ) > B || ( ( c >> 8 ) & 0xFF ) > B || ( ( c >> 8 ) & 0xFF ) > B ) { break ; } } colors [ i ] = c ; } return colors ; }
Several blob rending functions take in an array of colors so that the random blobs can be drawn with the same color each time . This function selects a random color for each blob and returns it in an array .
27,793
public static void bufferDepthToU16 ( ByteBuffer input , GrayU16 output ) { int indexIn = 0 ; for ( int y = 0 ; y < output . height ; y ++ ) { int indexOut = output . startIndex + y * output . stride ; for ( int x = 0 ; x < output . width ; x ++ , indexOut ++ ) { output . data [ indexOut ] = ( short ) ( ( input . get ( indexIn ++ ) & 0xFF ) | ( ( input . get ( indexIn ++ ) & 0xFF ) << 8 ) ) ; } } }
Converts data in a ByteBuffer into a 16bit depth image
27,794
public static void bufferRgbToMsU8 ( byte [ ] input , Planar < GrayU8 > output ) { GrayU8 band0 = output . getBand ( 0 ) ; GrayU8 band1 = output . getBand ( 1 ) ; GrayU8 band2 = output . getBand ( 2 ) ; int indexIn = 0 ; for ( int y = 0 ; y < output . height ; y ++ ) { int indexOut = output . startIndex + y * output . stride ; for ( int x = 0 ; x < output . width ; x ++ , indexOut ++ ) { band0 . data [ indexOut ] = input [ indexIn ++ ] ; band1 . data [ indexOut ] = input [ indexIn ++ ] ; band2 . data [ indexOut ] = input [ indexIn ++ ] ; } } }
Converts byte array that contains RGB data into a 3 - channel Planar image
27,795
public void computeECC ( GrowQueue_I8 input , GrowQueue_I8 output ) { int N = generator . size - 1 ; input . extend ( input . size + N ) ; Arrays . fill ( input . data , input . size - N , input . size , ( byte ) 0 ) ; math . polyDivide ( input , generator , tmp0 , output ) ; input . size -= N ; }
Given the input message compute the error correction code for it
27,796
public boolean correct ( GrowQueue_I8 input , GrowQueue_I8 ecc ) { computeSyndromes ( input , ecc , syndromes ) ; findErrorLocatorPolynomialBM ( syndromes , errorLocatorPoly ) ; if ( ! findErrorLocations_BruteForce ( errorLocatorPoly , input . size + ecc . size , errorLocations ) ) return false ; correctErrors ( input , input . size + ecc . size , syndromes , errorLocatorPoly , errorLocations ) ; return true ; }
Decodes the message and performs any necessary error correction
27,797
void findErrorLocatorPolynomial ( int messageLength , GrowQueue_I32 errorLocations , GrowQueue_I8 errorLocator ) { tmp1 . resize ( 2 ) ; tmp1 . data [ 1 ] = 1 ; errorLocator . resize ( 1 ) ; errorLocator . data [ 0 ] = 1 ; for ( int i = 0 ; i < errorLocations . size ; i ++ ) { int where = messageLength - errorLocations . get ( i ) - 1 ; tmp1 . data [ 0 ] = ( byte ) math . power ( 2 , where ) ; tmp0 . setTo ( errorLocator ) ; math . polyMult ( tmp0 , tmp1 , errorLocator ) ; } }
Compute the error locator polynomial when given the error locations in the message .
27,798
public boolean findErrorLocations_BruteForce ( GrowQueue_I8 errorLocator , int messageLength , GrowQueue_I32 locations ) { locations . resize ( 0 ) ; for ( int i = 0 ; i < messageLength ; i ++ ) { if ( math . polyEval_S ( errorLocator , math . power ( 2 , i ) ) == 0 ) { locations . add ( messageLength - i - 1 ) ; } } return locations . size == errorLocator . size - 1 ; }
Creates a list of bytes that have errors in them
27,799
void correctErrors ( GrowQueue_I8 message , int length_msg_ecc , GrowQueue_I8 syndromes , GrowQueue_I8 errorLocator , GrowQueue_I32 errorLocations ) { GrowQueue_I8 err_eval = new GrowQueue_I8 ( ) ; findErrorEvaluator ( syndromes , errorLocator , err_eval ) ; GrowQueue_I8 X = GrowQueue_I8 . zeros ( errorLocations . size ) ; for ( int i = 0 ; i < errorLocations . size ; i ++ ) { int coef_pos = ( length_msg_ecc - errorLocations . data [ i ] - 1 ) ; X . data [ i ] = ( byte ) math . power ( 2 , coef_pos ) ; } GrowQueue_I8 err_loc_prime_tmp = new GrowQueue_I8 ( X . size ) ; for ( int i = 0 ; i < X . size ; i ++ ) { int Xi = X . data [ i ] & 0xFF ; int Xi_inv = math . inverse ( Xi ) ; err_loc_prime_tmp . size = 0 ; for ( int j = 0 ; j < X . size ; j ++ ) { if ( i == j ) continue ; err_loc_prime_tmp . data [ err_loc_prime_tmp . size ++ ] = ( byte ) GaliosFieldOps . subtract ( 1 , math . multiply ( Xi_inv , X . data [ j ] & 0xFF ) ) ; } int err_loc_prime = 1 ; for ( int j = 0 ; j < err_loc_prime_tmp . size ; j ++ ) { err_loc_prime = math . multiply ( err_loc_prime , err_loc_prime_tmp . data [ j ] & 0xFF ) ; } int y = math . polyEval_S ( err_eval , Xi_inv ) ; y = math . multiply ( math . power ( Xi , 1 ) , y ) ; int magnitude = math . divide ( y , err_loc_prime ) ; int loc = errorLocations . get ( i ) ; if ( loc < message . size ) message . data [ loc ] = ( byte ) ( ( message . data [ loc ] & 0xFF ) ^ magnitude ) ; } }
Use Forney algorithm to compute correction values .