Wraps cv2.findContours to maintain compatiblity between versions
    3 and 4

    Returns:
        contours, hierarchy
334287
def findContours(*args, **kwargs):
    
    if cv2.__version__.startswith('4'):
        contours, hierarchy = cv2.findContours(*args, **kwargs)
    elif cv2.__version__.startswith('3'):
        _, contours, hierarchy = cv2.findContours(*args, **kwargs)
    else:
        raise AssertionError(
            'cv2 must be either version 3 or 4 to call this method')

    return contours, hierarchy
1128154
def fitImg(self, img_rgb):
        '''
        
        '''
        H = self.pattern.findHomography(img_rgb)[0]
        H_inv = self.pattern.invertHomography(H)
        s = self.img_orig.shape
        warped = cv2.warpPerspective(img_rgb, H_inv, (s[1], s[0]))
        return warped
1122478
def __msgc_step3_discontinuity_localization(self):
        
        import scipy

        start = self._start_time
        seg = 1 - self.segmentation.astype(np.int8)
        self.stats["low level object voxels"] = np.sum(seg)
        self.stats["low level image voxels"] = np.prod(seg.shape)
        # in seg is now stored low resolution segmentation
        # back to normal parameters
        # step 2: discontinuity localization
        # self.segparams = sparams_hi
        seg_border = scipy.ndimage.filters.laplace(seg, mode="constant")
        logger.debug("seg_border: %s", scipy.stats.describe(seg_border, axis=None))
        # logger.debug(str(np.max(seg_border)))
        # logger.debug(str(np.min(seg_border)))
        seg_border[seg_border != 0] = 1
        logger.debug("seg_border: %s", scipy.stats.describe(seg_border, axis=None))
        # scipy.ndimage.morphology.distance_transform_edt
        boundary_dilatation_distance = self.segparams["boundary_dilatation_distance"]
        seg = scipy.ndimage.morphology.binary_dilation(
            seg_border,
            # seg,
            np.ones(
                [
                    (boundary_dilatation_distance * 2) + 1,
                    (boundary_dilatation_distance * 2) + 1,
                    (boundary_dilatation_distance * 2) + 1,
                ]
            ),
        )
        if self.keep_temp_properties:
            self.temp_msgc_lowres_discontinuity = seg
        else:
            self.temp_msgc_lowres_discontinuity = None

        if self.debug_images:
            import sed3

            pd = sed3.sed3(seg_border)  # ), contour=seg)
            pd.show()
            pd = sed3.sed3(seg)  # ), contour=seg)
            pd.show()
        # segzoom = scipy.ndimage.interpolation.zoom(seg.astype('float'), zoom,
        #                                                order=0).astype('int8')
        self.stats["t3"] = time.time() - start
        return seg
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
611612
def patStarLines(s0):
    ''''''
    arr = np.zeros((s0,s0), dtype=np.uint8)
    col = 255
    t = int(s0/100.)
    for pos in np.linspace(0,np.pi/2,15):
        
        p0 = int(round(np.sin(pos)*s0*2))
        p1 = int(round(np.cos(pos)*s0*2))
       
        cv2.line(arr,(0,0),(p0,p1), color=col, 
                   thickness=t, lineType=cv2.LINE_AA )
    return arr.astype(float)
68363
def get_surface_boundaries(self):
        
        mesh = self.mesh
        lons = numpy.concatenate((mesh.lons[0, :],
                                  mesh.lons[1:, -1],
                                  mesh.lons[-1, :-1][::-1],
                                  mesh.lons[:-1, 0][::-1]))
        lats = numpy.concatenate((mesh.lats[0, :],
                                  mesh.lats[1:, -1],
                                  mesh.lats[-1, :-1][::-1],
                                  mesh.lats[:-1, 0][::-1]))
        return [lons], [lats]
181867
def _fitImg(self, img):
        '''
        
        '''
        img = imread(img, 'gray')
        if self.bg is not None:
            img = cv2.subtract(img, self.bg)

        if self.lens is not None:
            img = self.lens.correct(img, keepSize=True)

        (H, _, _, _, _, _, _, n_matches) = self.findHomography(img)
        H_inv = self.invertHomography(H)

        s = self.obj_shape
        fit = cv2.warpPerspective(img, H_inv, (s[1], s[0]))
        return fit, img, H, H_inv, n_matches
