Given a label matrix, return a matrix of the outlines of the labeled objects
    
    If a pixel is not zero and has at least one neighbor with a different
    value, then it is part of the outline.
769393
def outline(labels):
    
    
    output = numpy.zeros(labels.shape, labels.dtype)
    lr_different = labels[1:,:]!=labels[:-1,:]
    ud_different = labels[:,1:]!=labels[:,:-1]
    d1_different = labels[1:,1:]!=labels[:-1,:-1]
    d2_different = labels[1:,:-1]!=labels[:-1,1:]
    different = numpy.zeros(labels.shape, bool)
    different[1:,:][lr_different]  = True
    different[:-1,:][lr_different] = True
    different[:,1:][ud_different]  = True
    different[:,:-1][ud_different] = True
    different[1:,1:][d1_different] = True
    different[:-1,:-1][d1_different] = True
    different[1:,:-1][d2_different] = True
    different[:-1,1:][d2_different] = True
    #
    # Labels on edges need outlines
    #
    different[0,:] = True
    different[:,0] = True
    different[-1,:] = True
    different[:,-1] = True
    
    output[different] = labels[different]
    return output
1087627
private boolean areaLinePredicates_(int half_edge, int id_a, int id_b) {
        boolean bRelationKnown = true;

        if (m_perform_predicates[MatrixPredicate.InteriorInterior])
        {
            interiorAreaInteriorLine_(half_edge, id_a, id_b);
            bRelationKnown &= isPredicateKnown_(MatrixPredicate.InteriorInterior);
        }

        if (m_perform_predicates[MatrixPredicate.InteriorBoundary])
        {
            interiorAreaBoundaryLine_(half_edge, id_a, id_b, m_cluster_index_b);
            bRelationKnown &= isPredicateKnown_(MatrixPredicate.InteriorBoundary);
        }

        if (m_perform_predicates[MatrixPredicate.InteriorExterior])
        {
            interiorAreaExteriorLine_(half_edge, id_a, id_b);
            bRelationKnown &= isPredicateKnown_(MatrixPredicate.InteriorExterior);
        }

        if (m_perform_predicates[MatrixPredicate.BoundaryInterior])
        {
            boundaryAreaInteriorLine_(half_edge, id_a, id_b, m_cluster_index_b);
            bRelationKnown &= isPredicateKnown_(MatrixPredicate.BoundaryInterior);
        }

        if (m_perform_predicates[MatrixPredicate.BoundaryBoundary])
        {
            boundaryAreaBoundaryLine_(half_edge, id_a, id_b, m_cluster_index_b);
            bRelationKnown &= isPredicateKnown_(MatrixPredicate.BoundaryBoundary);
        }

        if (m_perform_predicates[MatrixPredicate.BoundaryExterior])
        {
            boundaryAreaExteriorLine_(half_edge, id_a, id_b);
            bRelationKnown &= isPredicateKnown_(MatrixPredicate.BoundaryExterior);
        }

        if (m_perform_predicates[MatrixPredicate.ExteriorInterior])
        {
            exteriorAreaInteriorLine_(half_edge, id_a);
            bRelationKnown &= isPredicateKnown_(MatrixPredicate.ExteriorInterior);
        }

        if (m_perform_predicates[MatrixPredicate.ExteriorBoundary])
        {
            exteriorAreaBoundaryLine_(half_edge, id_a, id_b, m_cluster_index_b);
            bRelationKnown &= isPredicateKnown_(MatrixPredicate.ExteriorBoundary);
        }

        return bRelationKnown;
	}
1112661
def _mark_grid_bounds(self, plane, region_bbox):
        
        # Grid boundaries
        vbars = np.zeros([self.num_rows, self.num_cols + 1], dtype=np.bool)
        hbars = np.zeros([self.num_rows + 1, self.num_cols], dtype=np.bool)

        def closest_idx(arr, elem):
            left = bisect.bisect_left(arr, elem) - 1
            right = bisect.bisect_right(arr, elem) - 1
            return left if abs(arr[left] - elem) < abs(arr[right] - elem) else right

        # Figure out which separating segments are missing, i.e. merge cells
        for row, (y0, y1) in enumerate(self.yranges):
            yc = (y0 + y1) // 2
            for l in plane.find((region_bbox.x0, yc, region_bbox.x1, yc)):
                vbars[row, closest_idx(self.xs, l.xc)] = True
        for col, (x0, x1) in enumerate(self.xranges):
            xc = (x0 + x1) // 2
            for l in plane.find((xc, region_bbox.y0, xc, region_bbox.y1)):
                hbars[closest_idx(self.ys, l.yc), col] = True
        return vbars, hbars