1133076
def contours(*values)
		(values = (0..values[0]+1).to_a.map{|i| i.to_f * (@grid.max - @grid.min) / ( values[0]+1) + @grid.min}; values.pop; values.shift) if values.size==1 and values[0].kind_of? Integer
		cons = values.inject({}){|hash, val| hash[val] = []; hash}
		get_startpoints(cons)
		#@analysed = {}
		@found = {}
		#p cons
		starts = cons

		cons = values.inject({}){|hash, val| hash[val] = []; hash}
		temp_cons = values.inject({}){|hash, val| hash[val] = []; hash}
		starts.each do |val, arr|
			#p 'arr', arr
			arr.each do |start_con|
			#arr.map{|edges| edges[-1][1].slice(0..1)}.each do |starti, startj|
				starti, startj = start_con[-1][1].slice(0..1)	
				temp_cons[val] = [start_con]
				p 'startj',  starti, startj
				loop do
					starti, startj = trace_contour(val, temp_cons, starti, startj)
					break unless starti and startj
				end
				cons[val].push temp_cons[val][0]
			end
		end
		cons.keys.each{|val| cons[val] = connect_contours(cons[val]);
			cons[val].map!{|con| con.map{|point| point[0]}}}
		
		@last_contours = cons
		gk =  graphkit
		#gk.gp.style = 'data with linespoints'
		gk.data.each{|dk| dk.with = 'lp'}
		gk.gnuplot
		@last_contours
	end
1322098
def _deep_copy_contours(self, ufo, parent, component, transformation):
        """"""

        for nested in component.components:
            self._deep_copy_contours(
                ufo,
                parent,
                ufo[nested.baseGlyph],
                transformation.transform(nested.transformation),
            )

        if component != parent:
            pen = TransformPen(parent.getPen(), transformation)

            # if the transformation has a negative determinant, it will reverse
            # the contour direction of the component
            xx, xy, yx, yy = transformation[:4]
            if xx * yy - xy * yx < 0:
                pen = ReverseContourPen(pen)

            component.draw(pen)
722470
def narrow_to(self, featuremap):
        
        shape2d = tf.shape(featuremap)[2:]  # h,w
        slice3d = tf.concat([shape2d, [-1]], axis=0)
        slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
        boxes = tf.slice(self.boxes, [0, 0, 0, 0], slice4d)
        gt_labels = tf.slice(self.gt_labels, [0, 0, 0], slice3d)
        gt_boxes = tf.slice(self.gt_boxes, [0, 0, 0, 0], slice4d)
        return RPNAnchors(boxes, gt_labels, gt_boxes)