1253169
def get_neighbors(distance_matrix, source, eps):
    

    return [dest for dest, distance in enumerate(distance_matrix[source]) if distance < eps]
907566
def colRowIsOnSciencePixelList(self, col, row, padding=DEFAULT_PADDING):
        """"""
        out = np.ones(len(col), dtype=bool)
        col_arr = np.array(col)
        row_arr = np.array(row)
        mask = np.bitwise_or(col_arr < 12. - padding, col_arr > 1111 + padding)
        out[mask] = False
        mask = np.bitwise_or(row_arr < 20. - padding, row_arr > 1043 + padding)
        out[mask] = False
        return out
239513
def distance_to_edge(labels):
    '''
    '''
    colors = color_labels(labels)
    max_color = np.max(colors)
    result = np.zeros(labels.shape)
    if max_color == 0:
        return result
    
    for i in range(1, max_color+1):
        mask = (colors==i)
        result[mask] = scind.distance_transform_edt(mask)[mask]
    return result
287620
def adjacent(labels):
    '''
       
    '''
    high = labels.max()+1
    if high > np.iinfo(labels.dtype).max:
        labels = labels.astype(np.int)
    image_with_high_background = labels.copy()
    image_with_high_background[labels == 0] = high
    min_label = scind.minimum_filter(image_with_high_background,
                                     footprint=np.ones((3,3),bool),
                                     mode = 'constant',
                                     cval = high)
    max_label = scind.maximum_filter(labels,
                                     footprint=np.ones((3,3),bool),
                                     mode = 'constant',
                                     cval = 0)
    return (min_label != max_label) & (labels > 0)
386219
private Matrix getEdgeSimMatrix(List<Edge> edgeList, SparseMatrix sm,
                                    boolean keepSimilarityMatrixInMemory) {
        return (keepSimilarityMatrixInMemory) 
            ? calculateEdgeSimMatrix(edgeList, sm)
            : new LazySimilarityMatrix(edgeList, sm);            
    }
1201810
def neighbors( open_list=[], closed_list=[] )
      i,j = free_cell      
      up = moved_matrix_with_parent(i, j, i-1, j, open_list, closed_list)
      down = moved_matrix_with_parent(i, j, i+1, j, open_list, closed_list)
      left = moved_matrix_with_parent(i, j, i, j-1, open_list, closed_list)
      right = moved_matrix_with_parent(i, j, i, j+1, open_list, closed_list)

      moved = []
      moved << up if !up.nil? 
      moved << down if !down.nil? 
      moved << left if !left.nil? 
      moved << right if !right.nil? 

      return moved
    end
712859
public int checkBackground( float[] pixelValue , float[] dataRow , int modelIndex ) {

		// see which gaussian is the best fit based on Mahalanobis distance
		int index = modelIndex;
		float bestDistance = maxDistance*numBands;
		float bestWeight = 0;

		int ng; // number of gaussians in use
		for (ng = 0; ng < maxGaussians; ng++, index += gaussianStride) {
			float variance = dataRow[index + 1];
			if (variance <= 0) {
				break;
			}

			float mahalanobis = 0;
			for (int i = 0; i < numBands; i++) {
				float mean = dataRow[index + 2+i];
				float delta = pixelValue[i] - mean;
				mahalanobis += delta * delta / variance;
			}

			if (mahalanobis < bestDistance) {
				bestDistance = mahalanobis;
				bestWeight = dataRow[index];
			}
		}

		if( ng == 0 ) // There are no models. Return unknown
			return unknownValue;
		return bestWeight >= significantWeight ? 0 : 1;
	}