452127
def as_contours(self):
        """"""
        contours = dict()
        for byte_value in self.__byte_values:
            if byte_value == 0:
                continue
            mask = (self.__array == byte_value) * 255
            found_contours = find_contours(mask, 254, fully_connected='high') # a list of array
            contours[byte_value] = ContourSet(found_contours)
        return contours
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)
1341592
private void findCandidateShapes() {

		// find blobs where all 4 edges are lines
		List<ContourPacked> blobs = contourFinder.getContours();
		for (int i = 0; i < blobs.size(); i++) {
			ContourPacked c = blobs.get(i);

			contourTmp.reset();
			contourFinder.loadContour(c.externalIndex,contourTmp);
			if( contourTmp.size() >= minimumContour) {
				float edgeInside=-1,edgeOutside=-1;

//				System.out.println("----- candidate "+contourTmp.size()+"  "+contourTmp.get(0));

				// ignore shapes which touch the image border
				boolean touchesBorder = touchesBorder(contourTmp.toList());
				if( !canTouchBorder && touchesBorder ) {
					if( verbose ) System.out.println("rejected polygon, touched border");
					continue;
				}

				if( helper != null )
					if( !helper.filterContour(contourTmp.toList(),touchesBorder,true) )
						continue;

				// filter out contours which are noise
				if( contourEdgeIntensity != null ) {
					contourEdgeIntensity.process(contourTmp.toList(),true);
					edgeInside = contourEdgeIntensity.getInsideAverage();
					edgeOutside = contourEdgeIntensity.getOutsideAverage();

					// take the ABS because CCW/CW isn't known yet
					if( Math.abs(edgeOutside-edgeInside) < contourEdgeThreshold ) {
						if( verbose ) System.out.println("rejected polygon. contour edge intensity");
						continue;
					}
				}

				// remove lens distortion
				List<Point2D_I32> undistorted;
				if( distToUndist != null ) {
					undistorted = this.undistorted.toList();
					removeDistortionFromContour(contourTmp.toList(),this.undistorted);
					if( helper != null )
						if( !helper.filterContour(this.undistorted.toList(),touchesBorder,false) )
							continue;
				} else {
					undistorted = contourTmp.toList();
				}

				if( helper != null ) {
					helper.configureBeforePolyline(contourToPolyline,touchesBorder);
				}

				// Find the initial approximate fit of a polygon to the contour
				if( !contourToPolyline.process(undistorted,splits) ) {
					if( verbose ) System.out.println("rejected polygon initial fit failed. contour size = "+contourTmp.size());
					continue;
				}

				// determine the polygon's orientation
				polygonPixel.clear();
				for (int j = 0; j < splits.size; j++) {
					polygonPixel.add(undistorted.get(splits.get(j)));
				}

				boolean isCCW = UtilPolygons2D_I32.isCCW(polygonPixel);

				// Now that the orientation is known it can check to see if it's actually trying to fit to a
				// white blob instead of a black blob
				if( contourEdgeIntensity != null ) {
					// before it assumed it was CCW
					if( !isCCW ) {
						float tmp = edgeInside;
						edgeInside = edgeOutside;
						edgeOutside = tmp;
					}

					if( edgeInside > edgeOutside ) {
						if( verbose ) System.out.println("White blob. Rejected");
						continue;
					}
				}

				// see if it should be flipped so that the polygon has the correct orientation
				if( outputClockwise == isCCW ) {
					flip(splits.data,splits.size);
				}

				// convert the format of the initial crude polygon
				polygonWork.vertexes.resize(splits.size());
				polygonDistorted.vertexes.resize(splits.size());
				for (int j = 0; j < splits.size(); j++) {
					Point2D_I32 p = undistorted.get( splits.get(j) );
					Point2D_I32 q = contourTmp.get( splits.get(j));
					polygonWork.get(j).set(p.x,p.y);
					polygonDistorted.get(j).set(q.x,q.y);
				}

				if( touchesBorder ) {
					determineCornersOnBorder(polygonDistorted, borderCorners);
				} else {
					borderCorners.resize(0);
				}

				if( helper != null ) {
					if( !helper.filterPixelPolygon(polygonWork,polygonDistorted,borderCorners,touchesBorder) ) {
						if( verbose ) System.out.println("rejected by helper.filterPixelPolygon()");
						continue;
					}
				}

				// make sure it's big enough
				double area = Area2D_F64.polygonSimple(polygonWork);

				if( area < minimumArea ) {
					if( verbose ) System.out.println("Rejected area");
					continue;
				}

				// Get the storage for a new polygon. This is recycled and has already been cleaned up
				Info info = foundInfo.grow();

				if( distToUndist != null ) {
					// changed the save points in the packed contour list with undistorted coordinates
					contourFinder.writeContour(c.externalIndex,undistorted);
				}

				// save results
				info.splits.setTo(splits);
				info.contourTouchesBorder = touchesBorder;
				info.external = true;
				info.edgeInside = edgeInside;
				info.edgeOutside = edgeOutside;
				info.contour = c;
				info.polygon.set(polygonWork);
				info.polygonDistorted.set(polygonDistorted);
				info.borderCorners.setTo(borderCorners);
			}
		}
	}
17106
def combine_last_two_dimensions(x):
  
  x_shape = common_layers.shape_list(x)
  a, b = x_shape[-2:]
  return tf.reshape(x, x_shape[:-2] + [a * b])
1271246
def contourInside(self, otherContour):
        
        otherContour = normalizers.normalizeContour(otherContour)
        return self._contourInside(otherContour)
427887
def img(self):
        ''''''
        if self._img is not None:
            return self._img 
        self._img = cv2.cvtColor(self.original_img, cv2.COLOR_BGR2RGB)
        if self.border_width and self.border_colour is not None:
            cv2.rectangle(self._img, (0, 0), (self.width-1, self.height-1),
                          self.border_colour, self.border_width)
        return self._img
1058278
def getShape(self, includeJunctions=False):
        """"""
        if self._shape is None:
            self.rebuildShape()
        if includeJunctions:
            return self._shapeWithJunctions
        return self._shape