1017848
private void handleStep2(GrayS32 labeled, int label) {
		// if the blob is not labeled and in this state it cannot be against the left side of the image
		if( label == 0 )
			label = labeled.data[indexOut-1];

		ContourPacked c = contours.get(label-1);
		c.internalIndexes.add( packedPoints.size() );
		packedPoints.grow();
		tracer.setMaxContourSize(saveInternalContours?maxContourSize:0);
		tracer.trace(label,x,y,false);

		// See if the inner contour exceeded the maximum  or minimum size. If so free its points
		if( packedPoints.sizeOfTail() >= maxContourSize || packedPoints.sizeOfTail() < minContourSize ) {
			packedPoints.removeTail();
			packedPoints.grow();
		}
	}
400094
def getPixmap(self, matrix=None, colorspace=None, alpha=0, clip=None):
        """"""
        return _fitz.DisplayList_getPixmap(self, matrix, colorspace, alpha, clip)
940778
private static boolean areAttachmentLabelsUnique(List<String> labels) {
    Map<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    for (int i = 0; i < labels.size(); i++) {
      map.put(labels.get(i), labels.get(i));
    }
    if (labels.size() == map.size()) {
      return true;
    } else {
      return false;
    }
  }
966043
def matrix_from_edges(edges):
    ''''''
    max_col = 0
    cols = []
    rows = []
    vals = []
    if type(edges) is defaultdict:
        edge_list = []
        for i, neighbors in edges.items():
            for j in neighbors:
                if i <= j:
                    edge_list.append((i,j))
        edges = edge_list
    for i, edge in enumerate(edges):
        s, t = edge[0], edge[1]
        weight = 1 if len(edge) == 2 else edge[2]
        cols.append(min(s,t))
        cols.append(max(s,t))
        rows.append(i)
        rows.append(i)
        vals.append(weight)
        vals.append(-weight)
        if cols[-1] > max_col:
            max_col = cols[-1]
    return coo_matrix((vals, (rows, cols)), shape=(rows[-1]+1, max_col+1))
585555
def _check_r(self, r):
        """"""
        if abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
            abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
            abs(np.dot(r[:, 0], r[:, 0]) - 1) > eps or \
            np.dot(r[:, 0], r[:, 1]) > eps or \
            np.dot(r[:, 1], r[:, 2]) > eps or \
            np.dot(r[:, 2], r[:, 0]) > eps:
            raise ValueError("The rotation matrix is significantly non-orthonormal.")
1335984
def array_scanlines_interlace(self, pixels):
        

        # http://www.w3.org/TR/PNG/#8InterlaceMethods
        # Array type.
        fmt = 'BH'[self.bitdepth > 8]
        # Value per row
        vpr = self.width * self.planes
        for xstart, ystart, xstep, ystep in _adam7:
            if xstart >= self.width:
                continue
            # Pixels per row (of reduced image)
            ppr = int(math.ceil((self.width-xstart)/float(xstep)))
            # number of values in reduced image row.
            row_len = ppr*self.planes
            for y in range(ystart, self.height, ystep):
                if xstep == 1:
                    offset = y * vpr
                    yield pixels[offset:offset+vpr]
                else:
                    row = array(fmt)
                    # There's no easier way to set the length of an array
                    row.extend(pixels[0:row_len])
                    offset = y * vpr + xstart * self.planes
                    end_offset = (y+1) * vpr
                    skip = self.planes * xstep
                    for i in range(self.planes):
                        row[i::self.planes] = \
                            pixels[offset+i:end_offset:skip]
                    yield row
757194
static void detectAdjacentAndPositionPatterns(int N, QrCodeCodeWordLocations matrix, FoundFeatures features) {

		for (int foo = 0; foo < 2; foo++) {
			for (int row = 0; row < N; row++) {
				int index = row * N;
				for (int col = 1; col < N; col++, index++) {
					if (matrix.data[index] == matrix.data[index + 1])
						features.adjacent++;
				}
				index = row * N;
				for (int col = 6; col < N; col++, index++) {
					if (matrix.data[index] && !matrix.data[index + 1] &&
							matrix.data[index + 2] && matrix.data[index + 3] && matrix.data[index + 4] &&
							!matrix.data[index + 5] && matrix.data[index + 6])
						features.position++;
				}
			}
			CommonOps_BDRM.transposeSquare(matrix);
		}

		// subtract out false positives by the mask applied to position patterns, timing, mode
		features.adjacent -= 8*9 + 2*9*8 + (N-18)*2;
	}