question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
When filling a grid with color such as when using contourf in pyplot, I need to find a way to change the color that pyplot uses to fill data that exceed the specified range of the colorbar. I wish to have a static colorbar that does not automatically change its range to fit the max/min of the data, so having occasional extreme values that exceed its bounds is inevitable, and colors need to be specified for such values. The default color for values exceeding the bounds of the colorbar is white, which can glaringly clash with the surrounding data if the colormap does not have white as its end colors. Example image is shown below - notice the white fill when values exceed the negative range of the colorbar: I believe there is a way to specify which color to use at each bound if they are exceeded by using rcParams, but I have not been able to find information on this anywhere. Any help would be appreciated.
The out-of-bounds colors can be set using the set_over and set_under methods of the colormap; see the documentation. You'll need to specify these values when you create your colormap. I don't see any matplotlibrc setting to set the default for this, though. You might also want to ask on the matplotlib mailing list. Edit: I see what is going on. The white area you describe is not beyond the limits of the color range. It is simply the blank background of the axes. Because you are only plotting certain levels, any levels outside that range will not be plotted at all, leaving those areas blank. To get what you want, do this: cs = pyplot.contourf(x,y,z,levels=np.arange(50, 220, 20), cmap=pyplot.cm.jet, extend="both") cs.cmap.set_under('k') cs.set_clim(50, 210) cb = pyplot.colorbar(cs) The "extend" argument is the key; it tells contourf to go ahead and plot all contours, but collapse all outside the given range into "too big" and "too small" categories. The cs.set_clim call is necessary to work around an oddity I discovered in contourf while debugging this; for some reason when you use extend, it manipulates the data limits, so we need to reset them back to what we want them to be. Also, just as a matter of style, you shouldn't be doing things like Colormap.set_under(cmap,color='k'). This is calling the class method and explicitly passing the instance in, which is an odd way to do it. Just do cmap.set_under(color="k").
Contour
11,386,054
26
I'm trying to find (but not draw!) contour lines for some data: from pprint import pprint import matplotlib.pyplot z = [[0.350087, 0.0590954, 0.002165], [0.144522, 0.885409, 0.378515], [0.027956, 0.777996, 0.602663], [0.138367, 0.182499, 0.460879], [0.357434, 0.297271, 0.587715]] cn = matplotlib.pyplot.contour(z) I know cn contains the contour lines I want, but I can't seem to get to them. I've tried several things: print dir(cn) pprint(cn.collections[0]) print dir(cn.collections[0]) pprint(cn.collections[0].figure) print dir(cn.collections[0].figure) to no avail. I know cn is a ContourSet, and cn.collections is an array of LineCollections. I would think a LineCollection is an array of line segments, but I can't figure out how to extract those segments. My ultimate goal is to create a KML file that plots data on a world map, and the contours for that data as well. However, since some of my data points are close together, and others are far away, I need the actual polygons (linestrings) that make up the contours, not just a rasterized image of the contours. I'm somewhat surprised qhull doesn't do something like this. Using Mathematica's ListContourPlot and then exporting as SVG works, but I want to use something open source. I can't use the well-known CONREC algorithm because my data isn't on a mesh (there aren't always multiple y values for a given x value, and vice versa). The solution doesn't have to python, but does have to be open source and runnable on Linux.
You can get the vertices back by looping over collections and paths and using the iter_segments() method of matplotlib.path.Path. Here's a function that returns the vertices as a set of nested lists of contour lines, contour sections and arrays of x,y vertices: import numpy as np def get_contour_verts(cn): contours = [] # for each contour line for cc in cn.collections: paths = [] # for each separate section of the contour line for pp in cc.get_paths(): xy = [] # for each segment of that section for vv in pp.iter_segments(): xy.append(vv[0]) paths.append(np.vstack(xy)) contours.append(paths) return contours Edit: It's also possible to compute the contours without plotting anything using the undocumented matplotlib._cntr C module: from matplotlib import pyplot as plt from matplotlib import _cntr as cntr z = np.array([[0.350087, 0.0590954, 0.002165], [0.144522, 0.885409, 0.378515], [0.027956, 0.777996, 0.602663], [0.138367, 0.182499, 0.460879], [0.357434, 0.297271, 0.587715]]) x, y = np.mgrid[:z.shape[0], :z.shape[1]] c = cntr.Cntr(x, y, z) # trace a contour at z == 0.5 res = c.trace(0.5) # result is a list of arrays of vertices and path codes # (see docs for matplotlib.path.Path) nseg = len(res) // 2 segments, codes = res[:nseg], res[nseg:] fig, ax = plt.subplots(1, 1) img = ax.imshow(z.T, origin='lower') plt.colorbar(img) ax.hold(True) p = plt.Polygon(segments[0], fill=False, color='w') ax.add_artist(p) plt.show()
Contour
18,304,722
25
I have a set of boundary points of an object. I want to draw it using opencv as contour. I have no idea that how to convert my points to contour representation. To the same contour representation which is obtained by following call contours,_ = cv2.findContours(image,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) Any ideas? Thanks
By looking at the format of the contours I would think something like this should be sufficient: contours = [numpy.array([[1,1],[10,50],[50,50]], dtype=numpy.int32) , numpy.array([[99,99],[99,60],[60,99]], dtype=numpy.int32)] This small program gives an running example: import numpy import cv2 contours = [numpy.array([[1,1],[10,50],[50,50]], dtype=numpy.int32) , numpy.array([[99,99],[99,60],[60,99]], dtype=numpy.int32)] drawing = numpy.zeros([100, 100],numpy.uint8) for cnt in contours: cv2.drawContours(drawing,[cnt],0,(255,255,255),2) cv2.imshow('output',drawing) cv2.waitKey(0)
Contour
14,161,331
25
I am trying to generate an image of a random contour using python but I couldn't find an easy way to do it. Here is an example sort of what I want: Initially I tought of doing it using matplotlib and gaussian functions, but I could not even get close to the image I showed. Is there a simple way to do it? I appreciate any help
The problem is that the kind of random shapes shown in the question is not truely random. They are somehow smoothed, ordered, seemingly random shapes. While creating truely random shapes is easy with the computer, creating those pseudo-random shapes is much easier done by using a pen and paper. One option is hence to create such shapes interactively. This is shown in the question Interactive BSpline fitting in Python . If you want to create random shapes programmatically, we may adapt the solution to How to connect points taking into consideration position and orientation of each of them using cubic Bezier curves. The idea is to create a set of random points via get_random_points and call a function get_bezier_curve with those. This creates a set of bezier curves which are smoothly connected to each other at the input points. We also make sure they are cyclic, i.e. that the transition between the start and end point is smooth as well. import numpy as np from scipy.special import binom import matplotlib.pyplot as plt bernstein = lambda n, k, t: binom(n,k)* t**k * (1.-t)**(n-k) def bezier(points, num=200): N = len(points) t = np.linspace(0, 1, num=num) curve = np.zeros((num, 2)) for i in range(N): curve += np.outer(bernstein(N - 1, i, t), points[i]) return curve class Segment(): def __init__(self, p1, p2, angle1, angle2, **kw): self.p1 = p1; self.p2 = p2 self.angle1 = angle1; self.angle2 = angle2 self.numpoints = kw.get("numpoints", 100) r = kw.get("r", 0.3) d = np.sqrt(np.sum((self.p2-self.p1)**2)) self.r = r*d self.p = np.zeros((4,2)) self.p[0,:] = self.p1[:] self.p[3,:] = self.p2[:] self.calc_intermediate_points(self.r) def calc_intermediate_points(self,r): self.p[1,:] = self.p1 + np.array([self.r*np.cos(self.angle1), self.r*np.sin(self.angle1)]) self.p[2,:] = self.p2 + np.array([self.r*np.cos(self.angle2+np.pi), self.r*np.sin(self.angle2+np.pi)]) self.curve = bezier(self.p,self.numpoints) def get_curve(points, **kw): segments = [] for i in range(len(points)-1): seg = Segment(points[i,:2], points[i+1,:2], points[i,2],points[i+1,2],**kw) segments.append(seg) curve = np.concatenate([s.curve for s in segments]) return segments, curve def ccw_sort(p): d = p-np.mean(p,axis=0) s = np.arctan2(d[:,0], d[:,1]) return p[np.argsort(s),:] def get_bezier_curve(a, rad=0.2, edgy=0): """ given an array of points *a*, create a curve through those points. *rad* is a number between 0 and 1 to steer the distance of control points. *edgy* is a parameter which controls how "edgy" the curve is, edgy=0 is smoothest.""" p = np.arctan(edgy)/np.pi+.5 a = ccw_sort(a) a = np.append(a, np.atleast_2d(a[0,:]), axis=0) d = np.diff(a, axis=0) ang = np.arctan2(d[:,1],d[:,0]) f = lambda ang : (ang>=0)*ang + (ang<0)*(ang+2*np.pi) ang = f(ang) ang1 = ang ang2 = np.roll(ang,1) ang = p*ang1 + (1-p)*ang2 + (np.abs(ang2-ang1) > np.pi )*np.pi ang = np.append(ang, [ang[0]]) a = np.append(a, np.atleast_2d(ang).T, axis=1) s, c = get_curve(a, r=rad, method="var") x,y = c.T return x,y, a def get_random_points(n=5, scale=0.8, mindst=None, rec=0): """ create n random points in the unit square, which are *mindst* apart, then scale them.""" mindst = mindst or .7/n a = np.random.rand(n,2) d = np.sqrt(np.sum(np.diff(ccw_sort(a), axis=0), axis=1)**2) if np.all(d >= mindst) or rec>=200: return a*scale else: return get_random_points(n=n, scale=scale, mindst=mindst, rec=rec+1) You may use those functions e.g. as fig, ax = plt.subplots() ax.set_aspect("equal") rad = 0.2 edgy = 0.05 for c in np.array([[0,0], [0,1], [1,0], [1,1]]): a = get_random_points(n=7, scale=1) + c x,y, _ = get_bezier_curve(a,rad=rad, edgy=edgy) plt.plot(x,y) plt.show() We may check how the parameters influence the result. There are essentially 3 parameters to use here: rad, the radius around the points at which the control points of the bezier curve sit. This number is relative to the distance between adjacent points and should hence be between 0 and 1. The larger the radius, the sharper the features of the curve. edgy, a parameter to determine the smoothness of the curve. If 0 the angle of the curve through each point will be the mean between the direction to adjacent points. The larger it gets, the more the angle will be determined only by one adjacent point. The curve hence gets "edgier". n the number of random points to use. Of course the minimum number of points is 3. The more points you use, the more feature rich the shapes can become; at the risk of creating overlaps or loops in the curve.
Contour
50,731,785
24
I am working with openCv and python and I am dealing with Structural Analysis and Shape Descriptors. I have found this blog: http://opencvpython.blogspot.it/2012/06/contours-2-brotherhood.html that's very helpful and I have tried with a black and white image to drawing a bounding rectangle and it works. But now from an image i extract, for example, the yellow color and on that i would like to draw a bounding rectangle. The problem is that the black and white image is not uniform it has some noise and like that the code doesn't recognize the whole shape. And this is the code: import numpy as np import cv2 im = cv2.imread('shot.bmp') hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) COLOR_MIN = np.array([20, 80, 80],np.uint8) COLOR_MAX = np.array([40, 255, 255],np.uint8) frame_threshed = cv2.inRange(hsv_img, COLOR_MIN, COLOR_MAX) imgray = frame_threshed ret,thresh = cv2.threshold(frame_threshed,127,255,0) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cnt=contours[0] x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow("Show",im) cv2.waitKey() cv2.destroyAllWindows()
Since your original image is fairly noisy, a simple fix is to remove some of the noise using cv2.medianBlur() This will remove small noise areas in your original image, and leave you with only one contour. The first few lines of your code would look like this: im = cv2.imread('shot.bmp') im = cv2.medianBlur(im,5) # 5 is a fairly small kernel size hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) However, this method is not the most robust because you must manually specify a kernel size, and the line cnt=contours[0] in your code assumes that the contour of interest is the firs in the list of contours, which is only true if there is only one contour. A more robust method is to assume that you are interested in the largest contour, which will allow you to compensate for even moderate noise. To do this, add the lines: # Find the index of the largest contour areas = [cv2.contourArea(c) for c in contours] max_index = np.argmax(areas) cnt=contours[max_index] after the line: contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) Resulting in this code: import numpy as np import cv2 im = cv2.imread('shot.bmp') hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) COLOR_MIN = np.array([20, 80, 80],np.uint8) COLOR_MAX = np.array([40, 255, 255],np.uint8) frame_threshed = cv2.inRange(hsv_img, COLOR_MIN, COLOR_MAX) imgray = frame_threshed ret,thresh = cv2.threshold(frame_threshed,127,255,0) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # Find the index of the largest contour areas = [cv2.contourArea(c) for c in contours] max_index = np.argmax(areas) cnt=contours[max_index] x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow("Show",im) cv2.waitKey() cv2.destroyAllWindows() Both of these methods give a result with a correct bounding box: N.B. As of OpenCV 3.x the findContours() method returns 3 results (as can be seen here), so the additional return value should be caught like: _, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPL‌​E)
Contour
16,538,774
23
I would like to control the location of matplotlib clabels on a contour plot, but without utilizing the manual=True flag in clabel. For example, I would like to specify an x-coordinate, and have labels created at the points that pass through this line. I see that you can get the location of the individual labels using get_position(), but I am stuck at that. Any help would be greatly appreciated. Thanks!
Yes, there now is a way to control label locations! https://github.com/matplotlib/matplotlib/pull/642 plt.figure() CS = plt.contour(X, Y, Z) manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)] plt.clabel(CS, inline=1, fontsize=10, manual=manual_locations)
Contour
2,791,445
23
I'm using OpenCV 3.0.0 on Python 2.7.9. I'm trying to track an object in a video with a still background, and estimate some of its properties. Since there can be multiple moving objects in an image, I want to be able to differentiate between them and track them individually throughout the remaining frames of the video. One way I thought I could do that was by converting the image to binary, getting the contours of the blobs (tracked object, in this case) and get the coordinates of the object boundary. Then I can go to these boundary coordinates in the grayscale image, get the pixel intensities surrounded by that boundary, and track this color gradient/pixel intensities in the other frames. This way, I could keep two objects separate from each other, so they won't be considered as new objects in the next frame. I have the contour boundary coordinates, but I don't know how to retrieve the pixel intensities within that boundary. Could someone please help me with that? Thanks!
Going with our comments, what you can do is create a list of numpy arrays, where each element is the intensities that describe the interior of the contour of each object. Specifically, for each contour, create a binary mask that fills in the interior of the contour, find the (x,y) coordinates of the filled in object, then index into your image and grab the intensities. I don't know exactly how you set up your code, but let's assume you have an image that's grayscale called img. You may need to convert the image to grayscale because cv2.findContours works on grayscale images. With this, call cv2.findContours normally: import cv2 import numpy as np #... Put your other code here.... #.... # Call if necessary #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Call cv2.findContours contours,_ = cv2.findContours(img, cv2.RETR_LIST, cv2.cv.CV_CHAIN_APPROX_NONE) contours is now a list of 3D numpy arrays where each is of size N x 1 x 2 where N is the total number of contour points for each object. As such, you can create our list like so: # Initialize empty list lst_intensities = [] # For each list of contour points... for i in range(len(contours)): # Create a mask image that contains the contour filled in cimg = np.zeros_like(img) cv2.drawContours(cimg, contours, i, color=255, thickness=-1) # Access the image pixels and create a 1D numpy array then add to list pts = np.where(cimg == 255) lst_intensities.append(img[pts[0], pts[1]]) For each contour, we create a blank image then draw the filled-in contour in this blank image. You can fill in the area that the contour occupies by specifying the thickness parameter to be -1. I set the interior of the contour to 255. After, we use numpy.where to find all row and column locations in an array that match a certain condition. In our case, we want to find the values that are equal to 255. After, we use these points to index into our image to grab the pixel intensities that are interior to the contour. lst_intensities contains that list of 1D numpy arrays where each element gives you the intensities that belong to the interior of the contour of each object. To access each array, simply do lst_intensities[i] where i is the contour you want to access.
Contour
33,234,363
21
I need to add lines via stat_contour() to my ggplot/ggplot2-plot. Unfortunately, I can not give you the real data from which point values should be evaluated. However, another easily repreducably example behaves the same: testPts <- data.frame(x=rep(seq(7.08, 7.14, by=0.005), 200)) testPts$y <- runif(length(testPts$x), 50.93, 50.96) testPts$z <- sin(testPts$y * 500) ggplot(data=testPts, aes(x=x, y=y, z=z)) + geom_point(aes(colour=z)) + stat_contour() This results in the following error message: Error in if (nrow(layer_data) == 0) return() : argument is of length zero In addition: Warning message: Not possible to generate contour data The example looks not different from others posted on stackoverflow or in the official manual/tutorial to me, and it seemingly doesn't matter if I provide more specifications to stat_contour. It seems the function does not pass the data(-layer) as pointed ou tint the error message.
Use stat_density2d instead of stat_contour with irregularly spaced data. library(ggplot2) testPts <- data.frame(x=rep(seq(7.08, 7.14, by=0.005), 200)) testPts$y <- runif(length(testPts$x), 50.93, 50.96) testPts$z <- sin(testPts$y * 500) (ggplot(data=testPts, aes(x=x, y=y, z=z)) + geom_point(aes(colour=z)) + stat_density2d() )
Contour
19,065,290
21
I am trying to implement the algorithm found here in python with OpenCV. I am trying to implement the part of the algorithm that remove irrelevant edge boundaries based on the number of interior boundaries that they have. If the current edge boundary has exactly one or two interior edge boundaries, the internal boundaries can be ignored If the current edge boundary has more than two interior edge boundaries, it can be ignored I am having trouble determining the tree structure of the contours I have extracted from the image. My current source: import cv2 # Load the image img = cv2.imread('test.png') cv2.copyMakeBorder(img, 50,50,50,50,cv2.BORDER_CONSTANT, img, (255,255,255)) # Split out each channel blue = cv2.split(img)[0] green = cv2.split(img)[1] red = cv2.split(img)[2] # Run canny edge detection on each channel blue_edges = cv2.Canny(blue, 1, 255) green_edges = cv2.Canny(green, 1, 255) red_edges = cv2.Canny(red, 1, 255) # Join edges back into image edges = blue_edges | green_edges | red_edges # Find the contours contours,hierarchy = cv2.findContours(edges.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # For each contour, find the bounding rectangle and draw it for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(edges,(x,y),(x+w,y+h),(200,200,200),2) # Finally show the image cv2.imshow('img',edges) cv2.waitKey(0) cv2.destroyAllWindows() I assumed that using cv2.RETR_TREE would give me a nice nested array of the contours but that doesn't seem to be the case. How do I retrieve the tree structure of my contours?
The main confusion here is probably the fact that the hierarchy returned is a numpy array with more dimensions than necessary. On top of that, it looks like the Python FindContours function returns a tuple that is a LIST of contours, and and NDARRAY of the hierarchy... You can get a sensible array of hierarchy information that is more in line with the C docs by just taking hierarchy[0]. It would then be an appropriate shape to zip, for example, with the contours. Below is an example that, will draw the outermost rectangles in green and the innermost rectangles in red on this image: Output: Note, by the way, that the wording in the OpenCV docs is a little ambiguous, but hierarchyDataOfAContour[2] describes the children of that contour (if it is negative then that is an inner contour), and hierarchyDataOfAContour[3] describes the parents of that contour (if it is negative then that is an exterior contour). Also note: I looked into implementing the algorithm that you referred to in the OCR paper, and I saw that FindContours was giving me a lot of repeats of near-identical contours. This would complicate the finding of "Edge Boxes" as the paper describes. This may be because the Canny thresholds were too low (note that I was playing around with them as described in the paper), but there may be some way to reduce that effect or just look at the average deviation of the four corners of all the boxes and eliminate duplicates... import cv2 import numpy # Load the image img = cv2.imread("/ContourTest.PNG") # Split out each channel blue, green, red = cv2.split(img) def medianCanny(img, thresh1, thresh2): median = numpy.median(img) img = cv2.Canny(img, int(thresh1 * median), int(thresh2 * median)) return img # Run canny edge detection on each channel blue_edges = medianCanny(blue, 0.2, 0.3) green_edges = medianCanny(green, 0.2, 0.3) red_edges = medianCanny(red, 0.2, 0.3) # Join edges back into image edges = blue_edges | green_edges | red_edges # Find the contours contours,hierarchy = cv2.findContours(edges, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) hierarchy = hierarchy[0] # get the actual inner list of hierarchy descriptions # For each contour, find the bounding rectangle and draw it for component in zip(contours, hierarchy): currentContour = component[0] currentHierarchy = component[1] x,y,w,h = cv2.boundingRect(currentContour) if currentHierarchy[2] < 0: # these are the innermost child components cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),3) elif currentHierarchy[3] < 0: # these are the outermost parent components cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3) # Finally show the image cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows()
Contour
11,782,147
21
My task is to detect the cracks on the soil surface and calculate crack's total area. I used Canny edge detection for this purpose. Input image Result My next step is to convert canny edges to contours since I want to filtrate the cracks using cv2.mean and calculate their area using cv2.contourArea functions. On this step, I faced the problem. When I used: canny_cracks = cv2.Canny(gray, 100, 200) contours, _ = cv2.findContours(canny_cracks, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) It does not convert properly because of the holes the ends of edges. See problem here My question is how can I connect the ends of edges in order to close the hole between them? Note: I used contours detection without applying Canny edges. The problem is that contours detection gives a lot of noise and doesn't detect all cracks well. Or maybe I do not know how to find contours as canny edges do.
Starting from your 2nd provided image, here's my approach to solving this problem: Gaussian blur image and convert to grayscale Isolate soil from pot Create circle mask of just the soil Extract soil ROI Perform morphological transformations to close holes Find contours and filter by contour area Sum area to obtain result We begin by Gaussian blurring and converting the image to grayscale. image = cv2.imread('5.png') original = image.copy() blur = cv2.GaussianBlur(image, (3,3), 0) gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5)) The goal is to isolate the soil edges from the pot edges. To do this, we find the outer circle of the pot using cv2.HoughCircles(), scale down the circle to grab the soil region, and create a mask using the shape of the original image. circle_mask = np.zeros(original.shape, dtype=np.uint8) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.5, 200) # Convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") circle_ratio = 0.85 # Loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: # Draw the circle, create mask, and obtain soil ROI cv2.circle(image, (x, y), int(r * circle_ratio), (0, 255, 0), 2) cv2.circle(circle_mask, (x, y), int(r * circle_ratio), (255, 255, 255), -1) soil_ROI = cv2.bitwise_and(original, circle_mask) We loop over coordinates to find the radius of the circle. From here we draw the largest outer circle. Now to isolate the soil and the pot, we apply a scaling factor to obtain this Next, we fill in the circle to obtain a mask and then apply that on the original image to obtain the soil ROI. Soil mask Soil ROI Your question was How can I connect the ends of edges in order to close the hole between them? To do this, you can perform a morphological transformation using cv2.morphologyEx() to close holes which results in this gray_soil_ROI = cv2.cvtColor(soil_ROI, cv2.COLOR_BGR2GRAY) close = cv2.morphologyEx(gray_soil_ROI, cv2.MORPH_CLOSE, kernel) Now we find contours using cv2.findContours() and filter using cv2.contourArea() with a minimum threshold area to remove small noise such as the rocks. You can adjust the minimum area to control filter strength. cnts = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] crack_area = 0 minumum_area = 25 for c in cnts: area = cv2.contourArea(c) if area > minumum_area: cv2.drawContours(original,[c], 0, (36,255,12), 2) crack_area += area Finally, we sum the area which gives us the crack's total area 3483.5 import cv2 import numpy as np image = cv2.imread('5.png') original = image.copy() blur = cv2.GaussianBlur(image, (3,3), 0) gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5)) circle_mask = np.zeros(original.shape, dtype=np.uint8) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.5, 200) # Convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") circle_ratio = 0.85 # Loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: # Draw the circle, create mask, and obtain soil ROI cv2.circle(image, (x, y), int(r * circle_ratio), (0, 255, 0), 2) cv2.circle(circle_mask, (x, y), int(r * circle_ratio), (255, 255, 255), -1) soil_ROI = cv2.bitwise_and(original, circle_mask) gray_soil_ROI = cv2.cvtColor(soil_ROI, cv2.COLOR_BGR2GRAY) close = cv2.morphologyEx(gray_soil_ROI, cv2.MORPH_CLOSE, kernel) cnts = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] crack_area = 0 minumum_area = 25 for c in cnts: area = cv2.contourArea(c) if area > minumum_area: cv2.drawContours(original,[c], 0, (36,255,12), 2) crack_area += area print(crack_area) cv2.imshow('close', close) cv2.imshow('circle_mask', circle_mask) cv2.imshow('soil_ROI', soil_ROI) cv2.imshow('original', original) cv2.waitKey(0)
Contour
56,754,451
19
I have found the following code on this website: import os import os.path import cv2 import glob import imutils CAPTCHA_IMAGE_FOLDER = "generated_captcha_images" OUTPUT_FOLDER = "extracted_letter_images" # Get a list of all the captcha images we need to process captcha_image_files = glob.glob(os.path.join(CAPTCHA_IMAGE_FOLDER, "*")) counts = {} # loop over the image paths for (i, captcha_image_file) in enumerate(captcha_image_files): print("[INFO] processing image {}/{}".format(i + 1, len(captcha_image_files))) # Since the filename contains the captcha text (i.e. "2A2X.png" has the text "2A2X"), # grab the base filename as the text filename = os.path.basename(captcha_image_file) captcha_correct_text = os.path.splitext(filename)[0] # Load the image and convert it to grayscale image = cv2.imread(captcha_image_file) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Add some extra padding around the image gray = cv2.copyMakeBorder(gray, 8, 8, 8, 8, cv2.BORDER_REPLICATE) # threshold the image (convert it to pure black and white) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] # find the contours (continuous blobs of pixels) the image contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Hack for compatibility with different OpenCV versions contours = contours[0] if imutils.is_cv2() else contours[1] letter_image_regions = [] # Now we can loop through each of the four contours and extract the letter # inside of each one for contour in contours: # Get the rectangle that contains the contour (x, y, w, h) = cv2.boundingRect(contour) # Compare the width and height of the contour to detect letters that # are conjoined into one chunk if w / h > 1.25: # This contour is too wide to be a single letter! # Split it in half into two letter regions! half_width = int(w / 2) letter_image_regions.append((x, y, half_width, h)) letter_image_regions.append((x + half_width, y, half_width, h)) else: # This is a normal letter by itself letter_image_regions.append((x, y, w, h)) # If we found more or less than 4 letters in the captcha, our letter extraction # didn't work correcly. Skip the image instead of saving bad training data! if len(letter_image_regions) != 4: continue # Sort the detected letter images based on the x coordinate to make sure # we are processing them from left-to-right so we match the right image # with the right letter letter_image_regions = sorted(letter_image_regions, key=lambda x: x[0]) # Save out each letter as a single image for letter_bounding_box, letter_text in zip(letter_image_regions, captcha_correct_text): # Grab the coordinates of the letter in the image x, y, w, h = letter_bounding_box # Extract the letter from the original image with a 2-pixel margin around the edge letter_image = gray[y - 2:y + h + 2, x - 2:x + w + 2] # Get the folder to save the image in save_path = os.path.join(OUTPUT_FOLDER, letter_text) # if the output directory does not exist, create it if not os.path.exists(save_path): os.makedirs(save_path) # write the letter image to a file count = counts.get(letter_text, 1) p = os.path.join(save_path, "{}.png".format(str(count).zfill(6))) cv2.imwrite(p, letter_image) # increment the count for the current key counts[letter_text] = count + 1 When I try to run the code I get the following error: [INFO] processing image 1/9955 Traceback (most recent call last): File "extract_single_letters_from_captchas.py", line 47, in <module> (x, y, w, h) = cv2.boundingRect(contour) cv2.error: OpenCV(4.0.0) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/shapedescr.cpp:741: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'pointSetBoundingRect' I've tried searching for a solution on StackOverflow, but I didn't find anything remotely similar. EDIT (see comments): type(contour[0]) = <class 'numpy.ndarray'> len(contour) = 4
This is doing the wrong thing: contours = contours[0] if imutils.is_cv2() else contours[1] imutils.is_cv2() is returning False even though it should return True. If you don't mind to remove this dependency, change to: contours = contours[0] I found out the reason. Probably, the tutorial you are following was published before OpenCV 4 was released. OpenCV 3 changed cv2.findContours(...) to return image, contours, hierarchy, while OpenCV 2's cv2.findContours(...) and OpenCV 4's cv2.findContours(...) return contours, hierarchy. Therefore, before OpenCV 4, it was correct to say that if you use OpenCV 2 it should be contours[0] else contours[1]. If you still want to have this "compatibility", you can change to: contours = contours[1] if imutils.is_cv3() else contours[0]
Contour
54,734,538
19
I have drawn a contour around extreme points. Inside polygon figure I have others points. How to check if they are inside contour?
You can use the cv2.pointPolygonTest() function available in OpenCV. For example: dist = cv2.pointPolygonTest(cnt,(50,50),True) In this example we are checking whether the coordinate (50, 50) is present withing the contour cnt dist returns one of the following three: Positive value if the point is inside the contour Negative value if the point is outside the contour Zero if the point is on the contour Within the function cv2.pointPolygonTest() the third parameter decides whether you want one of the following two : If it is True, dist returns either the positive or negative distance of the point, if it is either inside or outside the contour respectively. On the other hand, if it is set to False, it returns +1, -1 or 0 depending on the point lying inside, outside or on the contour respectively See THE DOCS for more details Illustration: I added an example to show how it works. I considered the following image for which a contour was obtained: I assumed the following points to be used as illustration: (50, 70), (170, 152), (152, 48) dist1 = cv2.pointPolygonTest(contours[0], (50, 70), True) #green dist2 = cv2.pointPolygonTest(contours[0], (170, 152), True) #blue dist3 = cv2.pointPolygonTest(contours[0], (152, 48), True) #red print('dist1 : ', dist1) print('dist2 : ', dist2) print('dist3 : ', dist3) Output: ('dist1 : ', -45.17742799230607) ('dist2 : ', 49.9799959983992) ('dist3 : ', -0.0)
Contour
50,670,326
19
I am using OpenCV's cv::findContours function to extract contours in a binary image, in particular, I'm extracting a hierarchy of contours (using the CV_RETR_CCOMP flag). At some point in my further processing of those contours I need to rely on a consistent vertex orientation of these contours (i.e. counter-clockwise vs. clockwise). Of course I can just determine that orientation myself using the sign of the contour's area (as computed by cv::contourArea(..., true)), but I wonder if that is even necessary (besides that, it won't even work for contours with an area of 0, i.e. thin lines in the source image) or if cv::findContours already guarantees a consistent orientation for the generated contours. I did check a few of the generated contours and cv::contourArea does indeed seem to return negative values for outer contours and positive values for inner contours. However, I couldn't find any actual guarantee to this effect in the OpenCV documentation. So, is it specifically guaranteed that the contours returned by cv::findContours always have a consistent orientation? Is this documented anywhere? Or does it vary by version (mine is 2.4.5 for that matter)? Does the actual paper on the algorithm referenced in the documentation already say something about this? Or maybe someone with a little more insight into the actual implementation of OpenCV can say a little more about this than the interface documentation can?
The contours returned from cv:findContours should have a consistent orientation. Outer contours should be oriented counter-clockwise, inner contours clockwise. This follows directly from the algorithm described in Appendix 1 of Suzuki's and Abe's paper. The image is scanned line by line from top left to bottom right. When a pixel belonging to a border is found, the border is followed by looking at the neighbours of the first pixel in counter-clockwise order (see step 3.3 in the algorithm), until a non-background pixel is found. This is added to the contour and the search continues from this pixel. The important thing is that in the first iteration the neighbour which is first looked at depends on whether it is an inner or an outer border. In case of an outer border the right-hand neighbour is visited first; in case of an inner border it is the left-hand neighbour. In the next search step the search starts from the last pixel visited. Due to the scanning happing from top left to bottom right, on detection of an outer border it is assured that all neighbouring pixels to the left and the top of the border pixel are background pixels. With inner border, it is exactly the opposite, all neighbours to the left and the top are non-background pixels. In combination with the different starting positions for visiting the neighbouring pixels this results in predictable orientations of the contours. This algorithm is implemented in the icvFetchContour function which is used internally by cv:findContour. From there it is clear that the pixel are added to the contour polygon in the order in which they are visited. As the documentation for cv::findContours specifically says that they implemented the algorithm by Suzuki et al. and as in this paper the direction and order for visiting the pixels is explicitely defined, I think one can assume that the orientation is kind of guaranteed.
Contour
45,323,590
18
The matplotlib.pyplot.contour() function takes 3 input arrays X, Y and Z. The arrays X and Y specify the x- and y-coordinates of points, while Z specifies the corresponding value of the function of interest evaluated at the points. I understand that np.meshgrid() makes it easy to produce arrays which serve as arguments to contour(): X = np.arange(0,5,0.01) Y = np.arange(0,3,0.01) X_grid, Y_grid = np.meshgrid(X,Y) Z_grid = X_grid**2 + Y_grid**2 plt.contour(X_grid, Y_grid, Z_grid) # Works fine This works fine. And conveniently, this works fine too: plt.contour(X, Y, Z_grid) # Works fine too However, why is the Z input required to be a 2D-array? Why is something like the following disallowed, even though it specifies all the same data aligned appropriately? plt.contour(X_grid.ravel(), Y_grid.ravel(), Z_grid.ravel()) # Disallowed Also, what are the semantics when only Z is specified (without the corresponding X and Y)?
Looking at the documentation of contour one finds that there are a couple of ways to call this function, e.g. contour(Z) or contour(X,Y,Z). So you'll find that it does not require any X or Y values to be present at all. However in order to plot a contour, the underlying grid must be known to the function. Matplotlib's contour is based on a rectangular grid. But even so, allowing contour(z), with z being a 1D array, would make it impossible to know how the field should be plotted. In the case of contour(Z) where Z is a 2D array, its shape unambiguously sets the grid for the plot. Once that grid is known, it is rather unimportant whether optional X and Y arrays are flattened or not; which is actually what the documentation tells us: X and Y must both be 2-D with the same shape as Z, or they must both be 1-D such that len(X) is the number of columns in Z and len(Y) is the number of rows in Z. It is also pretty obvious that someting like plt.contour(X_grid.ravel(), Y_grid.ravel(), Z_grid.ravel()) cannot produce a contour plot, because all the information about the grid shape is lost and there is no way the contour function could know how to interprete the data. E.g. if len(Z_grid.ravel()) == 12, the underlying grid's shape could be any of (1,12), (2,6), (3,4), (4,3), (6,2), (12,1). A possible way out could of course be to allow for 1D arrays and introduce an argument shape, like plt.contour(x,y,z, shape=(6,2)). This however is not the case, so you have to live with the fact that Z needs to be 2D. However, if you are looking for a way to obtain a countour plot with flattened (ravelled) arrays, this is possible using plt.tricontour(). plt.tricontour(X_grid.ravel(), Y_grid.ravel(), Z_grid.ravel()) Here a triangular grid will be produced internally using a Delaunay Triangualation. Therefore even completely randomized points will produce a nice result, as can be seen in the following picture, where this is compared to the same random points given to contour. (Here is the code to produce this picture)
Contour
42,045,921
18
I am stuck with a (hopefully) simple problem. My aim is to plot a dashed line interrupted with data (not only text). As I only found out to create a dashed line via linestyle = 'dashed', any help is appreciated to put the data between the dashes. Something similar, regarding the labeling, is already existing with Matplotlib - as I saw in the contour line demo. Update: The question link mentioned by Richard in comments was very helpful, but not the 100% like I mentioned via comment. Currently, I do it this way: line_string2 = '-10 ' + u"\u00b0" +"C" l, = ax1.plot(T_m10_X_Values,T_m10_Y_Values) pos = [(T_m10_X_Values[-2]+T_m10_X_Values[-1])/2., (T_m10_Y_Values[-2]+T_m10_Y_Values[-1])/2.] # transform data points to screen space xscreen = ax1.transData.transform(zip(T_m10_Y_Values[-2::],T_m10_Y_Values[-2::])) rot = np.rad2deg(np.arctan2(*np.abs(np.gradient(xscreen)[0][0][::-1]))) ltex = plt.text(pos[0], pos[1], line_string2, size=9, rotation=rot, color='b',ha="center", va="bottom",bbox = dict(ec='1',fc='1', alpha=0.5)) Here you can see a snapshot of the result. The minus 20°C is without BBox.
Quick and dirty answer using annotate: import matplotlib.pyplot as plt import numpy as np x = list(reversed([1.81,1.715,1.78,1.613,1.629,1.714,1.62,1.738,1.495,1.669,1.57,1.877,1.385])) y = [0.924,0.915,0.914,0.91,0.909,0.905,0.905,0.893,0.886,0.881,0.873,0.873,0.844] def plot_with_text(x, y, text, text_count=None): text_count = (2 * (len(x) / len(text))) if text_count is None else text_count fig, ax = plt.subplots(1,1) l, = ax.plot(x,y) text_size = len(text) * 10 idx_step = len(x) / text_count for idx_num in range(text_count): idx = int(idx_num * idx_step) text_pos = [x[idx], y[idx]] xscreen = ax.transData.transform(zip(x[max(0, idx-1):min(len(x), idx+2)], y[max(0, idx-1):min(len(y), idx+2)])) a = np.abs(np.gradient(xscreen)[0][0]) rot = np.rad2deg(np.arctan2(*a)) - 90 ax.annotate(text, xy=text_pos, color="r", bbox=dict(ec="1", fc="1", alpha=0.9), rotation=rot, ha="center", va="center") plot_with_text(x, y, "test") Yields: You can play with the offsets for more pleasing results.
Contour
31,720,714
18
I have used an adaptive thresholding technique to create a picture like the one below: The code I used was: image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 45, 0) Then, I use this code to get contours: cnt = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0] My goal is to generate a mask using all the pixels within the outer contour, so I want to fill in all pixels within the object to be white. How can I do this? I have tried the code below to create a mask, but the resulting mask seems no different then the image after applying adaptive threshold mask = np.zeros(image.shape[:2], np.uint8) cv2.drawContours(mask, cnt, -1, 255, -1)
What you have is almost correct. If you take a look at your thresholded image, the reason why it isn't working is because your shoe object has gaps in the image. Specifically, what you're after is that you expect that the shoe has its perimeter to be all connected. If this were to happen, then if you extract the most external contour (which is what your code is doing), you should only have one contour which represents the outer perimeter of the object. Once you fill in the contour, then your shoe should be completely solid. Because the perimeter of your shoe is not complete and broken, this results in disconnected white regions. Should you use findContours to find all of the contours, it will only find the contours of each of the white shapes and not the most outer perimeter. As such, if you try and use findContours, it'll give you the same result as the original image, because you're simply finding the perimeter of each white region inside the image, then filling in these regions with findContours. What you need to do is ensure that the image is completely closed. What I would recommend you do is use morphology to close all of the disconnected regions together, then run a findContours call on this new image. Specifically, perform a binary morphological closing. What this does is that it takes disconnected white regions that are close together and ensures that they're connected. Use a morphological closing, and perhaps use something like a 7 x 7 square structuring element to close the shoe. This structuring element you can think of as the minimum separation between white regions to consider them as being connected. As such, do something like this: import numpy as np import cv2 image = cv2.imread('...') # Load your image in here # Your code to threshold image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 45, 0) # Perform morphology se = np.ones((7,7), dtype='uint8') image_close = cv2.morphologyEx(image, cv2.MORPH_CLOSE, se) # Your code now applied to the closed image cnt = cv2.findContours(image_close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0] mask = np.zeros(image.shape[:2], np.uint8) cv2.drawContours(mask, cnt, -1, 255, -1) This code essentially takes your thresholded image, and applies morphological closing to this image. After, we find the external contours of this image, and fill them in with white. FWIW, I downloaded your thresholded image, and tried this on my own. This is what I get with your image:
Contour
27,299,405
18
I better explain my problem with an Image I have a contour and a line which is passing through that contour. At the intersection point of contour and line I want to draw a perpendicular line at the intersection point of a line and contour up to a particular distance. I know the intersection point as well as slope of the line. For reference I am attaching this Image.
If the blue line in your picture goes from point A to point B, and you want to draw the red line at point B, you can do the following: Get the direction vector going from A to B. This would be: v.x = B.x - A.x; v.y = B.y - A.y; Normalize the vector: mag = sqrt (v.x*v.x + v.y*v.y); v.x = v.x / mag; v.y = v.y / mag; Rotate the vector 90 degrees by swapping x and y, and inverting one of them. Note about the rotation direction: In OpenCV and image processing in general x and y axis on the image are not oriented in the Euclidian way, in particular the y axis points down and not up. In Euclidian, inverting the final x (initial y) would rotate counterclockwise (standard for euclidean), and inverting y would rotate clockwise. In OpenCV it's the opposite. So, for example to get clockwise rotation in OpenCV: temp = v.x; v.x = -v.y; v.y = temp; Create a new line at B pointing in the direction of v: C.x = B.x + v.x * length; C.y = B.y + v.y * length; (Note that you can make it extend in both directions by creating a point D in the opposite direction by simply negating length.)
Contour
8,664,866
18
I have a massive scatterplot (~100,000 points) that I'm generating in matplotlib. Each point has a location in this x/y space, and I'd like to generate contours containing certain percentiles of the total number of points. Is there a function in matplotlib which will do this? I've looked into contour(), but I'd have to write my own function to work in this way. Thanks!
Basically, you're wanting a density estimate of some sort. There multiple ways to do this: Use a 2D histogram of some sort (e.g. matplotlib.pyplot.hist2d or matplotlib.pyplot.hexbin) (You could also display the results as contours--just use numpy.histogram2d and then contour the resulting array.) Make a kernel-density estimate (KDE) and contour the results. A KDE is essentially a smoothed histogram. Instead of a point falling into a particular bin, it adds a weight to surrounding bins (usually in the shape of a gaussian "bell curve"). Using a 2D histogram is simple and easy to understand, but fundementally gives "blocky" results. There are some wrinkles to doing the second one "correctly" (i.e. there's no one correct way). I won't go into the details here, but if you want to interpret the results statistically, you need to read up on it (particularly the bandwidth selection). At any rate, here's an example of the differences. I'm going to plot each one similarly, so I won't use contours, but you could just as easily plot the 2D histogram or gaussian KDE using a contour plot: import numpy as np import matplotlib.pyplot as plt from scipy.stats import kde np.random.seed(1977) # Generate 200 correlated x,y points data = np.random.multivariate_normal([0, 0], [[1, 0.5], [0.5, 3]], 200) x, y = data.T nbins = 20 fig, axes = plt.subplots(ncols=2, nrows=2, sharex=True, sharey=True) axes[0, 0].set_title('Scatterplot') axes[0, 0].plot(x, y, 'ko') axes[0, 1].set_title('Hexbin plot') axes[0, 1].hexbin(x, y, gridsize=nbins) axes[1, 0].set_title('2D Histogram') axes[1, 0].hist2d(x, y, bins=nbins) # Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents k = kde.gaussian_kde(data.T) xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j] zi = k(np.vstack([xi.flatten(), yi.flatten()])) axes[1, 1].set_title('Gaussian KDE') axes[1, 1].pcolormesh(xi, yi, zi.reshape(xi.shape)) fig.tight_layout() plt.show() One caveat: With very large numbers of points, scipy.stats.gaussian_kde will become very slow. It's fairly easy to speed it up by making an approximation--just take the 2D histogram and blur it with a guassian filter of the right radius and covariance. I can give an example if you'd like. One other caveat: If you're doing this in a non-cartesian coordinate system, none of these methods apply! Getting density estimates on a spherical shell is a bit more complicated.
Contour
19,390,320
17
I'd like to know what would be the best strategy to compare a group of contours, in fact are edges resulting of a canny edges detection, from two pictures, in order to know which pair is more alike. I have this image: http://i55.tinypic.com/10fe1y8.jpg And I would like to know how can I calculate which one of these fits best to it: http://i56.tinypic.com/zmxd13.jpg (it should be the one on the right) Is there anyway to compare the contours as a whole? I can easily rotate the images but I don't know what functions to use in order to calculate that the reference image on the right is the best fit. Here it is what I've already tried using opencv: matchShapes function - I tried this function using 2 gray scales images and I always get the same result in every comparison image and the value seems wrong as it is 0,0002. So what I realized about matchShapes, but I'm not sure it's the correct assumption, is that the function works with pairs of contours and not full images. Now this is a problem because although I have the contours of the images I want to compare, they are hundreds and I don't know which ones should be "paired up". So I also tried to compare all the contours of the first image against the other two with a for iteration but I might be comparing,for example, the contour of the 5 against the circle contour of the two reference images and not the 2 contour. Also tried simple cv::compare function and matchTemplate, none with success.
Well, for this you have a couple of options depending on how robust you need your approach to be. Simple Solutions (with assumptions): For these methods, I'm assuming your the images you supplied are what you are working with (i.e., the objects are already segmented and approximately the same scale. Also, you will need to correct the rotation (at least in a coarse manner). You might do something like iteratively rotate the comparison image every 10, 30, 60, or 90 degrees, or whatever coarseness you feel you can get away with. For example, for(degrees = 10; degrees < 360; degrees += 10) coinRot = rotate(compareCoin, degrees) // you could also try Cosine Similarity, or even matchedTemplate here. metric = SAD(coinRot, targetCoin) if(metric > bestMetric) bestMetric = metric coinRotation = degrees Sum of Absolute Differences (SAD): This will allow you to quickly compare the images once you have determined an approximate rotation angle. Cosine Similarity: This operates a bit differently by treating the image as a 1D vector, and then computes the the high-dimensional angle between the two vectors. The better the match the smaller the angle will be. Complex Solutions (possibly more robust): These solutions will be more complex to implement, but will probably yield more robust classifications. Haussdorf Distance: This answer will give you an introduction on using this method. This solution will probably also need the rotation correction to work properly. Fourier-Mellin Transform: This method is an extension of Phase Correlation, which can extract the rotation, scale, and translation (RST) transform between two images. Feature Detection and Extraction: This method involves detecting "robust" (i.e., scale and/or rotation invariant) features in the image and comparing them against a set of target features with RANSAC, LMedS, or simple least squares. OpenCV has a couple of samples using this technique in matcher_simple.cpp and matching_to_many_images.cpp. NOTE: With this method you will probably not want to binarize the image, so there are more detectable features available.
Contour
7,869,405
17
I am looking for ways to fully fill in the contour generated by ggplot2's stat_contour. The current result is like this: # Generate data library(ggplot2) library(reshape2) # for melt volcano3d <- melt(volcano) names(volcano3d) <- c("x", "y", "z") v <- ggplot(volcano3d, aes(x, y, z = z)) v + stat_contour(geom="polygon", aes(fill=..level..)) The desired result can be produced by manually modifying the codes as follows. v + stat_contour(geom="polygon", aes(fill=..level..)) + theme(panel.grid=element_blank())+ # delete grid lines scale_x_continuous(limits=c(min(volcano3d$x),max(volcano3d$x)), expand=c(0,0))+ # set x limits scale_y_continuous(limits=c(min(volcano3d$y),max(volcano3d$y)), expand=c(0,0))+ # set y limits theme(panel.background=element_rect(fill="#132B43")) # color background My question: is there a way to fully fill the plot without manually specifying the color or using geom_tile()?
As @tonytonov has suggested this thread, the transparent areas can be deleted by closing the polygons. # check x and y grid minValue<-sapply(volcano3d,min) maxValue<-sapply(volcano3d,max) arbitaryValue=min(volcano3d$z-10) test1<-data.frame(x=minValue[1]-1,y=minValue[2]:maxValue[2],z=arbitaryValue) test2<-data.frame(x=minValue[1]:maxValue[1],y=minValue[2]-1,z=arbitaryValue) test3<-data.frame(x=maxValue[1]+1,y=minValue[2]:maxValue[2],z=arbitaryValue) test4<-data.frame(x=minValue[1]:maxValue[1],y=maxValue[2]+1,z=arbitaryValue) test<-rbind(test1,test2,test3,test4) vol<-rbind(volcano3d,test) w <- ggplot(vol, aes(x, y, z = z)) w + stat_contour(geom="polygon", aes(fill=..level..)) # better # Doesn't work when trying to get rid of unwanted space w + stat_contour(geom="polygon", aes(fill=..level..))+ scale_x_continuous(limits=c(min(volcano3d$x),max(volcano3d$x)), expand=c(0,0))+ # set x limits scale_y_continuous(limits=c(min(volcano3d$y),max(volcano3d$y)), expand=c(0,0)) # set y limits # work here! w + stat_contour(geom="polygon", aes(fill=..level..))+ coord_cartesian(xlim=c(min(volcano3d$x),max(volcano3d$x)), ylim=c(min(volcano3d$y),max(volcano3d$y))) The problem remained with this tweak is finding methods aside from trial and error to determine the arbitaryValue. [edit from here] Just a quick update to show how I am determining the arbitaryValue without having to guess for every datasets. BINS<-50 BINWIDTH<-(diff(range(volcano3d$z))/BINS) # reference from ggplot2 code arbitaryValue=min(volcano3d$z)-BINWIDTH*1.5 This seems to work well for the dataset I am working on now. Not sure if applicable with others. Also, note that the fact that I set BINS value here requires that I will have to use bins=BINS in stat_contour.
Contour
28,469,829
16
I am trying to color in black the outside region of a contours using openCV and python language. Here is my code : contours, hierarchy = cv2.findContours(copy.deepcopy(img_copy),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) areas = [cv2.contourArea(c) for c in contours] max_index = np.argmax(areas) cnt=contours[max_index] # how to fill of black the outside of the contours cnt please? `
Here's how you can fill an image with black color outside of a set of contours: import cv2 import numpy img = cv2.imread("zebra.jpg") stencil = numpy.zeros(img.shape).astype(img.dtype) contours = [numpy.array([[100, 180], [200, 280], [200, 180]]), numpy.array([[280, 70], [12, 20], [80, 150]])] color = [255, 255, 255] cv2.fillPoly(stencil, contours, color) result = cv2.bitwise_and(img, stencil) cv2.imwrite("result.jpg", result) UPD.: The code above exploits the fact that bitwise_and with 0-s produces 0-s, and won't work for fill colors other than black. To fill with an arbitrary color: import cv2 import numpy img = cv2.imread("zebra.jpg") fill_color = [127, 256, 32] # any BGR color value to fill with mask_value = 255 # 1 channel white (can be any non-zero uint8 value) # contours to fill outside of contours = [ numpy.array([ [100, 180], [200, 280], [200, 180] ]), numpy.array([ [280, 70], [12, 20], [80, 150]]) ] # our stencil - some `mask_value` contours on black (zeros) background, # the image has same height and width as `img`, but only 1 color channel stencil = numpy.zeros(img.shape[:-1]).astype(numpy.uint8) cv2.fillPoly(stencil, contours, mask_value) sel = stencil != mask_value # select everything that is not mask_value img[sel] = fill_color # and fill it with fill_color cv2.imwrite("result.jpg", img) Can fill with another image as well, for example, using img[sel] = ~img[sel] instead of img[sel] = fill_color would fill it with the same inverted image outside of the contours:
Contour
37,912,928
15
How would I make a countour grid in python using matplotlib.pyplot, where the grid is one colour where the z variable is below zero and another when z is equal to or larger than zero? I'm not very familiar with matplotlib so if anyone can give me a simple way of doing this, that would be great. So far I have: x= np.arange(0,361) y= np.arange(0,91) X,Y = np.meshgrid(x,y) area = funcarea(L,D,H,W,X,Y) #L,D,H and W are all constants defined elsewhere. plt.figure() plt.contourf(X,Y,area) plt.show()
You can do this using the levels keyword in contourf. import numpy as np import matplotlib.pyplot as plt fig, axs = plt.subplots(1,2) x = np.linspace(0, 1, 100) X, Y = np.meshgrid(x, x) Z = np.sin(X)*np.sin(Y) levels = np.linspace(-1, 1, 40) zdata = np.sin(8*X)*np.sin(8*Y) cs = axs[0].contourf(X, Y, zdata, levels=levels) fig.colorbar(cs, ax=axs[0], format="%.2f") cs = axs[1].contourf(X, Y, zdata, levels=[-1,0,1]) fig.colorbar(cs, ax=axs[1]) plt.show() You can change the colors by choosing and different colormap; using vmin, vmax; etc.
Contour
15,601,096
15
I'm trying to detect and fine-locate some objects in images from contours. The contours that I get often include some noise (maybe form the background, I don't know). The objects should look similar to rectangles or squares like: I get very good results with shape matching (cv::matchShapes) to detect contours with those objects in them, with and without noise, but I have problems with the fine-location in case of noise. Noise looks like: or for example. My idea was to find convexity defects and if they become too strong, somehow crop away the part that leads to concavity. Detecting the defects is ok, typically I get two defects per "unwanted structure", but I'm stuck on how to decide what and where I should remove points from the contours. Here are some contours, their masks (so you can extract the contours easily) and the convex hull including thresholded convexity defects: Could I just walk through the contour and locally decide whether a "left turn" is performed by the contour (if walking clockwise) and if so, remove contour points until the next left turn is taken? Maybe starting at a convexity defect? I'm looking for algorithms or code, programming language should not be important, algorithm is more important.
This approach works only on points. You don't need to create masks for this. The main idea is: Find defects on contour If I find at least two defects, find the two closest defects Remove from the contour the points between the two closest defects Restart from 1 on the new contour I get the following results. As you can see, it has some drawbacks for smooth defects (e.g. 7th image), but works pretty good for clearly visible defects. I don't know if this will solve your problem, but can be a starting point. In practice should be quite fast (you can surely optimize the code below, specially the removeFromContour function). Also, the only parameter of this approach is the amount of the convexity defect, so it works well with both small and big defecting blobs. #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int ed2(const Point& lhs, const Point& rhs) { return (lhs.x - rhs.x)*(lhs.x - rhs.x) + (lhs.y - rhs.y)*(lhs.y - rhs.y); } vector<Point> removeFromContour(const vector<Point>& contour, const vector<int>& defectsIdx) { int minDist = INT_MAX; int startIdx; int endIdx; // Find nearest defects for (int i = 0; i < defectsIdx.size(); ++i) { for (int j = i + 1; j < defectsIdx.size(); ++j) { float dist = ed2(contour[defectsIdx[i]], contour[defectsIdx[j]]); if (minDist > dist) { minDist = dist; startIdx = defectsIdx[i]; endIdx = defectsIdx[j]; } } } // Check if intervals are swapped if (startIdx <= endIdx) { int len1 = endIdx - startIdx; int len2 = contour.size() - endIdx + startIdx; if (len2 < len1) { swap(startIdx, endIdx); } } else { int len1 = startIdx - endIdx; int len2 = contour.size() - startIdx + endIdx; if (len1 < len2) { swap(startIdx, endIdx); } } // Remove unwanted points vector<Point> out; if (startIdx <= endIdx) { out.insert(out.end(), contour.begin(), contour.begin() + startIdx); out.insert(out.end(), contour.begin() + endIdx, contour.end()); } else { out.insert(out.end(), contour.begin() + endIdx, contour.begin() + startIdx); } return out; } int main() { Mat1b img = imread("path_to_mask", IMREAD_GRAYSCALE); Mat3b out; cvtColor(img, out, COLOR_GRAY2BGR); vector<vector<Point>> contours; findContours(img.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); vector<Point> pts = contours[0]; vector<int> hullIdx; convexHull(pts, hullIdx, false); vector<Vec4i> defects; convexityDefects(pts, hullIdx, defects); while (true) { // For debug Mat3b dbg; cvtColor(img, dbg, COLOR_GRAY2BGR); vector<vector<Point>> tmp = {pts}; drawContours(dbg, tmp, 0, Scalar(255, 127, 0)); vector<int> defectsIdx; for (const Vec4i& v : defects) { float depth = float(v[3]) / 256.f; if (depth > 2) // filter defects by depth { // Defect found defectsIdx.push_back(v[2]); int startidx = v[0]; Point ptStart(pts[startidx]); int endidx = v[1]; Point ptEnd(pts[endidx]); int faridx = v[2]; Point ptFar(pts[faridx]); line(dbg, ptStart, ptEnd, Scalar(255, 0, 0), 1); line(dbg, ptStart, ptFar, Scalar(0, 255, 0), 1); line(dbg, ptEnd, ptFar, Scalar(0, 0, 255), 1); circle(dbg, ptFar, 4, Scalar(127, 127, 255), 2); } } if (defectsIdx.size() < 2) { break; } // If I have more than two defects, remove the points between the two nearest defects pts = removeFromContour(pts, defectsIdx); convexHull(pts, hullIdx, false); convexityDefects(pts, hullIdx, defects); } // Draw result contour vector<vector<Point>> tmp = { pts }; drawContours(out, tmp, 0, Scalar(0, 0, 255), 1); imshow("Result", out); waitKey(); return 0; } UPDATE Working on an approximated contour (e.g. using CHAIN_APPROX_SIMPLE in findContours) may be faster, but the length of contours must be computed using arcLength(). This is the snippet to replace in the swapping part of removeFromContour: // Check if intervals are swapped if (startIdx <= endIdx) { //int len11 = endIdx - startIdx; vector<Point> inside(contour.begin() + startIdx, contour.begin() + endIdx); int len1 = (inside.empty()) ? 0 : arcLength(inside, false); //int len22 = contour.size() - endIdx + startIdx; vector<Point> outside1(contour.begin(), contour.begin() + startIdx); vector<Point> outside2(contour.begin() + endIdx, contour.end()); int len2 = (outside1.empty() ? 0 : arcLength(outside1, false)) + (outside2.empty() ? 0 : arcLength(outside2, false)); if (len2 < len1) { swap(startIdx, endIdx); } } else { //int len1 = startIdx - endIdx; vector<Point> inside(contour.begin() + endIdx, contour.begin() + startIdx); int len1 = (inside.empty()) ? 0 : arcLength(inside, false); //int len2 = contour.size() - startIdx + endIdx; vector<Point> outside1(contour.begin(), contour.begin() + endIdx); vector<Point> outside2(contour.begin() + startIdx, contour.end()); int len2 = (outside1.empty() ? 0 : arcLength(outside1, false)) + (outside2.empty() ? 0 : arcLength(outside2, false)); if (len1 < len2) { swap(startIdx, endIdx); } }
Contour
35,226,993
14
I have a problem to get my head around smoothing and sampling contours in OpenCV (C++ API). Lets say I have got sequence of points retrieved from cv::findContours (for instance applied on this this image: Ultimately, I want To smooth a sequence of points using different kernels. To resize the sequence using different types of interpolations. After smoothing, I hope to have a result like : I also considered drawing my contour in a cv::Mat, filtering the Mat (using blur or morphological operations) and re-finding the contours, but is slow and suboptimal. So, ideally, I could do the job using exclusively the point sequence. I read a few posts on it and naively thought that I could simply convert a std::vector(of cv::Point) to a cv::Mat and then OpenCV functions like blur/resize would do the job for me... but they did not. Here is what I tried: int main( int argc, char** argv ){ cv::Mat conv,ori; ori=cv::imread(argv[1]); ori.copyTo(conv); cv::cvtColor(ori,ori,CV_BGR2GRAY); std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i > hierarchy; cv::findContours(ori, contours,hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); for(int k=0;k<100;k += 2){ cv::Mat smoothCont; smoothCont = cv::Mat(contours[0]); std::cout<<smoothCont.rows<<"\t"<<smoothCont.cols<<std::endl; /* Try smoothing: no modification of the array*/ // cv::GaussianBlur(smoothCont, smoothCont, cv::Size(k+1,1),k); /* Try sampling: "Assertion failed (func != 0) in resize"*/ // cv::resize(smoothCont,smoothCont,cv::Size(0,0),1,1); std::vector<std::vector<cv::Point> > v(1); smoothCont.copyTo(v[0]); cv::drawContours(conv,v,0,cv::Scalar(255,0,0),2,CV_AA); std::cout<<k<<std::endl; cv::imshow("conv", conv); cv::waitKey(); } return 1; } Could anyone explain how to do this ? In addition, since I am likely to work with much smaller contours, I was wondering how this approach would deal with border effect (e.g. when smoothing, since contours are circular, the last elements of a sequence must be used to calculate the new value of the first elements...) Thank you very much for your advices, Edit: I also tried cv::approxPolyDP() but, as you can see, it tends to preserve extremal points (which I want to remove): Epsilon=0 Epsilon=6 Epsilon=12 Epsilon=24 Edit 2: As suggested by Ben, it seems that cv::GaussianBlur() is not supported but cv::blur() is. It looks very much closer to my expectation. Here are my results using it: k=13 k=53 k=103 To get around the border effect, I did: cv::copyMakeBorder(smoothCont,smoothCont, (k-1)/2,(k-1)/2 ,0, 0, cv::BORDER_WRAP); cv::blur(smoothCont, result, cv::Size(1,k),cv::Point(-1,-1)); result.rowRange(cv::Range((k-1)/2,1+result.rows-(k-1)/2)).copyTo(v[0]); I am still looking for solutions to interpolate/sample my contour.
Your Gaussian blurring doesn't work because you're blurring in column direction, but there is only one column. Using GaussianBlur() leads to a "feature not implemented" error in OpenCV when trying to copy the vector back to a cv::Mat (that's probably why you have this strange resize() in your code), but everything works fine using cv::blur(), no need to resize(). Try Size(0,41) for example. Using cv::BORDER_WRAP for the border issue doesn't seem to work either, but here is another thread of someone who found a workaround for that. Oh... one more thing: you said that your contours are likely to be much smaller. Smoothing your contour that way will shrink it. The extreme case is k = size_of_contour, which results in a single point. So don't choose your k too big.
Contour
11,925,777
14
I have problems with a contour-plot using logarithmic color scaling. I want to specify the levels by hand. Matplotlib, however, draws the color bar in a strange fashion -- the labels are not placed well and only one color appears. The idea is based on http://adversus.110mb.com/?cat=8 Is there anybody out there, who can help me? I use the latest git-repository matplotlib version, v1.1.0 (2011-04-21) import matplotlib.pyplot as plt import numpy as np from matplotlib.mlab import bivariate_normal from matplotlib.colors import LogNorm from matplotlib.backends.backend_pdf import PdfPages delta = 0.5 x = np.arange(-3.0, 4.001, delta) y = np.arange(-4.0, 3.001, delta) X, Y = np.meshgrid(x, y) Z = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) fig = plt.figure() ax = fig.add_subplot(1,1,1) #axim = ax.imshow(Z, norm = LogNorm()) axim = ax.contourf(X,Y,Z,levels=[1e0,1e-1,1e-2,1e-3],cmap=plt.cm.jet,norm = LogNorm()) cb = fig.colorbar(axim) pp = PdfPages('fig.pdf') pp.savefig() pp.close() plt.show() Thank you very much for your help! It works perfect, as you suggested... However, I have another question: Why does matplotlib not allow me to select the number of level lines in the logarithmic mode: import matplotlib.pyplot as plt import numpy as np from matplotlib.mlab import bivariate_normal from matplotlib.colors import LogNorm from matplotlib.backends.backend_pdf import PdfPages delta = 0.5 x = np.arange(-3.0, 4.001, delta) y = np.arange(-4.0, 3.001, delta) X, Y = np.meshgrid(x, y) Z = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) fig = plt.figure() ax = fig.add_subplot(1,1,1) #axim = ax.imshow(Z, norm = LogNorm()) #axim = ax.contourf(X,Y,Z,levels=[1e-3,1e-2,1e-1,1e0],cmap=plt.cm.jet,norm = LogNorm()) axim = ax.contourf(X,Y,Z,20,cmap=plt.cm.jet,norm = LogNorm()) cb = fig.colorbar(axim) pp = PdfPages('fig.pdf') pp.savefig() pp.close() plt.show() https://i.sstatic.net/VeVFQ.png This was my original problem...
So it's easily fixed; your order of levels means that the lowest level gets drawn last and therefore covered everything! Try: axim = ax.contourf(X,Y,Z,levels=[1e-3, 1e-2, 1e-1, 1e0],cmap=plt.cm.jet,norm = LogNorm()) instead and you should get the desired result.
Contour
5,748,076
14
I'm using OpenCV (Canny + findCountours) to find external contours of objects. The curve drawn is typically almost, but not entirely, closed. I'd like to close it - to find the region it bounds. How do I do this? Things considered: Dilation - the examples I've seen show this after Canny, although it would seem to me it makes more sense to do this after findContours Convex hull - might work, though I'm really trying to complete a curve Shape simplification - related, but not exactly what I want
Using PolyLine method to draw contours cv2.PolyLine(img, points, is_closed=True, 255, thickness=1, lineType=8, shift=0) Read the docs for further details: http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html Mark answered if it resolved your problem. If not then let me know.
Contour
21,469,409
13
I am using openCV with python to extract contours from an image. Now I need to export these contour paths (list) as an svg paths. How can I achieve this ? code: ret,thresh = cv2.threshold(imgray,27,25,0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_TC89_L1) print(type(contours)) #type list
the problem has been solved as follows: c = max(contours, key=cv2.contourArea) #max contour f = open('path.svg', 'w+') f.write('<svg width="'+str(width)+'" height="'+str(height)+'" xmlns="http://www.w3.org/2000/svg">') f.write('<path d="M') for i in xrange(len(c)): #print(c[i][0]) x, y = c[i][0] print(x) f.write(str(x)+ ' ' + str(y)+' ') f.write('"/>') f.write('</svg>') f.close()
Contour
43,108,751
13
In a previous question, I reproduced a contour plot generated with the fields package, in ggplot2 instead (full example below). The only trouble is, I would like to replicate the placement of the contour labels in contour(), which by default are at the "flattest" part of the line - the second picture might show why. I'm stumped by how to set up that calculation. I see here that it's possible to grab the data used to generate the contour lines, and then geom_text() could be used to plot the text. So what's left is figuring out how to calculate the "flattest" part. Ideas? library(fields) library(ggplot2) library(reshape) library(directlabels) sumframe<-structure(list(Morph = c("LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW"), xvalue = c(4, 8, 9, 9.75, 13, 14, 16.25, 17.25, 18, 23, 27, 28, 28.75, 4, 8, 9, 9.75, 13, 14, 16.25, 17.25, 18, 23, 27, 28, 28.75), yvalue = c(17, 34, 12, 21.75, 29, 7, 36.25, 14.25, 24, 19, 36, 14, 23.75, 17, 34, 12, 21.75, 29, 7, 36.25, 14.25, 24, 19, 36, 14, 23.75), zvalue = c(126.852666666667, 182.843333333333, 147.883333333333, 214.686666666667, 234.511333333333, 198.345333333333, 280.9275, 246.425, 245.165, 247.611764705882, 266.068, 276.744, 283.325, 167.889, 229.044, 218.447777777778, 207.393, 278.278, 203.167, 250.495, 329.54, 282.463, 299.825, 286.942, 372.103, 307.068)), .Names = c("Morph", "xvalue", "yvalue", "zvalue"), row.names = c(NA, -26L), class = "data.frame") sumframeLW<-subset(sumframe, Morph=="LW") # FIELDS CONTOUR PLOT: surf.teLW<-Tps(cbind(sumframeLW$xvalue, sumframeLW$yvalue), sumframeLW$zvalue, lambda=0.01) summary(surf.teLW) surf.te.outLW<-predict.surface(surf.teLW) image(surf.te.outLW, col=tim.colors(128), xlim=c(0,38), ylim=c(0,38), zlim=c(100,400), lwd=5, las=1, font.lab=2, cex.lab=1.3, mgp=c(2.7,0.5,0), font.axis=1, lab=c(5,5,6), xlab=expression("X value"), ylab=expression("Y value"),main="LW plot") contour(surf.te.outLW, lwd=2, labcex=1, add=T) # GGPLOT2 CONTOUR PLOT: LWsurfm<-melt(surf.te.outLW) LWsurfm<-rename(LWsurfm, c("value"="z", "X1"="x", "X2"="y")) LWsurfms<-na.omit(LWsurfm) LWp<-ggplot(LWsurfms, aes(x,y,z=z))+geom_tile(aes(fill=z))+stat_contour(aes(x,y,z=z, colour=..level..), colour="black", size=0.6)+scale_fill_gradientn(colours=tim.colors(128)) LWp LWp<-direct.label(LWp)
I created a function to calculate the flattest section using the method for contour() (from plot3d), created a data frame with just the flattest values with help from plyr, and added it manually to the plot with geom_text(). To exactly match the contour() output, the labels need to be rotated, sections of the contour lines need to be erased to make room for the labels, and corrections need to be made to ensure the labels don't fall off the edges of the contour lines. I will work on these over the next couple of months (this is all still a side project). library(fields) library(ggplot2) library(reshape) sumframe<-structure(list(Morph = c("LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "LW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW", "SW"), xvalue = c(4, 8, 9, 9.75, 13, 14, 16.25, 17.25, 18, 23, 27, 28, 28.75, 4, 8, 9, 9.75, 13, 14, 16.25, 17.25, 18, 23, 27, 28, 28.75), yvalue = c(17, 34, 12, 21.75, 29, 7, 36.25, 14.25, 24, 19, 36, 14, 23.75, 17, 34, 12, 21.75, 29, 7, 36.25, 14.25, 24, 19, 36, 14, 23.75), zvalue = c(126.852666666667, 182.843333333333, 147.883333333333, 214.686666666667, 234.511333333333, 198.345333333333, 280.9275, 246.425, 245.165, 247.611764705882, 266.068, 276.744, 283.325, 167.889, 229.044, 218.447777777778, 207.393, 278.278, 203.167, 250.495, 329.54, 282.463, 299.825, 286.942, 372.103, 307.068)), .Names = c("Morph", "xvalue", "yvalue", "zvalue"), row.names = c(NA, -26L), class = "data.frame") # Subdivide, calculate surfaces, recombine for ggplot: sumframeLW<-subset(sumframe, Morph=="LW") sumframeSW<-subset(sumframe, Morph="SW") surf.teLW<-Tps(cbind(sumframeLW$xvalue, sumframeLW$yvalue), sumframeLW$zvalue, lambda=0.01) surf.te.outLW<-predict.surface(surf.teLW) surf.teSW<-Tps(cbind(sumframeSW$xvalue, sumframeSW$yvalue), sumframeSW$zvalue, lambda=0.01) surf.te.outSW<-predict.surface(surf.teSW) sumframe$Morph<-as.numeric(as.factor(sumframe$Morph)) LWsurfm<-melt(surf.te.outLW) LWsurfm<-rename(LWsurfm, c("value"="z", "X1"="x", "X2"="y")) LWsurfms<-na.omit(LWsurfm) LWsurfms[,"Morph"]<-c("LW") SWsurfm<-melt(surf.te.outSW) SWsurfm<-rename(SWsurfm, c("value"="z", "X1"="x", "X2"="y")) SWsurfms<-na.omit(SWsurfm) SWsurfms[,"Morph"]<-c("SW") LWSWsurf<-rbind(LWsurfms, SWsurfms) # Note that I've lost my units - things have been rescaled to be between 0 and 80. LWSWc<-ggplot(LWSWsurf, aes(x,y,z=z))+facet_wrap(~Morph)+geom_contour(colour="black", size=0.6) LWSWc # Create data frame from data used to generate this contour plot: tmp3<-ggplot_build(LWSWc)$data[[1]] In a nutshell, the tmp3 data frame contains a vector, tmp3$group, which was used as a grouping variable for subsequent calculations. Within each level of tmp3$group, the variances were calculated with flattenb. A new data frame was generated, and the values from that data frame were added to the plot with geom_text(). flattenb <- function (tmp3){ counts = length(tmp3$group) xdiffs = diff(tmp3$x) ydiffs = diff(tmp3$y) avgGradient = ydiffs/xdiffs squareSum = avgGradient * avgGradient variance = (squareSum - (avgGradient * avgGradient) / counts / counts) data.frame(variance = c(9999999, variance) #99999 pads this so the length is same as original and the first values are not selected ) } tmp3<-cbind(tmp3, ddply(tmp3, 'group', flattenb)) tmp3l<-ddply(tmp3, 'group', subset, variance==min(variance)) tmp3l[,"Morph"]<-c(rep("LW", times=8), rep("SW", times=8)) LWSWpp<-ggplot(LWSWsurf, aes(x,y,z=z)) LWSWpp<-LWSWpp+geom_tile(aes(fill=z))+stat_contour(aes(x,y,z=z, colour=..level..), colour="black", size=0.6) LWSWpp<-LWSWpp+scale_fill_gradientn(colours=tim.colors(128)) LWSWpp<-LWSWpp+geom_text(data=tmp3l, aes(z=NULL, label=level))+facet_wrap(~Morph) LWSWpp
Contour
21,868,353
13
How can I sort contours by the size of their contour areas? And how can I get the biggest/smallest one?
You can use std::sort with a custom comparison function object // comparison function object bool compareContourAreas ( std::vector<cv::Point> contour1, std::vector<cv::Point> contour2 ) { double i = fabs( contourArea(cv::Mat(contour1)) ); double j = fabs( contourArea(cv::Mat(contour2)) ); return ( i < j ); } Usage: [...] // find contours std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours( binary_image, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) ); // sort contours std::sort(contours.begin(), contours.end(), compareContourAreas); // grab contours std::vector<cv::Point> biggestContour = contours[contours.size()-1]; std::vector<cv::Point> smallestContour = contours[0];
Contour
13,495,207
13
Possible Duplicate: Understanding region of interest in openCV 2.4 i want to get a sub-image (the one bounded by the red box below) from an image (Mat format). how do i do this? here's my progress so far: include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; int main() { Mat imgray, thresh; vector<vector<Point> >contours; vector<Point> cnt; vector<Vec4i> hierarchy; Point leftmost; Mat im = imread("igoy1.jpg"); cvtColor(im, imgray, COLOR_BGR2GRAY); threshold(imgray, thresh, 127, 255, 0); findContours(thresh, contours, hierarchy, RETR_TREE,CHAIN_APPROX_SIMPLE); }
You can start picking a contour (in your case, the contour corresponding to the hand). Then, you calculate the bounding rectangle for this contour. Finally you make a new matrix header from it. int n=0;// Here you will need to define n differently (for instance pick the largest contour instead of the first one) cv::Rect rect(contours[n]); cv::Mat miniMat; miniMat = imgray(rect); Warning: In this case, miniMat is a subregion of imgray. This means that if you modify the former, you also modify the latter. Use miniMat.copyTo(anotherMat) to avoid this. I hope it helped, Good luck
Contour
12,931,621
13
I have a function f(x,y) of two variables, of which I need to know the location of the curves at which it crosses zero. ContourPlot does that very efficiently (that is: it uses clever multi-grid methods, not just a brute force fine-grained scan) but just gives me a plot. I would like to have a set of values {x,y} (with some specified resolution) or perhaps some interpolating function which allows me to get access to the location of these contours. Have thought of extracting this from the FullForm of ContourPlot but this seems to be a bit of a hack. Any better way to do this?
If you end up extracting points from ContourPlot, this is one easy way to do it: points = Cases[ Normal@ContourPlot[Sin[x] Sin[y] == 1/2, {x, -3, 3}, {y, -3, 3}], Line[pts_] -> pts, Infinity ] Join @@ points (* if you don't want disjoint components to be separate *) EDIT It appears that ContourPlot does not produce very precise contours. They're of course meant for plotting and are good enough for that, but the points don't lie precisely on the contours: In[78]:= Take[Join @@ points /. {x_, y_} -> Sin[x] Sin[y] - 1/2, 10] Out[78]= {0.000163608, 0.0000781187, 0.000522698, 0.000516078, 0.000282781, 0.000659909, 0.000626086, 0.0000917416, 0.000470424, 0.0000545409} We can try to come up with our own method to trace the contour, but it's a lot of trouble to do it in a general way. Here's a concept that works for smoothly varying functions that have smooth contours: Start from some point (pt0), and find the intersection with the contour along the gradient of f. Now we have a point on the contour. Move along the tangent of the contour by a fixed step (resolution), then repeat from step 1. Here's a basic implementation that only works with functions that can be differentiated symbolically: rot90[{x_, y_}] := {y, -x} step[f_, pt : {x_, y_}, pt0 : {x0_, y0_}, resolution_] := Module[ {grad, grad0, t, contourPoint}, grad = D[f, {pt}]; grad0 = grad /. Thread[pt -> pt0]; contourPoint = grad0 t + pt0 /. First@FindRoot[f /. Thread[pt -> grad0 t + pt0], {t, 0}]; Sow[contourPoint]; grad = grad /. Thread[pt -> contourPoint]; contourPoint + rot90[grad] resolution ] result = Reap[ NestList[step[Sin[x] Sin[y] - 1/2, {x, y}, #, .5] &, {1, 1}, 20] ]; ListPlot[{result[[1]], result[[-1, 1]]}, PlotStyle -> {Red, Black}, Joined -> True, AspectRatio -> Automatic, PlotMarkers -> Automatic] The red points are the "starting points", while the black points are the trace of the contour. EDIT 2 Perhaps it's an easier and better solution to use a similar technique to make the points that we get from ContourPlot more precise. Start from the initial point, then move along the gradient until we intersect the contour. Note that this implementation will also work with functions that can't be differentiated symbolically. Just define the function as f[x_?NumericQ, y_?NumericQ] := ... if this is the case. f[x_, y_] := Sin[x] Sin[y] - 1/2 refine[f_, pt0 : {x_, y_}] := Module[{grad, t}, grad = N[{Derivative[1, 0][f][x, y], Derivative[0, 1][f][x, y]}]; pt0 + grad*t /. FindRoot[f @@ (pt0 + grad*t), {t, 0}] ] points = Join @@ Cases[ Normal@ContourPlot[f[x, y] == 0, {x, -3, 3}, {y, -3, 3}], Line[pts_] -> pts, Infinity ] refine[f, #] & /@ points
Contour
6,806,034
13
I am trying to detect playing cards and transform them to get a bird's eye view of the card using python opencv. My code works fine for simple cases but I didn't stop at the simple cases and want to try out more complex ones. I'm having problems finding correct contours for cards.Here's an attached image where I am trying to detect cards and draw contours: My Code: path1 = "F:\\ComputerVisionPrograms\\images\\cards4.jpeg" g = cv2.imread(path1,0) img = cv2.imread(path1) edge = cv2.Canny(g,50,200) p,c,h = cv2.findContours(edge, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) rect = [] for i in c: p = cv2.arcLength(i, True) ap = cv2.approxPolyDP(i, 0.02 * p, True) if len(ap)==4: rect.append(i) cv2.drawContours(img,rect, -1, (0, 255, 0), 3) plt.imshow(img) plt.show() Result: This is not what I wanted, I wanted only the rectangular cards to be selected but since they are occluding one another, I am not getting what I expected. I believe I need to apply morphological tricks or other operations to maybe separate them or make the edges more prominent or may be something else. It would be really appreciated if you could share your approach to tackle this problem. A few more examples requested by other fellows:
There are lots of approaches to find overlapping objects in the image. The information you have for sure is that your cards are all rectangles, mostly white and have the same size. Your variables are brightness, angle, may be some perspective distortion. If you want a robust solution, you need to address all that issues. I suggest using Hough transform to find card edges. First, run a regular edge detection. Than you need to clean up the results, as many short edges will belong to "face" cards. I suggest using a combination of dilate(11)->erode(15)->dilate(5). This combination will fill all the gaps in the "face" card, then it "shrinks" down the blobs, on the way removing the original edges and finally grow back and overlap a little the original face picture. Then you remove it from the original image. Now you have an image that have almost all the relevant edges. Find them using Hough transform. It will give you a set of lines. After filtering them a little you can fit those edges to rectangular shape of the cards. dst = cv2.Canny(img, 250, 50, None, 3) cn = cv2.dilate(dst, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))) cn = cv2.erode(cn, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))) cn = cv2.dilate(cn, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))) dst -= cn dst[dst < 127] = 0 cv2.imshow("erode-dilated", dst) # Copy edges to the images that will display the results in BGR cdstP = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR) linesP = cv2.HoughLinesP(dst, 0.7, np.pi / 720, 30, None, 20, 15) if linesP is not None: for i in range(0, len(linesP)): l = linesP[i][0] cv2.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0, 255, 0), 2, cv2.LINE_AA) cv2.imshow("Detected edges", cdstP) This will give you following:
Contour
62,679,083
12
Given a probability distribution with unknown functional form (example below), I like to plot "percentile-based" contour lines, i.e.,those that correspond to regions with an integral of 10%, 20%, ..., 90% etc. ## example of an "arbitrary" probability distribution ## from matplotlib.mlab import bivariate_normal import matplotlib.pyplot as plt import numpy as np X, Y = np.mgrid[-3:3:100j, -3:3:100j] z1 = bivariate_normal(X, Y, .5, .5, 0., 0.) z2 = bivariate_normal(X, Y, .4, .4, .5, .5) z3 = bivariate_normal(X, Y, .6, .2, -1.5, 0.) z = z1+z2+z3 plt.imshow(np.reshape(z.T, (100,-1)), origin='lower', extent=[-3,3,-3,3]) plt.show() I've looked into multiple approaches, from using the default contour function in matplotlib, methods involving stats.gaussian_kde in scipy, and even perhaps generating random point samples from the distribution and estimating a kernel afterwards. None of them appears to provide the solution.
Look at the integral of p(x) inside the contour p(x) ≥ t and solve for the desired value of t: import matplotlib from matplotlib.mlab import bivariate_normal import matplotlib.pyplot as plt import numpy as np X, Y = np.mgrid[-3:3:100j, -3:3:100j] z1 = bivariate_normal(X, Y, .5, .5, 0., 0.) z2 = bivariate_normal(X, Y, .4, .4, .5, .5) z3 = bivariate_normal(X, Y, .6, .2, -1.5, 0.) z = z1 + z2 + z3 z = z / z.sum() n = 1000 t = np.linspace(0, z.max(), n) integral = ((z >= t[:, None, None]) * z).sum(axis=(1,2)) from scipy import interpolate f = interpolate.interp1d(integral, t) t_contours = f(np.array([0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1])) plt.imshow(z.T, origin='lower', extent=[-3,3,-3,3], cmap="gray") plt.contour(z.T, t_contours, extent=[-3,3,-3,3]) plt.show()
Contour
37,890,550
12
I am creating a two-dimensional contour plot with matplotlib. Using the documentation provided http://matplotlib.org/examples/pylab_examples/contour_demo.html, such a contour plot can be created by import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 10.0 * (Z2 - Z1) plt.figure() CS = plt.contour(X, Y, Z) plt.clabel(CS, inline=1, fontsize=10) plt.title('Simplest default with labels') which outputs the following plot. The documentation details how to manually label certain contours (or "lines") on the existing plot. My question is how to create more contour lines than those shown. For example, the plot shown has two bivariate gaussians. The upper right has three contour lines, at 0.5, 1.0, and 1.5. How could I add contour lines at say 0.75 and 1.25? Also, I should be able to zoom in and (in principle) add dozens of dozens of contour lines from (for example) 1.0 and 1.5. How does one do this?
To draw isolines at specified level values, set the levels parameter in .contour: levels = np.arange(-1.0,1.5,0.25) CS = plt.contour(X, Y, Z, levels=levels) import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 10.0 * (Z2 - Z1) plt.figure() levels = np.arange(-1.0,1.5,0.25) CS = plt.contour(X, Y, Z, levels=levels) plt.clabel(CS, inline=1, fontsize=10) plt.title('levels = {}'.format(levels.tolist())) plt.show() The sixth figure here uses this method to draw isolines at levels = np.arange(-1.2, 1.6, 0.2). To zoom in, set the x limits and y limits of the desired region: plt.xlim(0, 3) plt.ylim(0, 2) and to draw, say, 24 automatically-chosen levels, use CS = plt.contour(X, Y, Z, 24) For example, import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 10.0 * (Z2 - Z1) plt.figure() N = 24 CS = plt.contour(X, Y, Z, N) plt.clabel(CS, inline=1, fontsize=10) plt.title('{} levels'.format(N)) plt.xlim(0, 3) plt.ylim(0, 2) plt.show() The third figure here uses this method to draw 6 isolines.
Contour
31,499,689
12
Can anyone give me an example of how to mark a specific level in a contour map? I would like to mark the level which is the black line in this plot: I am using the following code: plt.figure() CS = plt.contour(X, Y,log_mu,levels = [np.log10(5e-8),np.log10(9e-5)]) CS = plt.contourf(X, Y,log_mu) CB = plt.colorbar(CS, shrink=0.8, extend='both') plt.xscale('log') plt.yscale('log') plt.show() And the data for this specific plot can be obtained here dpaste data for contour plot
Take a look at this example from the matplotlib gallery for contour plot functionality. By modifying the levels in your script, as well as changing some of the references, leads to : plt.figure() CS = plt.contour(X, Y,log_mu,levels = [-7,-8], colors=('k',),linestyles=('-',),linewidths=(2,)) CSF = plt.contourf(X, Y,log_mu) plt.clabel(CS, fmt = '%2.1d', colors = 'k', fontsize=14) #contour line labels CB = plt.colorbar(CSF, shrink=0.8, extend='both') plt.xscale('log') plt.yscale('log') plt.show()
Contour
24,418,980
12
I have following Pandas Dataframe: In [66]: hdf.size() Out[66]: a b 0 0.0 21004 0.1 119903 0.2 186579 0.3 417349 0.4 202723 0.5 100906 0.6 56386 0.7 6080 0.8 3596 0.9 2391 1.0 1963 1.1 1730 1.2 1663 1.3 1614 1.4 1309 ... 186 0.2 15 0.3 9 0.4 21 0.5 4 187 0.2 3 0.3 10 0.4 22 0.5 10 188 0.0 11 0.1 19 0.2 20 0.3 13 0.4 7 0.5 5 0.6 1 Length: 4572, dtype: int64 You see, a from 0...188 and b in every group from some value to some value. And as the designated Z-value, the count of the occurence of the pair a/b. How to get a countour or heatmap plot out of the grouped dataframe? I have this (asking for the ?): numcols, numrows = 30, 30 xi = np.linspace(0, 200, numcols) yi = np.linspace(0, 6, numrows) xi, yi = np.meshgrid(xi, yi) zi = griddata(?, ?, hdf.size().values, xi, yi) How to get the x and y values out of the Groupby object and plot a contour?
Thanks a lot! My fault was, that I did not realize, that I have to apply some function to the groupby dataframe, like .size(), to work with it... hdf = aggdf.groupby(['a','b']).size() hdf gives me a b 1 -2.0 1 -1.9 1 -1.8 1 -1.7 2 -1.6 5 -1.5 10 -1.4 9 -1.3 21 -1.2 34 -1.1 67 -1.0 65 -0.9 94 -0.8 180 -0.7 242 -0.6 239 ... 187 0.4 22 0.5 10 188 -0.6 2 -0.5 2 -0.4 1 -0.3 2 -0.2 5 -0.1 10 -0.0 18 0.1 19 0.2 20 0.3 13 0.4 7 0.5 5 0.6 1 Length: 8844, dtype: int64 With that, and your help CT Zhu, I could then do hdfreset = hdf.reset_index() hdfreset.columns = ['a', 'b', 'occurrence'] hdfpivot=hdfreset.pivot('a', 'b') and this finally gave me the correct values to X=hdfpivot.columns.levels[1].values Y=hdfpivot.index.values Z=hdfpivot.values Xi,Yi = np.meshgrid(X, Y) plt.contourf(Yi, Xi, Z, alpha=0.7, cmap=plt.cm.jet); which leads to this beautiful contourf:
Contour
24,032,282
12
Would it be possible to have levels of the colorbar in log scale like in the image below? Here is some sample code where it could be implemented: import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LogNorm delta = 0.025 x = y = np.arange(0, 3.01, delta) X, Y = np.meshgrid(x, y) Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 1e6 * (Z1* Z2) fig=plt.figure() ax1 = fig.add_subplot(111) lvls = np.logspace(0,4,20) CF = ax1.contourf(X,Y,Z, norm = LogNorm(), levels = lvls ) CS = ax1.contour(X,Y,Z, norm = LogNorm(), colors = 'k', levels = lvls ) cbar = plt.colorbar(CF, ticks=lvls, format='%.4f') plt.show() I am using python 2.7.3 with matplotlib 1.1.1 on Windows 7.
I propose to generate a pseudo colorbar as follows (see comments for explanations): import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LogNorm import matplotlib.gridspec as gridspec delta = 0.025 x = y = np.arange(0, 3.01, delta) X, Y = np.meshgrid(x, y) Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 1e6 * (Z1 * Z2) fig=plt.figure() # # define 2 subplots, using gridspec to control the # width ratios: # # note: you have to import matplotlib.gridspec for this # gs = gridspec.GridSpec(1, 2,width_ratios=[15,1]) # the 1st subplot ax1 = plt.subplot(gs[0]) lvls = np.logspace(0,4,20) CF = ax1.contourf(X,Y,Z, norm = LogNorm(), levels = lvls ) CS = ax1.contour(X,Y,Z, norm = LogNorm(), colors = 'k', levels = lvls ) # # the pseudo-colorbar # # the 2nd subplot ax2 = plt.subplot(gs[1]) # # new levels! # # np.logspace gives you logarithmically spaced levels - # this, however, is not what you want in your colorbar # # you want equally spaced labels for each exponential group: # levls = np.linspace(1,10,10) levls = np.concatenate((levls[:-1],np.linspace(10,100,10))) levls = np.concatenate((levls[:-1],np.linspace(100,1000,10))) levls = np.concatenate((levls[:-1],np.linspace(1000,10000,10))) # # simple x,y setup for a contourf plot to serve as colorbar # XC = [np.zeros(len(levls)), np.ones(len(levls))] YC = [levls, levls] CM = ax2.contourf(XC,YC,YC, levels=levls, norm = LogNorm()) # log y-scale ax2.set_yscale('log') # y-labels on the right ax2.yaxis.tick_right() # no x-ticks ax2.set_xticks([]) plt.show() This will give you a plot like this: EDIT Or, use something like the new levels and the spacing='proportional' option when calling the colorbar: replace this line: lvls = np.logspace(0,4,20) with these: lvls = np.linspace(1,10,5) lvls = np.concatenate((lvls[:-1],np.linspace(10,100,5))) lvls = np.concatenate((lvls[:-1],np.linspace(100,1000,5))) lvls = np.concatenate((lvls[:-1],np.linspace(1000,10000,5))) replace this line: cbar = plt.colorbar(CF, ticks=lvls, format='%.4f') with this: cbar = plt.colorbar(CF, ticks=lvls, format='%.2f', spacing='proportional') And you will end up with this plot: (the format was only changed, because the new ticks do not require 4 decimals) EDIT 2 If you wanted to automatically generate levels like the ones I have used, you can consider this piece of code: levels = [] LAST_EXP = 4 N_LEVELS = 5 for E in range(0,LAST_EXP): levels = np.concatenate((levels[:-1],np.linspace(10**E,10**(E+1),N_LEVELS)))
Contour
18,191,867
12
I have a image with about 50 to 100 small contours. I wish to find the average intensity[1] of each of these contours in real-time[2]. Some of the ways I could think of was Draw contour with FILLED option for each contour; use each image as a mask over the original image, thus find the average. But I presume that this method won't be real-time at first glance. Study OpenCV implementation of drawContour function with the FILLED option and access the pixels enclosed by the contour in the same manner. But the code seems really complex and not readily understandable. Calculate the minimum area rectangle, find all the points inside the rectangle using transformation, and find average of points that are non-zero. Again, seems complex approach. Is there an easier, efficient way to do this? [1] Average of all pixel intensities enclosed by each of the non-overlapping contours [2] About 25, (960 x 480) pixel images per sec on a 2.66 Ghz desktop PC
I was unable to come up with any methods substantially different than your suggested approaches. However, I was able to do some timings that may help guide your decision. All of my timings were run on a 1280*720 image on an iMac, limited to finding 100 contours. The timings will of course be different on your machine, but the relative timings should be informative. For each test case, the following are declared: std::vector<std::vector<cv::Point>> cont; // Filled by cv::findContours() cv::Mat labels = cv::Mat::zeros(image.size(), CV_8UC1); std::vector<float> cont_avgs(cont.size(), 0.f); // This contains the averages of each contour Method 1: 19.0ms Method 1 is conceptually the simplest, but it is also the slowest. Each contour is labeled by assigning a unique color to each contour. Values of each labelled component are summed by iterating through every pixel in the image. for (size_t i = 0; i < cont.size(); ++i) { // Labels starts at 1 because 0 means no contour cv::drawContours(labels, cont, i, cv::Scalar(i+1), CV_FILLED); } std::vector<float> counts(cont.size(), 0.f); const int width = image.rows; for (size_t i = 0; i < image.rows; ++i) { for (size_t j = 0; j < image.cols; ++j) { uchar label = labels.data[i*width + j]; if (label == 0) { continue; // No contour } else { label -= 1; // Make labels zero-indexed } uchar value = image.data[i*width + j]; cont_avgs[label] += value; ++counts[label]; } } for (size_t i = 0; i < cont_avgs.size(); ++i) { cont_avgs[i] /= counts[i]; } Method 3: 15.7ms An unmodified Method 3 has the simplest implementation and is also the fastest. All contours are filled to use as a mask for finding the mean. The bounding rectangle of each contour is computed, and then the mean is calculated using the mask within the bounding box. Warning: This method will give incorrect results if any other contours are within the bounding rectangle of the contour of interest. cv::drawContours(labels, cont, -1, cv::Scalar(255), CV_FILLED); for (size_t i = 0; i < cont.size(); ++i) { cv::Rect roi = cv::boundingRect(cont[i]); cv::Scalar mean = cv::mean(image(roi), labels(roi)); cont_avgs[i] = mean[0]; } Modified Method 3: 17.8ms Making slight modifications to Method 3 increases execution time slightly, but gains the benefit of giving correct results regardless of contour positions. Each contour is individually labeled, and the mean is calculated using only the mask for that contour. for (size_t i = 0; i < cont.size(); ++i) { cv::drawContours(labels, cont, i, cv::Scalar(i), CV_FILLED); cv::Rect roi = cv::boundingRect(cont[i]); cv::Scalar mean = cv::mean(image(roi), labels(roi) == i); cont_avgs[i] = mean[0]; }
Contour
17,936,510
12
I have two contours and I want to check the relation between them (if one of them is nested). Normally, I would use the findContours function with CV_RETR_TREE retrieval mode. However, I obtained the contours from a different source (using MSER method). I actually not only have the contours, but also the region mask if that helps. For example, lets say I want to segment the letter 'O', then I would have the following masks or contours: 1) 0 0 0 0 0 0 0 1 1 1 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 0 0 2) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 How can I easily check that the second one is inside the first contour? I thought about checking the relation between the bounding boxes, but this doesn't cover all possible cases.
Use cv::pointPolygonTest(InputArray contour, Point2f pt, bool measureDist) to know whether a point from a contour is inside the other. You have to check for border cases (the first point you pick is common to both polygons, etc) if(pointPolygonTest(contour, pointFromOtherContour, false) > 0) { // it is inside } The function determines whether the point is inside a contour, outside, or lies on an edge (or coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively. Otherwise, the return value is a signed distance between the point and the nearest contour edge.
Contour
8,508,096
12
I'm trying to match a slightly irregular shape to a database of shapes. For example, here the contour I'm trying to match: For more information, this is an outline of an HDMI connector, represented as a contour. It is slightly rough as this was taken with a phone while holding the HDMI. This is my database of connectors: HDMI: DVI: 5PinDIN: DB25: These are a lot clearer as these are contours gathered from connector images from the internet. For what I have tried: cv2.matchShapes() Since these are all just contours, I tried directly comparing them using the matchShapes() method, and it failed to produce good results. The similarities between the irregular contour, and my database was: HDMI: 0.90 DB25: 0.84 5 Pin DIN: 0.5 DVI: 0.21 Since contours are more similar the closer to 0 the match result is, the algorithm completely failed. I tried the other methods of matching by changing the third parameter and was still unsuccessful. ORB: Being similar to SIFT, I tried keypoint matching. Averaging the distance between the different matches in my database (after finding the top 15% of matches): mean([m.distance for m in matches]) The distances came up as: Five Pin DIN: 7.6 DB25: 11.7 DVI: 12.1 HDMI: 19.6 As this classified a circle as the shape most like my contour, this has failed as well. Here are the matching key points from ORB of the actual HDMI slot vs my example HDMI slot for more information: Are there any ideas/other algorithms I should try? Or is a CNN my only choice (which I would rather avoid as I don't have the appropriate amount of data).
This answer is based on ZdaR's answer here https://stackoverflow.com/a/55530040/1787145. I have tried some variations in hope of using a single discerning criterion (cv2.matchShapes()) by incorporating more in the pre-processing. 1. Compare images instead of contours I like the idea of normalization (crop and resize). But after shrinking an image, its originally closed contour might be broken into multiple disconnected parts, due to the low resolution of pixels. The result of cv2.matchShapes() is unreliable. By comparing whole resized images, I get following results. It says the circle is the most similar. Not good! 2. Fill the shape By filling the shape, we take area into consideration. The result looks better, but DVI still beats HDMI for having a more similar height or Height/Width ratio. We want to ignore that. 3. Resize every image to the same size By resizing all to the same size, we eliminate some ratio in the dimensions. (300, 300) works well here. 4. Code def normalize_filled(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) im, cnt, _ = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # fill shape cv2.fillPoly(img, pts=cnt, color=(255,255,255)) bounding_rect = cv2.boundingRect(cnt[0]) img_cropped_bounding_rect = img[bounding_rect[1]:bounding_rect[1] + bounding_rect[3], bounding_rect[0]:bounding_rect[0] + bounding_rect[2]] # resize all to same size img_resized = cv2.resize(img_cropped_bounding_rect, (300, 300)) return img_resized imgs = [imgQuery, imgHDMI, imgDVI, img5PinDin, imgDB25] imgs = [normalize_filled(i) for i in imgs] for i in range(1, 6): plt.subplot(2, 3, i), plt.imshow(imgs[i - 1], cmap='gray') print(cv2.matchShapes(imgs[0], imgs[i - 1], 1, 0.0))
Contour
55,529,371
11
I'm trying to use OpenCV to extract tags from Nike images. This is a tutorial code taken from: http://opencv-code.com/tutorials/ocr-ing-nikes-new-rsvp-program/ I've modified few lines of code though and there is no error in that part (not sure if it's working because I haven't been able to successfully completely run it.) When I run command 'python a.py'. This error is displayed:- Traceback (most recent call last): File "a.py", line 42, in <module> otcnt = [c for c in cnt if cv2.contourArea(c) < 100] TypeError: contour is not a numpy array, neither a scalar a.py:- #!/usr/bin/env python import numpy as np import cv2 import cv2.cv as cv def do_ocr(img0): pass if __name__ == "__main__": img0 = cv2.imread('nike-1.jpg') if img0 == None: import sys sys.exit() do_ocr(img0) img1 = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY) img2 = cv2.adaptiveThreshold(img1, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 45, 0) size = np.size(img2) skel = np.zeros(img2.shape,np.uint8) ret,img2 = cv2.threshold(img2,127,255,0) element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3)) done = False while( not done): eroded = cv2.erode(img2,element) temp = cv2.dilate(eroded,element) temp = cv2.subtract(img2,temp) skel = cv2.bitwise_or(skel,temp) img2 = eroded.copy() zeros = size - cv2.countNonZero(img2) if zeros==size: done = True img3 = img2 img4 = cv2.copyMakeBorder(img3, 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0) cv2.floodFill(img4, None, (0,0), 255) img5 = cv2.erode(255-img4, np.ones((3,3), np.uint8), iterations=2) cnt = cv2.findContours(img5, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0] cnt = [c for c in cnt if cv2.contourArea(c) > 5000] mask = np.zeros(img0.shape[:2], np.uint8) cv2.drawContours(mask, cnt, -1, 255, -1) dst = img2 & mask cnt = cv2.findContours(dst.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) otcnt = [c for c in cnt if cv2.contourArea(c) < 100] cv2.drawContours(dst, otcnt, -1, 0, -1) api = tesseract.TessBaseAPI() api.Init(".", "eng", tesseract.OEM_DEFAULT) api.SetVariable("tessedit_char_whitelist", "#ABCDEFGHIJKLMNOPQRSTUVWXYZ") api.SetPageSegMode(tesseract.PSM_SINGLE_LINE) image = cv.CreateImageHeader(dst.shape[:2], cv.IPL_DEPTH_8U, 1) cv.SetData(image, dst.tostring(), dst.dtype.itemsize * dst.shape[1]) tesseract.SetCvImage(image, api) print api.GetUTF8Text().string() I'm very new to Python programming (and Python syntax) and I've to do this in Python anyway. I shall be very thankful to you if you can either post the complete correct version of it or finger point which line of code should be replaced with which one. Thanks p.s. My first question at stackoverflow so apologies if not following any convention.
This runtime error is caused by the fact that when you redefine cnt on line 42 as cnt = cv2.findContours(dst.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) you are setting it is the tuple of the two return values of cv2.findContours. Look at your earlier call to the function on line 37 as a guide. All you need to do is change line 42 to cnt = cv2.findContours(dst.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0] Your next issue is that you haven't imported tesseract.
Contour
17,628,627
11
I need to calculate the area of a blob/an object in a grayscale picture (loading it as Mat, not as IplImage) using OpenCV. I thought it would be a good idea to get the coordinates of the edges (number of edges change form object to object) or to get all coordinates of the contour and then use contourArea() to calculate the area of my object. I deleted all noise and got some nice and satisfying contours by using findContours() (programming in C++). findContours(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy,int mode, int method, Point offset=Point()); Now I got to understand that param contours already owns the coordinates of all contours of my object. Did I get that right? If yes, it there a way to access them? And if no, how do I get the coordinates of the contour anyway?
contours is actually defined as vector<vector<Point> > contours; And now I think it's clear how to access its points. The contour area is calculated by a function nicely called contourArea(): for (unsigned int i = 0; i < contours.size(); i++) { std::cout << "# of contour points: " << contours[i].size() << std::endl; for (unsigned int j=0; j<contours[i].size(); j++) { std::cout << "Point(x,y)=" << contours[i][j] << std::endl; } std::cout << " Area: " << contourArea(contours[i]) << std::endl; }
Contour
11,631,533
11
I want to represent data with 2 variables in 2D format. The value is represented by color and the 2 variables as the 2 axis. I am using the contourf function to plot my data: clc; clear; load('dataM.mat') cMap=jet(256); %set the colomap using the "jet" scale F2=figure(1); [c,h]=contourf(xrow,ycol,BDmatrix,50); set(h, 'edgecolor','none'); xlim([0.0352 0.3872]); ylim([0.0352 0.3872]); colormap(cMap); cb=colorbar; caxis([0.7 0.96]); % box on; hold on; Both xrow and ycol are 6x6 matrices representing the coordinates. BDmatrix is the 6x6 matrix representing the corresponding data. However, what I get is this: The following is the xrow and yrow matices: The following is the BDmatrix matices: Would it be possible for the contour color to vary smoothly rather than appearing as straight lines joining the data points? The problem of this figure is the coarse-granularity which is not appealing. I have tried to replace contourf with imagec but it seems not working. I am using MATLAB R2015b.
You can interpolate your data. newpoints = 100; [xq,yq] = meshgrid(... linspace(min(min(xrow,[],2)),max(max(xrow,[],2)),newpoints ),... linspace(min(min(ycol,[],1)),max(max(ycol,[],1)),newpoints )... ); BDmatrixq = interp2(xrow,ycol,BDmatrix,xq,yq,'cubic'); [c,h]=contourf(xq,yq,BDmatrixq); Choose the "smoothness" of the new plot via the parameter newpoints. To reduce the Color edges, you can increase the number of value-steps. By default this is 10. The following code increases the number of value-steps to 50: [c,h]=contourf(xq,yq,BDmatrixq,50); A 3D-surf plot would be more suitable for very smooth color-shading. Just rotate it to a top-down view. The surf plot is also much faster than the contour plot with a lot of value-steps. f = figure; ax = axes('Parent',f); h = surf(xq,yq,BDmatrixq,'Parent',ax); set(h, 'edgecolor','none'); view(ax,[0,90]); colormap(Jet); colorbar; Note 1: Cubic interpolation is not shape-preserving. That means, the interpolated shape can have maxima which are greater than the maximum values of the original BDmatrix (and minima which are less). If BDmatrix has noisy values, the interpolation might be bad. Note 2: If you generated xrow and yrow by yourself (and know the limits), than you do not need that min-max-extraction what I did. Note 3: After adding screenshots of your data matrices to your original posting, one can see, that xrow and ycol come from an ndgrid generator. So we also must use this here in order to be consistent. Since interp2 needs meshgrid we have to switch to griddedInterpolant: [xq,yq] = ndgrid(... linspace(min(min(xrow,[],1)),max(max(xrow,[],1)),newpoints ),... linspace(min(min(ycol,[],2)),max(max(ycol,[],2)),newpoints )... ); F = griddedInterpolant(xrow,ycol,BDmatrix,'cubic'); BDmatrixq = F(xq,yq);
Contour
44,816,434
10
I'm trying to export the results of the scikit-image.measure.find_contours() function as a shapefile or geojson after running on a satellite image. The output is an array like (row, column) with coordinates along the contours, of which there are many. How do I plot the coordinates of the various contours, and export this to a shapefile (can set appropriate projection etc.)? My current code where 'mask' is my processed image: from skimage import measure import matplotlib.pyplot as plt contours = measure.find_contours(mask, 0.5) plt.imshow(mask) for n, contour in enumerate(contours): plt.plot(contour[:,1], contour[:, 0], linewidth=1)
Something along the lines of the following, adapted from a post by the primary developer of rasterio and fiona, should work, though I'm sure you'll need to adapt a little more. It uses rasterio.features.shapes to identify contiguous regions in an image that have some value and return the associated coordinates, based on the transform of the raster. It then writes those records to a shapefile using fiona. import fiona import rasterio.features schema = {"geometry": "Polygon", "properties": {"value": "int"}} with rasterio.open(raster_filename) as raster: image = raster.read() # use your function to generate mask mask = your_thresholding_function(image) # and convert to uint8 for rasterio.features.shapes mask = mask.astype('uint8') shapes = rasterio.features.shapes(mask, transform=raster.transform) # select the records from shapes where the value is 1, # or where the mask was True records = [{"geometry": geometry, "properties": {"value": value}} for (geometry, value) in shapes if value == 1] with fiona.open(shape_filename, "w", "ESRI Shapefile", crs=raster.crs.data, schema=schema) as out_file: out_file.writerecords(records)
Contour
41,487,642
10
What is the algorithm that Matlab uses to generate contour lines? In other words, how does it transform level data on a grid into a set of lines? What I would like is: the local criterion to obtain points that lie on the contour? the global procedure to capture all contour lines? I don't need detailed specifics about the underlying code, but the general principles would be helpful for me to interpret the output. I use contour (and derivatives) in my research, and want to get a sense of the numerical errors that are introduced in this step. It looks like a very simple question, but I couldn't find an explanation in Matlab's documentation, nor found anything on SO or elsewhere on the web. My apologies if it turns about to be easy to find after all.
From MATLAB® - Graphics - R2012a, from page 5-73 to page 5-76: The Contouring Algorithm The contourc function calculates the contour matrix for the other contour functions. It is a low-level function that is not called from the command line. The contouring algorithm first determines which contour levels to draw. If you specified the input vector v, the elements of v are the contour level values, and length(v) determines the number of contour levels generated. If you do not specify v, the algorithm chooses no more than 20 contour levels that are divisible by 2 or 5. The height matrix Z has associated X and Y matrices that locate each value in Z at the intersection of a row and a column, or these matrices are inferred when they are unspecified. The row and column widths can vary, but typically they are constant (i.e., Z is a regular grid). Before calling contourc to interpolate contours, contourf pads the height matrix with an extra row or column on each edge. It assigns z-values to the added grid cells that are well below the minimum value of the matrix. The padded values enable contours to close at the matrix boundary so that they can be filled with color. When contourc creates the contour matrix, it replaces the x,y coordinates containing the low z-values with NaNs to prevent contour lines that pass along matrix edges from being displayed. This is why contour matrices returned by contourf sometimes contain NaN values. Set the current level, c, equal to the lowest contour level to be plotted within the range [min(Z) max(Z)]. The contouring algorithm checks each edge of every square in the grid to see if c is between the two z values for the edge points. If so, a contour at that level crosses the edge, and a linear interpolation is performed: t=(c-Z0)/(Z1-Z0) Z0 is the z value at one edge point, and Z1 is the z value at the other edge point. Start indexing a new contour line (i=1) for level c by interpolating x and y: cx(i) = X0+t*(X1-X0) cy(i) = Y0+t*(Y1-Y0) Walk around the edges of the square just entered; the contour exits at the next edge with z values that bracket c. Increment i, compute t for the edge, and then compute cx(i) and cy(i), as above. Mark the square as having been visited. Keep checking the edges of each square entered to determine the exit edge until the line(cx,cy) closes on its initial point or exits the grid. If the square being entered is already marked, the contour line closes there. Copy cx, cy, c, and i to the contour line data structure (the matrix returned by contouring functions, described shortly). Reinitialize cx, cy, and i. Move to an unmarked square and test its edges for intersections; when you find one at level c, repeat the preceding operations. Any number of contour lines can exist for a given level. Clear all the markers, increment the contour level, and repeat until c exceeds max(Z). Extra logic is needed for squares where a contour passes through all four edges (saddle points) to determine which pairs of edges to connect. contour, contour3, and contourf return a two-row matrix that specifies all the contour lines: C = [ value1 xdata(1) xdata(2)... numv ydata(1) ydata(2)...] The first row of the column that begins each definition of a contour line contains the contour value, as specified by v and used by clabel. Beneath that value is the number of (x,y) vertices in the contour line. Remaining columns contain the data for the (x,y) pairs. For example, the contour matrix calculated by C = contour(peaks(3)) is as follows. The circled values begin each definition of a contour line.
Contour
39,274,728
10
I'm trying to find contours in a binary image which is a numpy array a = np.array(np.random.rand(1024,768),dtype='float32') _, t2 = cv2.threshold(a,127,255,0) im2, contours, hierarchy = cv2.findContours(t2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) When I try to run that code I get this error OpenCV Error: Unsupported format or combination of formats ([Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only) in cvStartFindContours
As the error message states - the only format supported, when the mode is not CV_RETR_FLOODFILL, is CV_8UC1 => single channel 8 bit, unsigned integer matrix. When the mode is CV_RETR_FLOODFILL, the only supported format is CV_32SC1 - 32 bit signed... Since you are passing array of float32, it is CV_32FC1 - 32 bit, floating, which is not supported. You have to use array of integer.
Contour
36,721,936
10
I'm a program that find contours in a stream, for example : I want to find "set of points " that can describe this contours say like the red line : the yellow part is the the moments of the contours , I tried to use fitLine function of opencv but the result was nonsense, any Idea how can I get the middle line of a contours, that should represent the key aspect of my Contours . by the way **I'm not asking for codes ! ** just a hint how can I do that ? thanks in advance for any help
maybe try this approach with a distance transform and ridge detection: cv::Mat input = cv::imread("fitLine.jpg"); cv::Mat gray; cv::cvtColor(input,gray,CV_BGR2GRAY); cv::Mat mask = gray>100; cv::imshow("mask",mask); cv::Mat dt; cv::distanceTransform(mask,dt,CV_DIST_L1,CV_DIST_MASK_PRECISE); cv::imshow("dt", dt/15.0f); cv::imwrite("fitLineOut.png",255*dt/15.0f); //care: this part doesn't work for diagonal lines, a ridge detection would be better!! cv::Mat lines = cv::Mat::zeros(input.rows, input.cols, CV_8UC1); //only take the maxDist of each row for(unsigned int y=0; y<dt.rows; ++y) { float biggestDist = 0; cv::Point2i biggestDistLoc(0,0); for(unsigned int x=0; x<dt.cols; ++x) { cv::Point2i current(x,y); if(dt.at<float>(current) > biggestDist) { biggestDist = dt.at<float>(current) ; biggestDistLoc = current; } } lines.at<unsigned char>(biggestDistLoc) = 255; } //and the maxDist of each row for(unsigned int x=0; x<dt.cols; ++x) { float biggestDist = 0; cv::Point2i biggestDistLoc(0,0); for(unsigned int y=0; y<dt.rows; ++y) { cv::Point2i current(x,y); if(dt.at<float>(current) > biggestDist) { biggestDist = dt.at<float>(current) ; biggestDistLoc = current; } } lines.at<unsigned char>(biggestDistLoc) = 255; } cv::imshow("max", lines); cv::waitKey(-1); the idea is to compute the distance transform and find the ridges within the contour. this is how the distance transformed image looks like: you can see that there is a local ridge maximum in the middle of the lines. then I use a very simple method: just find the maximum distance in each row/column. That is very sloppy and should be changed for a real ridge detection or thinning method!!!! edit: additional description: The idea is to find all points that are in the "middle" of the contour. In mathematics/graphics, the medial axis in some kind of "middle" of an object and it's definition is to be all points that have the same minimum distance to at least two contour points at the same time. A way to approximate the medial axis is to compute the distance transform. The distance transform is a matrix that holds for each pixel the distance to the next object point (for example a contour of an object)(see http://en.wikipedia.org/wiki/Distance_transform too). That's the first image. There you can see that the points in the middle of the lines are a little bit brighter than the points closer to the border, which means that the brightest points along the lines can be interpreted as the medial axis (approximation), since if you move away from it (orthogonal to the line direction) the distances become smaller, so the peak is the point where the distance to both borders in close to equality. That way if you can find those "ridges" in the distance transform, you're done. Ridge detection is normally done by a Harris Operator (see http://en.wikipedia.org/wiki/Ridge_detection ). In the fast and dirty version that I've posted, I try to detect the ridge by accepting only the maximum value in each line and in each row. That's ok for most horizontal and vertical ridges, but will fail for diagonal ones. So maybe you really want to exchange the for loops with a real ridge detection.
Contour
21,675,509
10
I have a bivariate gaussian I defined as follow: I=[1 0;0 1]; mu=[0,0]; sigma=0.5*I; beta = mvnrnd(mu,sigma,100); %100x2 matrix where each column vector is a variable. now I want to plot a contour of the pdf of the above matrix. What I did: Z = mvnpdf(beta,mu,sigma); %100x1 pdf matrix Now I want to plot a contour of the bivariate gaussian beta. I know I should use the command contour but this one require Z to be a square matrix. how do I solve this? I am very confused and not sure how to plot the contour of the bivariate gaussian!! ANY HELP IS GREATLY APPRECIATED.. Thank you
You need to define your x, y axes and use meshgrid (or ndgrid) to generate all combinations of x, y values, in the form of two matrices X and Y. You then compute the Z values (your Gaussian pdf) for those X and Y, and plot Z as a function of X , Y using contour (contour plot), or perhaps surf (3D plot). mu = [0,0]; %// data sigma = [.5 0; 0 .5]; %// data x = -5:.1:5; %// x axis y = -4:.1:4; %// y axis [X Y] = meshgrid(x,y); %// all combinations of x, y Z = mvnpdf([X(:) Y(:)],mu,sigma); %// compute Gaussian pdf Z = reshape(Z,size(X)); %// put into same size as X, Y %// contour(X,Y,Z), axis equal %// contour plot; set same scale for x and y... surf(X,Y,Z) %// ... or 3D plot
Contour
20,170,083
10
I'm working with some custom functions and I need to draw contours for them based on multiple values for the parameters. Here is an example function: I need to draw such a contour plot: Any idea? Thanks.
First you construct a function, fourvar that takes those four parameters as arguments. In this case you could have done it with 3 variables one of which was lambda_2 over lambda_1. Alpha1 is fixed at 2 so alpha_1/alpha_2 will vary over 0-10. fourvar <- function(a1,a2,l1,l2){ a1* integrate( function(x) {(1-x)^(a1-1)*(1-x^(l2/l1) )^a2} , 0 , 1)$value } The trick is to realize that the integrate function returns a list and you only want the 'value' part of that list so it can be Vectorize()-ed. Second you construct a matrix using that function: mat <- outer( seq(.01, 10, length=100), seq(.01, 10, length=100), Vectorize( function(x,y) fourvar(a1=2, x/2, l1=2, l2=y/2) ) ) Then the task of creating the plot with labels in those positions can only be done easily with lattice::contourplot. After doing a reasonable amount of searching it does appear that the solution to geom_contour labeling is still a work in progress in ggplot2. The only labeling strategy I found is in an external package. However, the 'directlabels' package's function directlabel does not seem to have sufficient control to spread the labels out correctly in this case. In other examples that I have seen, it does spread the labels around the plot area. I suppose I could look at the code, but since it depends on the 'proto'-package, it will probably be weirdly encapsulated so I haven't looked. require(reshape2) mmat <- melt(mat) str(mmat) # to see the names in the melted matrix g <- ggplot(mmat, aes(x=Var1, y=Var2, z=value) ) g <- g+stat_contour(aes(col = ..level..), breaks=seq(.1, .9, .1) ) g <- g + scale_colour_continuous(low = "#000000", high = "#000000") # make black install.packages("directlabels", repos="http://r-forge.r-project.org", type="source") require(directlabels) direct.label(g) Note that these are the index positions from the matrix rather than the ratios of parameters, but that should be pretty easy to fix. This, on the other hand, is how easilyy one can construct it in lattice (and I think it looks "cleaner": require(lattice) contourplot(mat, at=seq(.1,.9,.1))
Contour
19,079,152
10
Here is my code to plot some data: from scipy.interpolate import griddata from numpy import linspace import matplotlib.pyplot as plt meanR = [9.95184937, 9.87947708, 9.87628496, 9.78414422, 9.79365258, 9.96168969, 9.87537519, 9.74536093, 10.16686878, 10.04425475, 10.10444126, 10.2917172 , 10.16745917, 10.0235203 , 9.89914 , 10.11263505, 9.99756449, 10.17861254, 10.04704248] koord = [[1,4],[3,4],[1,3],[3,3],[2,3],[1,2],[3,2],[2,2],[1,1],[3,1],[2,1],[1,0],[3,0],[0,3],[4,3],[0,2],[4,2],[0,1],[4,1]] x,y=[],[] for i in koord: x.append(i[0]) y.append(i[1]) z = meanR xi = linspace(-2,6,300); yi = linspace(-2,6,300); zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic') CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet) plt.scatter(x,y,marker='o',c='b',s=15) plt.xlim(min(x),max(x)) plt.ylim(min(y),max(y)) plt.show() In result we have: How can I inscribe it in a circle? something like this
Because you don't seem to need any axes you can also use a normal projection, remove the axes and draw a circle. I had some fun and added some bonus ears, a nose and a color bar. I annotated the code, I hope it is clear. from __future__ import print_function from __future__ import division from __future__ import absolute_import import scipy.interpolate import numpy import matplotlib import matplotlib.pyplot as plt # close old plots plt.close("all") # some parameters N = 300 # number of points for interpolation xy_center = [2,2] # center of the plot radius = 2 # radius # mostly original code meanR = [9.95184937, 9.87947708, 9.87628496, 9.78414422, 9.79365258, 9.96168969, 9.87537519, 9.74536093, 10.16686878, 10.04425475, 10.10444126, 10.2917172 , 10.16745917, 10.0235203 , 9.89914 , 10.11263505, 9.99756449, 10.17861254, 10.04704248] koord = [[1,4],[3,4],[1,3],[3,3],[2,3],[1,2],[3,2],[2,2],[1,1],[3,1],[2,1],[1,0],[3,0],[0,3],[4,3],[0,2],[4,2],[0,1],[4,1]] x,y = [],[] for i in koord: x.append(i[0]) y.append(i[1]) z = meanR xi = numpy.linspace(-2, 6, N) yi = numpy.linspace(-2, 6, N) zi = scipy.interpolate.griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic') # set points > radius to not-a-number. They will not be plotted. # the dr/2 makes the edges a bit smoother dr = xi[1] - xi[0] for i in range(N): for j in range(N): r = numpy.sqrt((xi[i] - xy_center[0])**2 + (yi[j] - xy_center[1])**2) if (r - dr/2) > radius: zi[j,i] = "nan" # make figure fig = plt.figure() # set aspect = 1 to make it a circle ax = fig.add_subplot(111, aspect = 1) # use different number of levels for the fill and the lines CS = ax.contourf(xi, yi, zi, 60, cmap = plt.cm.jet, zorder = 1) ax.contour(xi, yi, zi, 15, colors = "grey", zorder = 2) # make a color bar cbar = fig.colorbar(CS, ax=ax) # add the data points # I guess there are no data points outside the head... ax.scatter(x, y, marker = 'o', c = 'b', s = 15, zorder = 3) # draw a circle # change the linewidth to hide the circle = matplotlib.patches.Circle(xy = xy_center, radius = radius, edgecolor = "k", facecolor = "none") ax.add_patch(circle) # make the axis invisible for loc, spine in ax.spines.iteritems(): # use ax.spines.items() in Python 3 spine.set_linewidth(0) # remove the ticks ax.set_xticks([]) ax.set_yticks([]) # Add some body parts. Hide unwanted parts by setting the zorder low # add two ears circle = matplotlib.patches.Ellipse(xy = [0,2], width = 0.5, height = 1.0, angle = 0, edgecolor = "k", facecolor = "w", zorder = 0) ax.add_patch(circle) circle = matplotlib.patches.Ellipse(xy = [4,2], width = 0.5, height = 1.0, angle = 0, edgecolor = "k", facecolor = "w", zorder = 0) ax.add_patch(circle) # add a nose xy = [[1.5,3], [2,4.5],[2.5,3]] polygon = matplotlib.patches.Polygon(xy = xy, facecolor = "w", zorder = 0) ax.add_patch(polygon) # set axes limits ax.set_xlim(-0.5, 4.5) ax.set_ylim(-0.5, 4.5) plt.show()
Contour
15,361,143
10
Does anyone know of a way to turn the output of contourLines polygons in order to plot as filled contours, as with filled.contours. Is there an order to how the polygons must then be plotted in order to see all available levels? Here is an example snippet of code that doesn't work: #typical plot filled.contour(volcano, color.palette = terrain.colors) #try cont <- contourLines(volcano) fun <- function(x) x$level LEVS <- sort(unique(unlist(lapply(cont, fun)))) COLS <- terrain.colors(length(LEVS)) contour(volcano) for(i in seq(cont)){ COLNUM <- match(cont[[i]]$level, LEVS) polygon(cont[[i]], col=COLS[COLNUM], border="NA") } contour(volcano, add=TRUE)
A solution that uses the raster package (which calls rgeos and sp). The output is a SpatialPolygonsDataFrame that will cover every value in your grid: library('raster') rr <- raster(t(volcano)) rc <- cut(rr, breaks= 10) pols <- rasterToPolygons(rc, dissolve=T) spplot(pols) Here's a discussion that will show you how to simplify ('prettify') the resulting polygons.
Contour
14,379,828
10
I'm working on a segmentation algorithme for medical images and during the process it must display the evolving contour on the original image. I'm working with greyscale JPEG. In order to display the contours I use the drawContours function but I can't manage to draw a color contour. I would like to draw a red contour on the greyscale image but it only appears black or white. Here is the section of the code: Mat_<uchar> matrix = imread(path,0); int row = matrix.rows; int col = matrix.cols; Mat_<uchar> maskInter(row,col); for (int i=0; i<row; i++) for (int j=0; j<col; j++) { if ((double)matrix(i,j) <0) {maskInter(i,j)=255;} else {maskInter(i,j)=0;} }; vector<vector<Point> > contours; vector<Vec4i> hierarchy; Mat mat_out = maskInter.clone(); findContours( mat_out, contours, hierarchy, CV_RETR_TREE , CHAIN_APPROX_SIMPLE); drawContours( img, contours, -1, RGB(255,0,0),1.5,8,hierarchy,2,Point()); namedWindow(title); moveWindow(title, 100, 100); imshow(title, img); waitKey(0); Is it possible to display a color contour on a greyscale image? Thanks
You need a 3-channel (RGB) image in order to draw and display colors. Your Mat_<uchar> matrix is only one channel. You can convert your grayscale image to a color image as follows: // read image cv::Mat img_gray = imread(path,0); // create 8bit color image. IMPORTANT: initialize image otherwise it will result in 32F cv::Mat img_rgb(img_gray.size(), CV_8UC3); // convert grayscale to color image cv::cvtColor(img_gray, img_rgb, CV_GRAY2RGB);
Contour
13,441,873
10
I am developing some image processing tools in iOS. Currently, I have a contour of features computed, which is of type InputArrayOfArrays. Declared as: std::vector<std::vector<cv::Point> > contours_final( temp_contours.size() ); Now, I would like to extract areas of the original RGB picture circled by contours and may further store sub-image as cv::Mat format. How can I do that? Thanks in advance!
I'm guessing what you want to do is just extract the regions in the the detected contours. Here is a possible solution: using namespace cv; int main(void) { vector<Mat> subregions; // contours_final is as given above in your code for (int i = 0; i < contours_final.size(); i++) { // Get bounding box for contour Rect roi = boundingRect(contours_final[i]); // This is a OpenCV function // Create a mask for each contour to mask out that region from image. Mat mask = Mat::zeros(image.size(), CV_8UC1); drawContours(mask, contours_final, i, Scalar(255), CV_FILLED); // This is a OpenCV function // At this point, mask has value of 255 for pixels within the contour and value of 0 for those not in contour. // Extract region using mask for region Mat contourRegion; Mat imageROI; image.copyTo(imageROI, mask); // 'image' is the image you used to compute the contours. contourRegion = imageROI(roi); // Mat maskROI = mask(roi); // Save this if you want a mask for pixels within the contour in contourRegion. // Store contourRegion. contourRegion is a rectangular image the size of the bounding rect for the contour // BUT only pixels within the contour is visible. All other pixels are set to (0,0,0). subregions.push_back(contourRegion); } return 0; } You might also want to consider saving the individual masks to optionally use as a alpha channel in case you want to save the subregions in a format that supports transparency (e.g. png). NOTE: I'm NOT extracting ALL the pixels in the bounding box for each contour, just those within the contour. Pixels that are not within the contour but in the bounding box are set to 0. The reason is that your Mat object is an array and that makes it rectangular. Lastly, I don't see any reason for you to just save the pixels in the contour in a specially created data structure because you would then need to store the position for each pixel in order to recreate the image. If your concern is saving space, that would not save you much space if at all. Saving the tightest bounding box would suffice. If instead you wish to just analyze the pixels in the contour region, then save a copy of the mask for each contour so that you can use it to check which pixels are within the contour.
Contour
10,176,184
10
I would like to do a 3D contour plot using Mayavi in exactly the same way as the third figure on this page (a hydrogen electron cloud model) : http://www.sethanil.com/python-for-reseach/5 I have a set of data points which I created using my own model which I would like to use. The data points are stored in a multi-dimensional numpy array like so: XYZV = [[1, 2, 3, 4], [6, 7, 8, 9], ... [4, 5, 6, 7]] The data points are not uniformly spread in XYZ space and not stored in any particular order. I think the example uses a meshgrid to generate the data points - I have looked this up but totally don't understand it. Any help would be much appreciated? (source: sethanil.com)
The trick is to interpolate over a grid before you plot - I'd use scipy for this. Below R is a (500,3) array of XYZ values and V is the "magnitude" at each XYZ point. from scipy.interpolate import griddata import numpy as np # Create some test data, 3D gaussian, 200 points dx, pts = 2, 100j N = 500 R = np.random.random((N,3))*2*dx - dx V = np.exp(-( (R**2).sum(axis=1)) ) # Create the grid to interpolate on X,Y,Z = np.mgrid[-dx:dx:pts, -dx:dx:pts, -dx:dx:pts] # Interpolate the data F = griddata(R, V, (X,Y,Z)) From here it's a snap to display our data: from mayavi.mlab import * contour3d(F,contours=8,opacity=.2 ) This gives a nice (lumpy) Gaussian. Take a look at the docs for griddata, note that you can change the interpolation method. If you have more points (both on the interpolated grid, and on the data set), the interpolation gets better and better represents the underlying function you're trying to illustrate. Here is the above example at 10K points and a finer grid:
Contour
9,419,451
10
I installed kubernetes cluster using kubeadm following this guide. After some period of time, I decided to reinstall K8s but run into troubles with removing all related files and not finding any docs on official site how to remove cluster installed via kubeadm. Did somebody meet the same problems and know the proper way of removing all files and dependencies? Thank you in advance. For more information, I removed kubeadm, kubectl and kubelet using apt-get purge/remove but when I started installing the cluster again I got next errors: [preflight] Some fatal errors occurred: Port 6443 is in use Port 10251 is in use Port 10252 is in use /etc/kubernetes/manifests is not empty /var/lib/kubelet is not empty Port 2379 is in use /var/lib/etcd is not empty
In my "Ubuntu 16.04", I use next steps to completely remove and clean Kubernetes (installed with "apt-get"): kubeadm reset sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube* sudo apt-get autoremove sudo rm -rf ~/.kube And restart the computer.
Kubernetes
44,698,283
94
We created a kubernetes cluster for a customer about one year ago with two environments; staging and production separated in namespaces. We are currently developing the next version of the application and need an environment for this development work, so we've created a beta environment in its own namespace. This is a bare metal kubernetes cluster with MetalLB and and nginx-ingress. The nginx ingress controllers is installed with helm and the ingresses are created with the following manifest (namespaces are enforced by our deployment pipeline and are not visible in the manifest): apiVersion: extensions/v1beta1 kind: Ingress metadata: name: api-ingress annotations: #ingress.kubernetes.io/ssl-redirect: "true" #kubernetes.io/tls-acme: "true" #certmanager.k8s.io/issuer: "letsencrypt-staging" #certmanager.k8s.io/acme-challenge-type: http01 kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/configuration-snippet: | more_set_headers "X-Robots-Tag: noindex, nofollow"; nginx.ingress.kubernetes.io/enable-cors: "true" nginx.ingress.kubernetes.io/cors-allow-methods: "GET, OPTIONS" nginx.ingress.kubernetes.io/cors-allow-origin: "*" nginx.ingress.kubernetes.io/cors-allow-credentials: "true" spec: tls: - hosts: - ${API_DOMAIN} secretName: api-cert rules: - host: ${API_DOMAIN} http: paths: - backend: serviceName: api servicePort: 80 When applying the manifest kubernetes responds with the following error: Error from server (InternalError): error when creating "STDIN": Internal error occurred: failed calling webhook "validate.nginx.ingress.kubernetes.io": Post https://ingress-nginx-controller-admission.ingress-nginx.svc:443/extensions/v1beta1/ingresses?timeout=30s: service "ingress-nginx-controller-admission" not found I've attempted to update the apiVersion of the ingress manifest to networking.k8s.io/v1beta1 (this is the apiVersion the new nginx-ingress controllers are installed with via helm), but I'm getting the same error. My initial suspicion is that this is related to a change in the nginx-ingress between the current installation and the installation from one year ago, even if the ingress controllers are separated by namespaces. But i cant find any services called ingress-nginx-controller-admission in any of my namespaces, so I'm clueless how to proceed.
I had the same problem and found a solution from another SO thread. I had previously installed nginx-ingress using the manifests. I deleted the namespace it created, and the clusterrole and clusterrolebinding as noted in the documentation, but that does not remove the ValidatingWebhookConfiguration that is installed in the manifests, but NOT when using helm by default. As Arghya noted above, it can be enabled using a helm parameter. Once I deleted the ValidatingWebhookConfiguration, my helm installation went flawlessly. kubectl delete -A ValidatingWebhookConfiguration ingress-nginx-admission
Kubernetes
61,365,202
94
I have been trying to install nginx ingress using helm version 3 helm install my-ingress stable/nginx-ingress But Helm doesn't seem to be able to find it's official stable repo. It gives the message: Error: failed to download "stable/nginx-ingress" (hint: running helm repo update may help) I tried helm repo update. But it doesn't help. I tried listing the repos helm repo list but it is empty. I tried to add the stable repo: helm repo add stable https://github.com/helm/charts/tree/master/stable But it fails with: Error: looks like "https://github.com/helm/charts/tree/master/stable" is not a valid chart repository or cannot be reached: failed to fetch https://github.com/helm/charts/tree/master/stable/index.yaml : 404 Not Found
The stable repository is hosted on https://kubernetes-charts.storage.googleapis.com/. So, try the following: helm repo add stable https://kubernetes-charts.storage.googleapis.com/ EDIT 2020-11-16: the above repository seems to have been deprecated. The following should now work instead: helm repo add stable https://charts.helm.sh/stable
Kubernetes
57,970,255
92
i'm getting an error when running kubectl one one machine (windows) the k8s cluster is running on CentOs 7 kubernetes cluster 1.7 master, worker Here's my .kube\config apiVersion: v1 clusters: - cluster: certificate-authority-data: REDACTED server: https://10.10.12.7:6443 name: kubernetes contexts: - context: cluster: kubernetes user: system:node:localhost.localdomain name: system:node:localhost.localdomain@kubernetes current-context: system:node:localhost.localdomain@kubernetes kind: Config preferences: {} users: - name: system:node:localhost.localdomain user: client-certificate-data: REDACTED client-key-data: REDACTED the cluster is built using kubeadm with the default certificates on the pki directory kubectl unable to connect to server: x509: certificate signed by unknown authority
One more solution in case it helps anyone: My scenario: using Windows 10 Kubernetes installed via Docker Desktop ui 2.1.0.1 the installer created config file at ~/.kube/config the value in ~/.kube/config for server is https://kubernetes.docker.internal:6443 using proxy Issue: kubectl commands to this endpoint were going through the proxy, I figured it out after running kubectl --insecure-skip-tls-verify cluster-info dump which displayed the proxy html error page. Fix: just making sure that this URL doesn't go through the proxy, in my case in bash I used export no_proxy=$no_proxy,*.docker.internal
Kubernetes
46,234,295
92
Have been using Kubernetes secrets up to date. Now we have ConfigMaps as well. What is the preferred way forward - secrets or config maps? P.S. After a few iterations we have stabilised at the following rule: configMaps are per solution domain (can be shared across microservices within the domain, but ultimately are single purpose config entries) secrets are shared across solution domains, usually represent third party systems or databases
I'm the author of both of these features. The idea is that you should: Use Secrets for things which are actually secret like API keys, credentials, etc Use ConfigMaps for not-secret configuration data In the future, there will likely be some differentiators for secrets like rotation or support for backing the secret API w/ HSMs, etc. In general, we like intent-based APIs, and the intent is definitely different for secret data vs. plain old configs.
Kubernetes
36,912,372
92
I would like to deploy an application cluster by managing my deployment via Kubernetes Deployment object. The documentation has me extremely confused. My basic layout has the following components that scale independently: API server UI server Redis cache Timer/Scheduled task server Technically, all 4 above belong in separate pods that are scaled independently. My questions are: Do I need to create pod.yml files and then somehow reference them in the deployment.yml file or can a deployment file also embed pod definitions? Kubernetes documentation seems to imply that the spec portion of Deployment is equivalent to defining one pod. Is that correct? What if I want to declaratively describe multi-pod deployments? Do I need multiple deployment.yml files?
Pagid's answer has most of the basics. You should create 4 Deployments for your scenario. Each deployment will create a ReplicaSet that schedules and supervises the collection of Pods for the Deployment. Each Deployment will most likely also require a Service in front of it for access. I usually create a single yaml file that has a Deployment and the corresponding Service in it. Here is an example for an nginx.yaml that I use: apiVersion: v1 kind: Service metadata: annotations: service.alpha.kubernetes.io/tolerate-unready-endpoints: "true" name: nginx labels: app: nginx spec: type: NodePort ports: - port: 80 name: nginx targetPort: 80 nodePort: 32756 selector: app: nginx --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: nginxdeployment spec: replicas: 3 template: metadata: labels: app: nginx spec: containers: - name: nginxcontainer image: nginx:latest imagePullPolicy: Always ports: - containerPort: 80 Here some additional information for clarification: A Pod is not a scalable unit. A Deployment that schedules pods is. A Deployment is meant to represent a single group of pods fulfilling a single purpose together. You can have many Deployments work together in the virtual network of the cluster. For accessing a Deployment that may consist of many Pods running on different nodes you have to create a Service. Deployments are meant to contain stateless services. If you need to store a state you need to create StatefulSet instead (e.g. for a database service).
Kubernetes
43,217,006
90
I have the following image created by a Dockerfile: REPOSITORY TAG IMAGE ID CREATED SIZE ruby/lab latest f1903b1508cb 2 hours ago 729.6 MB And I have my following YAML file: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: ruby-deployment spec: replicas: 2 template: metadata: labels: app: ruby spec: containers: - name: ruby-app image: ruby/lab imagePullPolicy: IfNotPresent ports: - containerPort: 4567 When I create the deployment I got the following info in the pods: ruby-deployment-3830038651-sa4ii 0/1 ImagePullBackOff 0 7m ruby-deployment-3830038651-u1tvc 0/1 ImagePullBackOff 0 7m And the error Failed to pull image "ruby/lab:latest": Error: image ruby/lab not found from below: 8m 2m 6 {kubelet minikube} spec.containers{ruby} Normal Pulling pulling image "ruby/lab:latest" 8m 2m 6 {kubelet minikube} spec.containers{ruby} Warning Failed Failed to pull image "ruby/lab:latest": Error: image ruby/lab not found 8m 2m 6 {kubelet minikube} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "ruby" with ErrImagePull: "Error: image ruby/lab not found" Is really necessary to have registry in docker for this? I just want to make test locally and pass my code/repo to a friend for testing purposes Thanks
You can point your docker client to the VM's docker daemon by running eval $(minikube docker-env) Then you can build your image normally and create your kubernetes resources normally using kubectl. Make sure that you have imagePullPolicy: IfNotPresent in your YAML or JSON specs. Additionally, there is a flag to pass in insecure registries to the minikube VM. However, this must be specified the first time you create the machine. minikube start --insecure-registry You may also want to read this when using a private registry https://kubernetes.io/docs/concepts/containers/images/
Kubernetes
40,144,138
90
When I provision a Kubernetes cluster using kubeadm, I get my nodes tagged as "none". It's a known bug in Kubernetes and currently a PR is in progress. However, I would like to know if there is an option to add a Role name manually for the node. root@ip-172-31-14-133:~# kubectl get nodes NAME STATUS ROLES AGE VERSION ip-172-31-14-133 Ready master 19m v1.9.3 ip-172-31-6-147 Ready <none> 16m v1.9.3
This worked for me: kubectl label node cb2.4xyz.couchbase.com node-role.kubernetes.io/worker=worker NAME STATUS ROLES AGE VERSION cb2.4xyz.couchbase.com Ready custom,worker 35m v1.11.1 cb3.5xyz.couchbase.com Ready worker 29m v1.11.1 I could not delete/update the old label, but I can live with it.
Kubernetes
48,854,905
89
If I am running a container in privileged mode, does it have all the Kernel capabilities or do I need to add them separately?
Running in privileged mode indeed gives the container all capabilities. But it is good practice to always give a container the minimum requirements it needs. The Docker run command documentation refers to this flag: Full container capabilities (--privileged) The --privileged flag gives all capabilities to the container, and it also lifts all the limitations enforced by the device cgroup controller. In other words, the container can then do almost everything that the host can do. This flag exists to allow special use-cases, like running Docker within Docker. You can give specific capabilities using --cap-add flag. See man 7 capabilities for more info on those capabilities. The literal names can be used, e.g. --cap-add CAP_FOWNER.
Kubernetes
36,425,230
89
Both replica set and deployment have the attribute replica: 3, what's the difference between deployment and replica set? Does deployment work via replica set under the hood? configuration of deployment apiVersion: apps/v1 kind: Deployment metadata: name: my-deployment labels: my-label: my-value spec: replicas: 3 selector: matchLabels: my-label: my-value template: metadata: labels: my-label: my-value spec: containers: - name: app-container image: my-image:latest configuration of replica set apiVersion: apps/v1 kind: ReplicaSet metadata: name: my-replicaset labels: my-label: my-value spec: replicas: 3 selector: matchLabels: my-label: my-value template: metadata: labels: my-label: my-value spec: containers: - name: app-container image: my-image:latest Kubernetes Documentation When to use a ReplicaSet A ReplicaSet ensures that a specified number of pod replicas are running at any given time. However, Deployment is a higher-level concept that manages ReplicaSets and provides declarative updates to Pods along with a lot of other useful features. Therefore, we recommend using Deployments instead of directly using ReplicaSets, unless you require custom update orchestration or don't require updates at all. This actually means that you may never need to manipulate ReplicaSet objects: use a Deployment instead, and define your application in the spec section.
Deployment resource makes it easier for updating your pods to a newer version. Lets say you use ReplicaSet-A for controlling your pods, then You wish to update your pods to a newer version, now you should create Replicaset-B, scale down ReplicaSet-A and scale up ReplicaSet-B by one step repeatedly (This process is known as rolling update). Although this does the job, but it's not a good practice and it's better to let K8S do the job. A Deployment resource does this automatically without any human interaction and increases the abstraction by one level. Note: Deployment doesn't interact with pods directly, it just does rolling update using ReplicaSets.
Kubernetes
69,448,131
88
kubectl get pod run-sh-1816639685-xejyk NAME READY STATUS RESTARTS AGE run-sh-1816639685-xejyk 2/2 Running 0 26m What's the meaning of "READY=2/2"? The same with "1/1"?
The "Ready" column shows how many containers in a pod are considered ready. You can have some containers starting faster then others or having their readiness checks not yet fulfilled (or still in initial delay). In such cases there will be fewer containers ready in the pod than the total number (e.g. 1/2) hence the whole pod will not be considered ready.
Kubernetes
39,764,365
88
I want to create a secret for my kubernetes cluster. So I composed following dummy-secret.yaml file: apiVersion: v1 kind: Secret metadata: name: dummy-secret type: Opaque data: API_KEY: bWVnYV9zZWNyZXRfa2V5 API_SECRET: cmVhbGx5X3NlY3JldF92YWx1ZTE= When I run kubectl create -f dummy-secret.yaml I receive back following message: Error from server (BadRequest): error when creating "dummy-secret.yaml": Secret in version "v1" cannot be handled as a Secret: v1.Secret: Data: decode base64: illegal base64 data at input byte 8, error found in #10 byte of ...|Q89_Hj1Aq","API_SECR|..., bigger context ...|sion":"v1","data":{"API_KEY":"af76fsdK_cQ89_Hj1Aq","API_SECRET":"bsdfmkwegwegwe"},"kind":"Secret","m|... Not sure why it happens. As I understood, I need to encode all values under the data key in the yaml file. So I did base64 encoding, but kubernetes still doesn't handle the yaml secret file as I expect. UPDATE: I used this command to encode data values on my mac: echo -n 'mega_secret_key' | openssl base64
I got the decoded values "mega_secret_key" and "really_secret_value1" from from your encoded data. Seems they are not encoded in right way. So, encode your data in right way: $ echo "mega_secret_key" | base64 bWVnYV9zZWNyZXRfa2V5Cg== $ echo "really_secret_value1" | base64 cmVhbGx5X3NlY3JldF92YWx1ZTEK Then check whether they are encoded properly: $ echo "bWVnYV9zZWNyZXRfa2V5Cg==" | base64 -d mega_secret_key $ echo "cmVhbGx5X3NlY3JldF92YWx1ZTEK" | base64 -d really_secret_value1 So they are ok. Now use them in your dummy-secret.yaml: apiVersion: v1 kind: Secret metadata: name: dummy-secret type: Opaque data: API_KEY: bWVnYV9zZWNyZXRfa2V5Cg== API_SECRET: cmVhbGx5X3NlY3JldF92YWx1ZTEK And run $ kubectl create -f dummy-secret.yaml. UPDATE on 11-02-2022: The newer versions of Kubernetes support the optional stringData property where one can provide the value against any key without decoding. All key-value pairs in the stringData field are internally merged into the data field. If a key appears in both the data and the stringData field, the value specified in the stringData field takes precedence. apiVersion: v1 kind: Secret metadata: name: dummy-secret type: Opaque stringData: API_KEY: mega_secret_key API_SECRET: really_secret_value1 UPDATE: If you use -n flag while running $ echo "some_text", it will trim the trailing \n (newline) from the string you are printing. $ echo "some_text" some_text $ echo -n "some_text" some_text⏎ Just try it, # first encode $ echo -n "mega_secret_key" | base64 bWVnYV9zZWNyZXRfa2V5 $ echo -n "really_secret_value1" | base64 cmVhbGx5X3NlY3JldF92YWx1ZTE= # then decode and check whether newline is stripped $ echo "bWVnYV9zZWNyZXRfa2V5" | base64 -d mega_secret_key⏎ $ echo "cmVhbGx5X3NlY3JldF92YWx1ZTE=" | base64 -d really_secret_value1⏎ You can use these newly (without newline) decoded data in your secret instead. That also should fine. $ cat - <<-EOF | kubectl apply -f - apiVersion: v1 kind: Secret metadata: name: dummy-secret type: Opaque data: API_KEY: bWVnYV9zZWNyZXRfa2V5 API_SECRET: cmVhbGx5X3NlY3JldF92YWx1ZTE= EOF secret/dummy-secret created At the time of update, my kubernetes version is, Minor:"17", GitVersion:"v1.17.3", GitCommit:"06ad960bfd03b39c8310aaf92d1e7c1 2ce618213", GitTreeState:"clean", BuildDate:"2020-02-11T18:14:22Z", GoVersion:"go1.13.6", Compiler:"gc", Platform:"l inux/amd64"} Server Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.3", GitCommit:"06ad960bfd03b39c8310aaf92d1e7c1 2ce618213", GitTreeState:"clean", BuildDate:"2020-02-11T18:07:13Z", GoVersion:"go1.13.6", Compiler:"gc", Platform:"l inux/amd64"} ```
Kubernetes
53,394,973
86
If I forwarded a port using kubectl port-forward mypod 9000:9000 How can I undo that so that I can bind port 9000 with another program? Additionally, how can I test to see what ports are forwarded?
The port is only forwarded while the kubectl process is running, so you can just kill the kubectl process that's forwarding the port. In most cases that'll just mean pressing CTRL+C in the terminal where the port-forward command is running.
Kubernetes
37,288,500
86
I'm having trouble deleting custom resource definition. I'm trying to upgrade kubeless from v1.0.0-alpha.7 to v1.0.0-alpha.8. I tried to remove all the created custom resources by doing $ kubectl delete -f kubeless-v1.0.0-alpha.7.yaml deployment "kubeless-controller-manager" deleted serviceaccount "controller-acct" deleted clusterrole "kubeless-controller-deployer" deleted clusterrolebinding "kubeless-controller-deployer" deleted customresourcedefinition "functions.kubeless.io" deleted customresourcedefinition "httptriggers.kubeless.io" deleted customresourcedefinition "cronjobtriggers.kubeless.io" deleted configmap "kubeless-config" deleted But when I try, $ kubectl get customresourcedefinition NAME AGE functions.kubeless.io 21d And because of this when I next try to upgrade by doing, I see, $ kubectl create -f kubeless-v1.0.0-alpha.8.yaml Error from server (AlreadyExists): error when creating "kubeless-v1.0.0-alpha.8.yaml": object is being deleted: customresourcedefinitions.apiextensions.k8s.io "functions.kubeless.io" already exists I think because of this mismatch in the function definition , the hello world example is failing. $ kubeless function deploy hellopy --runtime python2.7 --from-file test.py --handler test.hello INFO[0000] Deploying function... FATA[0000] Failed to deploy hellopy. Received: the server does not allow this method on the requested resource (post functions.kubeless.io) Finally, here is the output of, $ kubectl describe customresourcedefinitions.apiextensions.k8s.io Name: functions.kubeless.io Namespace: Labels: <none> Annotations: kubectl.kubernetes.io/last-applied-configuration={"apiVersion":"apiextensions.k8s.io/v1beta1","description":"Kubernetes Native Serverless Framework","kind":"CustomResourceDefinition","metadata":{"anno... API Version: apiextensions.k8s.io/v1beta1 Kind: CustomResourceDefinition Metadata: Creation Timestamp: 2018-08-02T17:22:07Z Deletion Grace Period Seconds: 0 Deletion Timestamp: 2018-08-24T17:15:39Z Finalizers: customresourcecleanup.apiextensions.k8s.io Generation: 1 Resource Version: 99792247 Self Link: /apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions/functions.kubeless.io UID: 951713a6-9678-11e8-bd68-0a34b6111990 Spec: Group: kubeless.io Names: Kind: Function List Kind: FunctionList Plural: functions Singular: function Scope: Namespaced Version: v1beta1 Status: Accepted Names: Kind: Function List Kind: FunctionList Plural: functions Singular: function Conditions: Last Transition Time: 2018-08-02T17:22:07Z Message: no conflicts found Reason: NoConflicts Status: True Type: NamesAccepted Last Transition Time: 2018-08-02T17:22:07Z Message: the initial names have been accepted Reason: InitialNamesAccepted Status: True Type: Established Last Transition Time: 2018-08-23T13:29:45Z Message: CustomResource deletion is in progress Reason: InstanceDeletionInProgress Status: True Type: Terminating Events: <none>
So it turns out , the root cause was that Custom resources with finalizers can "deadlock". The CustomResource "functions.kubeless.io" had a Finalizers: customresourcecleanup.apiextensions.k8s.io and this is can leave it in a bad state when deleting. https://github.com/kubernetes/kubernetes/issues/60538 I followed the steps mentioned in this workaround and it now gets deleted.
Kubernetes
52,009,124
85
I'm trying to install a helm package on a kubernetes cluster which allegedly has RBAC disabled. I'm getting a permission error mentioning clusterroles.rbac.authorization.k8s.io, which is what I'd expect if RBAC was enabled. Is there a way to check with kubectl whether RBAC really is disabled? What I've tried: kubectl describe nodes --all-namespaces | grep -i rbac : nothing comes up kubectl describe rbac --all-namespaces | grep -i rbac : nothing comes up kubectl config get-contexts | grep -i rbac : nothing comes up k get clusterroles it says "No resources found", not an error message. So does that mean that RBAC is enabled? kuebctl describe cluster isn't a thing I'm aware that maybe this is the x-y problem because it's possible the helm package I'm installing is expecting RBAC to be enabled. But still, I'd like to know how to check whether or not it is enabled/disabled.
You can check this by executing the command kubectl api-versions; if RBAC is enabled you should see the API version .rbac.authorization.k8s.io/v1. In AKS, the best way is to check the cluster's resource details at resources.azure.com. If you can spot "enableRBAC": true, your cluster has RBAC enabled. Please note that existing non-RBAC enabled AKS clusters cannot currently be updated for RBAC use. (thanks @DennisAmeling for the clarification)
Kubernetes
51,238,988
85
I wanted to know what is the difference between a Replication Controller and a Deployment within Kubernetes (1.2). Going through the getting started document (http://kubernetes.io/docs/hellonode/) I have created a deployment - but it doesn't show up on the web UI. When I build applications using the web UI, they are set up as replication controllers. Functionally though, they seem very similar (they both manage pods and have services). So - what is the difference and when should I use each?
Deployments are a newer and higher level concept than Replication Controllers. They manage the deployment of Replica Sets (also a newer concept, but pretty much equivalent to Replication Controllers), and allow for easy updating of a Replica Set as well as the ability to roll back to a previous deployment. Previously this would have to be done with kubectl rolling-update which was not declarative and did not provide the rollback features. Kubernetes Dashboard has not yet been updated to support Deployments, and currently only supports Replication Controllers (see Deployments not visible in Kubernetes Dashboard). EDIT: The dashboard now supports Deployments.
Kubernetes
37,423,117
85
I set up a k8s cluster using kubeadm (v1.18) on an Ubuntu virtual machine. Now I need to add an Ingress Controller. I decided for nginx (but I'm open for other solutions). I installed it according to the docs, section "bare-metal": kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-0.31.1/deploy/static/provider/baremetal/deploy.yaml The installation seems fine to me: kubectl get all -n ingress-nginx NAME READY STATUS RESTARTS AGE pod/ingress-nginx-admission-create-b8smg 0/1 Completed 0 8m21s pod/ingress-nginx-admission-patch-6nbjb 0/1 Completed 1 8m21s pod/ingress-nginx-controller-78f6c57f64-m89n8 1/1 Running 0 8m31s NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/ingress-nginx-controller NodePort 10.107.152.204 <none> 80:32367/TCP,443:31480/TCP 8m31s service/ingress-nginx-controller-admission ClusterIP 10.110.191.169 <none> 443/TCP 8m31s NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/ingress-nginx-controller 1/1 1 1 8m31s NAME DESIRED CURRENT READY AGE replicaset.apps/ingress-nginx-controller-78f6c57f64 1 1 1 8m31s NAME COMPLETIONS DURATION AGE job.batch/ingress-nginx-admission-create 1/1 2s 8m31s job.batch/ingress-nginx-admission-patch 1/1 3s 8m31s However, when trying to apply a custom Ingress, I get the following error: Error from server (InternalError): error when creating "yaml/xxx/xxx-ingress.yaml": Internal error occurred: failed calling webhook "validate.nginx.ingress.kubernetes.io": Post https://ingress-nginx-controller-admission.ingress-nginx.svc:443/extensions/v1beta1/ingresses?timeout=30s: Temporary Redirect Any idea what could be wrong? I suspected DNS, but other NodePort services are working as expected and DNS works within the cluster. The only thing I can see is that I don't have a default-http-backend which is mentioned in the docs here. However, this seems normal in my case, according to this thread. Last but not least, I tried as well the installation with manifests (after removing ingress-nginx namespace from previous installation) and the installation via Helm chart. It has the same result. I'm pretty much a beginner on k8s and this is my playground-cluster. So I'm open to alternative solutions as well, as long as I don't need to set up the whole cluster from scratch. Update: With "applying custom Ingress", I mean: kubectl apply -f <myIngress.yaml> Content of myIngress.yaml apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: my-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - http: paths: - path: /someroute/fittingmyneeds pathType: Prefix backend: serviceName: some-service servicePort: 5000
Another option you have is to remove the Validating Webhook entirely: kubectl delete -A ValidatingWebhookConfiguration ingress-nginx-admission I found I had to do that on another issue, but the workaround/solution works here as well. This isn't the best answer; the best answer is to figure out why this doesn't work. But at some point, you live with workarounds. I'm installing on Docker for Mac, so I used the cloud rather than baremetal version: kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v0.34.1/deploy/static/provider/cloud/deploy.yaml
Kubernetes
61,616,203
83
I have the following setup: A docker image omg/telperion on docker hub A kubernetes cluster (with 4 nodes, each with ~50GB RAM) and plenty resources I followed tutorials to pull images from dockerhub to kubernetes SERVICE_NAME=telperion DOCKER_SERVER="https://index.docker.io/v1/" DOCKER_USERNAME=username DOCKER_PASSWORD=password DOCKER_EMAIL="[email protected]" # Create secret kubectl create secret docker-registry dockerhub --docker-server=$DOCKER_SERVER --docker-username=$DOCKER_USERNAME --docker-password=$DOCKER_PASSWORD --docker-email=$DOCKER_EMAIL # Create service yaml echo "apiVersion: v1 \n\ kind: Pod \n\ metadata: \n\ name: ${SERVICE_NAME} \n\ spec: \n\ containers: \n\ - name: ${SERVICE_NAME} \n\ image: omg/${SERVICE_NAME} \n\ imagePullPolicy: Always \n\ command: [ \"echo\",\"done deploying $SERVICE_NAME\" ] \n\ imagePullSecrets: \n\ - name: dockerhub" > $SERVICE_NAME.yaml # Deploy to kubernetes kubectl create -f $SERVICE_NAME.yaml Which results in the pod going into a CrashLoopBackoff docker run -it -p8080:9546 omg/telperion works fine. So my question is Is this debug-able?, if so, how do i debug this? Some logs: kubectl get nodes NAME STATUS AGE VERSION k8s-agent-adb12ed9-0 Ready 22h v1.6.6 k8s-agent-adb12ed9-1 Ready 22h v1.6.6 k8s-agent-adb12ed9-2 Ready 22h v1.6.6 k8s-master-adb12ed9-0 Ready,SchedulingDisabled 22h v1.6.6 . kubectl get pods NAME READY STATUS RESTARTS AGE telperion 0/1 CrashLoopBackOff 10 28m . kubectl describe pod telperion Name: telperion Namespace: default Node: k8s-agent-adb12ed9-2/10.240.0.4 Start Time: Wed, 21 Jun 2017 10:18:23 +0000 Labels: <none> Annotations: <none> Status: Running IP: 10.244.1.4 Controllers: <none> Containers: telperion: Container ID: docker://c2dd021b3d619d1d4e2afafd7a71070e1e43132563fdc370e75008c0b876d567 Image: omg/telperion Image ID: docker-pullable://omg/telperion@sha256:c7e3beb0457b33cd2043c62ea7b11ae44a5629a5279a88c086ff4853828a6d96 Port: Command: echo done deploying telperion State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Completed Exit Code: 0 Started: Wed, 21 Jun 2017 10:19:25 +0000 Finished: Wed, 21 Jun 2017 10:19:25 +0000 Ready: False Restart Count: 3 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-n7ll0 (ro) Conditions: Type Status Initialized True Ready False PodScheduled True Volumes: default-token-n7ll0: Type: Secret (a volume populated by a Secret) SecretName: default-token-n7ll0 Optional: false QoS Class: BestEffort Node-Selectors: <none> Tolerations: <none> Events: FirstSeen LastSeen Count From SubObjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 1m 1m 1 default-scheduler Normal Scheduled Successfully assigned telperion to k8s-agent-adb12ed9-2 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Created Created container with id d9aa21fd16b682698235e49adf80366f90d02628e7ed5d40a6e046aaaf7bf774 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Started Started container with id d9aa21fd16b682698235e49adf80366f90d02628e7ed5d40a6e046aaaf7bf774 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Started Started container with id c6c8f61016b06d0488e16bbac0c9285fed744b933112fd5d116e3e41c86db919 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Created Created container with id c6c8f61016b06d0488e16bbac0c9285fed744b933112fd5d116e3e41c86db919 1m 1m 2 kubelet, k8s-agent-adb12ed9-2 Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "telperion" with CrashLoopBackOff: "Back-off 10s restarting failed container=telperion pod=telperion_default(f4e36a12-566a-11e7-99a6-000d3aa32f49)" 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Started Started container with id 3b911f1273518b380bfcbc71c9b7b770826c0ce884ac876fdb208e7c952a4631 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Created Created container with id 3b911f1273518b380bfcbc71c9b7b770826c0ce884ac876fdb208e7c952a4631 1m 1m 2 kubelet, k8s-agent-adb12ed9-2 Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "telperion" with CrashLoopBackOff: "Back-off 20s restarting failed container=telperion pod=telperion_default(f4e36a12-566a-11e7-99a6-000d3aa32f49)" 1m 50s 4 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Pulling pulling image "omg/telperion" 47s 47s 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Started Started container with id c2dd021b3d619d1d4e2afafd7a71070e1e43132563fdc370e75008c0b876d567 1m 47s 4 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Pulled Successfully pulled image "omg/telperion" 47s 47s 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Created Created container with id c2dd021b3d619d1d4e2afafd7a71070e1e43132563fdc370e75008c0b876d567 1m 9s 8 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Warning BackOff Back-off restarting failed container 46s 9s 4 kubelet, k8s-agent-adb12ed9-2 Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "telperion" with CrashLoopBackOff: "Back-off 40s restarting failed container=telperion pod=telperion_default(f4e36a12-566a-11e7-99a6-000d3aa32f49)" Edit 1: Errors reported by kubelet on master: journalctl -u kubelet . Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: E0621 10:28:49.798140 1809 fsHandler.go:121] failed to collect filesystem stats - rootDiskErr: du command failed on /var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce with output Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: , stderr: du: cannot access '/var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce/merged/proc/13122/task/13122/fd/4': No such file or directory Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: du: cannot access '/var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce/merged/proc/13122/task/13122/fdinfo/4': No such file or directory Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: du: cannot access '/var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce/merged/proc/13122/fd/3': No such file or directory Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: du: cannot access '/var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce/merged/proc/13122/fdinfo/3': No such file or directory Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: - exit status 1, rootInodeErr: <nil>, extraDiskErr: <nil> Edit 2: more logs kubectl logs $SERVICE_NAME -p done deploying telperion
You can access the logs of your pods with kubectl logs [podname] -p the -p option will read the logs of the previous (crashed) instance If the crash comes from the application, you should have useful logs in there.
Kubernetes
44,673,957
83
I would like to run specific command after initialization of deployment is successful. This is my yaml file: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: auth spec: replicas: 1 template: metadata: labels: app: auth spec: containers: - name: auth image: {{my-service-image}} env: - name: NODE_ENV value: "docker-dev" resources: requests: cpu: 100m memory: 100Mi ports: - containerPort: 3000 However, I would like to run command for db migration after (not before) deployment is successfully initialized and pods are running. I can do it manually for every pod (with kubectl exec), but this is not very scalable.
I resolved it using lifecycles: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: auth spec: replicas: 1 template: metadata: labels: app: auth spec: containers: - name: auth image: {{my-service-image}} env: - name: NODE_ENV value: "docker-dev" resources: requests: cpu: 100m memory: 100Mi ports: - containerPort: 3000 lifecycle: postStart: exec: command: ["/bin/sh", "-c", {{cmd}}]
Kubernetes
44,140,593
82
I am doing a lab about kubernetes in google cloud. I have create the YAML file, but when I am trying to deploy it a shell shows me this error: error converting YAML to JSON: yaml: line 34: did not find expected key YAML file: apiVersion: apps/v1 kind: Deployment metadata: name: nginx labels: app: nginx spec: replicas: 2 selector: matchLabels: app: nginx spec: volumes: - name: nginx-config configMap: name: nginx-config - name: php-config configMap: name: php-config containers: - image: php-fpm:7.2 name: php ports: - containerPort: 9000 volumeMounts: - name: persistent-storage mountPath: /var/www/data - name: php-config mountPath: /usr/local/etc/php-fpm.d/www.conf subPath: www.conf - image: nginx:latest name: nginx - containerPort: 80 volumeMounts: - name: persistent-storage mountPath: /var/www/data - name: nginx-config mountPath: /etc/nginx/nginx.conf subPath: nginx.conf volumes: - name: persistent-storage persistentVolumeClaim: claimName: nfs-pvc
yamllint package is useful to debug and find this kind of errors, just do yamllint filename and it will list the possible problems it finds. Install via your distro package manager (usually recommended if available) or via the below npm install command (it will install globally) npm install -g yaml-lint Thanks to Kyle VG for the npm command
Kubernetes
54,479,397
81
Is it possible to restart pods automatically based on the time? For example, I would like to restart the pods of my cluster every morning at 8.00 AM.
Use a cronjob, but not to run your pods, but to schedule a Kubernetes API command that will restart the deployment everyday (kubectl rollout restart). That way if something goes wrong, the old pods will not be down or removed. Rollouts create new ReplicaSets, and wait for them to be up, before killing off old pods, and rerouting the traffic. Service will continue uninterrupted. You have to setup RBAC, so that the Kubernetes client running from inside the cluster has permissions to do needed calls to the Kubernetes API. --- # Service account the client will use to reset the deployment, # by default the pods running inside the cluster can do no such things. kind: ServiceAccount apiVersion: v1 metadata: name: deployment-restart namespace: <YOUR NAMESPACE> --- # allow getting status and patching only the one deployment you want # to restart apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: deployment-restart namespace: <YOUR NAMESPACE> rules: - apiGroups: ["apps", "extensions"] resources: ["deployments"] resourceNames: ["<YOUR DEPLOYMENT NAME>"] verbs: ["get", "patch", "list", "watch"] # "list" and "watch" are only needed # if you want to use `rollout status` --- # bind the role to the service account apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: deployment-restart namespace: <YOUR NAMESPACE> roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: deployment-restart subjects: - kind: ServiceAccount name: deployment-restart namespace: <YOUR NAMESPACE> And the cronjob specification itself: apiVersion: batch/v1 kind: CronJob metadata: name: deployment-restart namespace: <YOUR NAMESPACE> spec: concurrencyPolicy: Forbid schedule: '0 8 * * *' # cron spec of time, here, 8 o'clock jobTemplate: spec: backoffLimit: 2 # this has very low chance of failing, as all this does # is prompt kubernetes to schedule new replica set for # the deployment activeDeadlineSeconds: 600 # timeout, makes most sense with # "waiting for rollout" variant specified below template: spec: serviceAccountName: deployment-restart # name of the service # account configured above restartPolicy: Never containers: - name: kubectl image: bitnami/kubectl # probably any kubectl image will do, # optionaly specify version, but this # should not be necessary, as long the # version of kubectl is new enough to # have `rollout restart` command: - 'kubectl' - 'rollout' - 'restart' - 'deployment/<YOUR DEPLOYMENT NAME>' Optionally, if you want the cronjob to wait for the deployment to roll out, change the cronjob command to: command: - bash - -c - >- kubectl rollout restart deployment/<YOUR DEPLOYMENT NAME> && kubectl rollout status deployment/<YOUR DEPLOYMENT NAME>
Kubernetes
52,422,300
81
I have created basic helm template using helm create command. While checking the template for Ingress its adding the string RELEASE-NAME and appname like this RELEASE-NAME-microapp How can I change .Release.Name value? helm template --kube-version 1.11.1 microapp/ # Source: microapp/templates/ingress.yaml apiVersion: extensions/v1beta1 kind: Ingress metadata: name: RELEASE-NAME-microapp labels: app: microapp chart: microapp-0.1.0 release: RELEASE-NAME heritage: Tiller annotations: kubernetes.io/ingress.class: nginx
This depends on what version of Helm you have; helm version can tell you this. In Helm version 2, it's the value of the helm install --name parameter, or absent this, a name Helm chooses itself. If you're checking what might be generated via helm template that also takes a --name parameter. In Helm version 3, it's the first parameter to the helm install command. Helm won't generate a name automatically unless you explicitly ask it to helm install --generate-name. helm template also takes the same options. Also, in helm 3, if you want to specify a name explicitly, you should use the --name-template flag. e.g. helm template --name-template=dummy in order to use the name dummy instead of RELEASE-NAME
Kubernetes
51,718,202
81
How can I use kubectl or the API to retrieve the current image for containers in a pod or deployment? For example, in a deployment created with the below configuration, I want to retrieve the value eu.gcr.io/test0/brain:latest. apiVersion: v1 kind: Deployment metadata: name: flags spec: replicas: 6 template: metadata: labels: app: flags spec: containers: - name: flags image: eu.gcr.io/test0/brain:latest
From kubectl 1.6 the -o wide option does this, so kubectl get deployments -o wide will show the current image in the output.
Kubernetes
39,089,230
81
After creating the pod-definition.yml file. apiVersion: v1 kind: Pod metadata: name: myapp-pod labels: app: myapp type: server spec: containers: - name: nginx-container image: nginx The linter is giving this warning. One or more containers do not have resource limits - this could starve other processes
It is a good practice to declare resource requests and limits for both memory and cpu for each container. This helps to schedule the container to a node that has available resources for your Pod, and also so that your Pod does not use resources that other Pods needs - therefore the "this could starve other processes" message. E.g. to add resource requests and limits to your example apiVersion: v1 kind: Pod metadata: name: myapp-pod labels: app: myapp type: server spec: containers: - name: nginx-container image: nginx resources: limits: memory: 512Mi cpu: "1" requests: memory: 256Mi cpu: "0.2"
Kubernetes
64,080,471
80
I have installed Docker Desktop (version : 2.3.0.4) and enabled Kubernetes. I deployed couple of PODS and everything was working fine, Since yesterday I am facing a weird issue mentioned below: Unable to connect to the server: dial tcp 127.0.0.1:6443: connectex: No connection could be made because the target machine actively refused it. As such, no changes were made on my system. I am using Linux Containers on Windows 10 machine. Following steps I have tried: Restarted the Docker Desktop Tried the same with minikube and Docker Desktop both Tried to disable the firewall but due to some permissions, I am not able to turn it off. I have reset the kubernetes cluster as well.
I tried numerous changes to fix docker desktop Kubernetes failing to start. What finally worked: Clicked the troubleshooting icon (it's a bug icon at the top right corner) and then chose Clean/Purge Data.*
Kubernetes
63,312,861
80
I have been using the Kubernetes and Helm for a while and have now come across Kustomize for the first time. But what exactly is the difference between Kustomize and Helm? Are both simply different solutions for bundling K8s elements such as services, deployments, ...? Or does it make sense to use both Helm and Kustomize together?
The best way to describe the differences is to refer to them as different types of deployment engines. Helm is a Templating Engine and Kustomize is an Overlay Engine. So what are these? Well when you use a templating engine you create a boilerplate example of your file. From there you abstract away contents with known filters and within these abstractions you provide references to variables. These variables are normally abstracted to another file where you insert information specific to your environment Then, on runtime, when you execute the templating engine, the templates are loaded into memory and all of the variables are exchanged with their placeholders. This is different from an overlay engine in a few nuanced ways. Normally about how information gets into configuration examples. Noticed how I used the word examples there instead of templates. This was intentional as Kustomize doesn't use templates. Instead, you create a Kustomization.yml file. This file then points to two different things. Your Base and your Overlays. At runtime your Base is loaded into memory and if any Overlays exist that match they are merged over top of your Base configuration. The latter method allows you to scale your configurations to large numbers of variants more easily. Imagine maintaining 10,000 different sets of variables files for 10,000 different configurations. Now imagine maintaining a hierarchy of modular and small configurations that can be inherited in any combination or permutation? It would greatly reduce redundancy and greatly improve manageability. Another nuance to make note of is ownership of the projects. Helm is operated by a third party. Kustomize is developed directly by the Kubernetes team. Though both are CNCF projects. In fact, Kustomize functionality is directly supported in Kubectl. You can build and perform a Kustomize project like so: kubectl apply -k DIR. However, the version of kustomize embedded in the kubectl binary is out of date and missing some new features. There are a few other improvements in Kustomize too that are somewhat more minor but still worth mentioning. It can reference bases from the internet or other non-standard paths. It supports generators to build configuration files for you automatically based on files and string literals. It supports robust & granular JSON patching. It supports injecting metadata across configuration files. The following links were added in the comments below for more comparisons: https://medium.com/@alexander.hungenberg/helm-vs-kustomize-how-to-deploy-your-applications-in-2020-67f4d104da69 https://codeengineered.com/blog/2018/helm-kustomize-complexity/
Kubernetes
60,519,939
80
After I have run helm list I got following error: Error: incompatible versions client[v2.9.0] server[v2.8.2] I did a helm init to install the compatible tiller version "Warning: Tiller is already installed in the cluster. (Use --client-only to suppress this message, or --upgrade to upgrade Tiller to the current version.)". Any pointers?
Like the OP, I had this error: $ helm list Error: incompatible versions client[v2.10.0] server[v2.9.1] Updating the server wasn't an option for me so I needed to brew install a previous version of the client. I hadn't previously installed client[v2.9.1] (or any previous client version) and thus couldn't just brew switch kubernetes-helm 2.9.1. I ended up having to follow the steps in this SO answer: https://stackoverflow.com/a/17757092/2356383 Which basically says Look on Github for the correct kubernetes-helm.rb file for the version you want (2.9.1 in my case): https://github.com/Homebrew/homebrew-core/search?q=kubernetes-helm&type=Commits Click the commit hash (78d6425 in my case) Click the "View" button to see the whole file Click the "Raw" button And copy the url: https://raw.githubusercontent.com/Homebrew/homebrew-core/78d64252f30a12b6f4b3ce29686ab5e262eea812/Formula/kubernetes-helm.rb Now that I had the url for the correct kubernetes-helm.rb file, I ran the following: $ brew unlink kubernetes-helm $ brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/78d64252f30a12b6f4b3ce29686ab5e262eea812/Formula/kubernetes-helm.rb $ brew switch kubernetes-helm 2.9.1 Hope this helps someone.
Kubernetes
50,701,224
80
I'd like to update a value config for a helm release on my cluster. Something like helm update -f new_values.yml nginx-controller
helm upgrade -f ingress-controller/values.yml nginx-ingress stable/nginx-ingress Or more generally: helm upgrade -f new-values.yml {release name} {package name or path} --version {fixed-version} The command above does the job. Unless you manually specify the version with the --version {fixed-version} argument, upgrade will also update the chart version. You can find the current chart version with helm ls. Docs: https://helm.sh/docs/helm/helm_upgrade/
Kubernetes
48,927,233
80
Is there a way to get some details about Kubernetes pod that was deleted (stopped, replaced by new version). I am investigating bug. I have logs with my pod name. That pod does not exist anymore, it was replaced by another one (with different configuration). New pod resides in same namespace, replication controller and service as old one. Commands like kubectl get pods kubectl get pod <pod-name> work only with current pods (live or stopped). How I could get more details about old pods? I would like to see when they were created which environment variables they had when created why and when they were stopped
As of today, kubectl get pods -a is deprecated, and as a result you cannot get deleted pods. What you can do though, is to get a list of recently deleted pod names - up to 1 hour in the past unless you changed the ttl for kubernetes events - by running: kubectl get event -o custom-columns=NAME:.metadata.name | cut -d "." -f1 You can then investigate further issues within your logging pipeline if you have one in place.
Kubernetes
40,636,021
80
I want send multiple entrypoint commands to a Docker container in the command tag of kubernetes config file. apiVersion: v1 kind: Pod metadata: name: hello-world spec: # specification of the pod’s contents restartPolicy: Never containers: - name: hello image: "ubuntu:14.04" command: ["command1 arg1 arg2 && command2 arg3 && command3 arg 4"] But it seems like it does not work. What is the correct format of sending multiple commands in the command tag?
There can only be a single entrypoint in a container... if you want to run multiple commands like that, make bash be the entry point, and make all the other commands be an argument for bash to run: command: ["/bin/bash","-c","touch /foo && echo 'here' && ls /"]
Kubernetes
33,979,501
80
I am writing an ansible playbook right now that deploys a dockerized application in kubernetes. However, for molecularity purposes I would rather not hard code the files that need to be apply after doing kompose convert -f docker-compose.yaml --volumes hostPath Is there a way to apply all the files in a directory?
You can apply all files in a folder with kubectl apply -f <folder> You may also be interested in parameterization of your manifest files using Kustomize e.g. use more replicas in a prod-namespace than in a test-namespace. You can apply parameterized manifest files with kubectl apply -k <folder>
Kubernetes
59,491,324
79
I have a Kubernetes deployment that looks something like this (replaced names and other things with '....'): # Please edit the object below. Lines beginning with a '#' will be ignored, # and an empty file will abort the edit. If an error occurs while saving this file will be # reopened with the relevant failures. # apiVersion: extensions/v1beta1 kind: Deployment metadata: annotations: deployment.kubernetes.io/revision: "3" kubernetes.io/change-cause: kubectl replace deployment .... -f - --record creationTimestamp: 2016-08-20T03:46:28Z generation: 8 labels: app: .... name: .... namespace: default resourceVersion: "369219" selfLink: /apis/extensions/v1beta1/namespaces/default/deployments/.... uid: aceb2a9e-6688-11e6-b5fc-42010af000c1 spec: replicas: 2 selector: matchLabels: app: .... strategy: rollingUpdate: maxSurge: 1 maxUnavailable: 1 type: RollingUpdate template: metadata: creationTimestamp: null labels: app: .... spec: containers: - image: gcr.io/..../....:0.2.1 imagePullPolicy: IfNotPresent name: .... ports: - containerPort: 8080 protocol: TCP resources: requests: cpu: "0" terminationMessagePath: /dev/termination-log dnsPolicy: ClusterFirst restartPolicy: Always securityContext: {} terminationGracePeriodSeconds: 30 status: availableReplicas: 2 observedGeneration: 8 replicas: 2 updatedReplicas: 2 The problem I'm observing is that Kubernetes places both replicas (in the deployment I've asked for two) on the same node. If that node goes down, I lose both containers and the service goes offline. What I want Kubernetes to do is to ensure that it doesn't double up containers on the same node where the containers are the same type - this only consumes resources and doesn't provide any redundancy. I've looked through the documentation on deployments, replica sets, nodes etc. but I couldn't find any options that would let me tell Kubernetes to do this. Is there a way to tell Kubernetes how much redundancy across nodes I want for a container? EDIT: I'm not sure labels will work; labels constrain where a node will run so that it has access to local resources (SSDs) etc. All I want to do is ensure no downtime if a node goes offline.
There is now a proper way of doing this. You can use the label in "kubernetes.io/hostname" if you just want to spread it out across all nodes. Meaning if you have two replicas of a pod, and two nodes, each should get one if their names aren't the same. Example: apiVersion: apps/v1 kind: Deployment metadata: name: my-service labels: app: my-service spec: replicas: 2 selector: matchLabels: app: my-service template: metadata: labels: app: my-service spec: topologySpreadConstraints: - maxSkew: 1 topologyKey: kubernetes.io/hostname whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: app: my-service containers: - name: pause image: k8s.gcr.io/pause:3.1
Kubernetes
39,092,090
79
I fail to see why kubernetes need a pod selector in a deployment statement that can only contain one pod template? Feel free to educate me why kubernetes engineers introduced a selector statement inside a deployment definition instead of automatically select the pod from the template? --- apiVersion: v1 kind: Service metadata: name: grpc-service spec: type: LoadBalancer ports: - name: grpc port: 8080 targetPort: 8080 protocol: TCP selector: app: grpc-test --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: grpc-deployment spec: replicas: 1 revisionHistoryLimit: 3 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 selector: matchLabels: app: grpc-test template: metadata: labels: app: grpc-test spec: containers: ... Why not simply define something like this? --- apiVersion: v1 kind: Service metadata: name: grpc-service spec: type: LoadBalancer ports: - name: grpc port: 8080 targetPort: 8080 protocol: TCP selector: app: grpc-test --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: grpc-deployment spec: replicas: 1 revisionHistoryLimit: 3 strategy: type: RollingUpdate rollingUpdate: maxUnavailable: 0 template: metadata: labels: app: grpc-test spec: containers: ...
Ah! Funny enough, I have once tried wrapping my head around the concept of label selectors as well before. So, here it goes... First of all, what the hell are these labels used for? Labels within Kubernetes are the core means of identifying objects. A controller controls pods based on their label instead of their name. In this particular case they are meant to identify the pods belonging to the deployment’s replica set. You actually didn’t have to implicitly define .spec.selector when using the v1beta1 extensions. It would in that case default from .spec.template.labels. However, if you don’t, you can run into problems with kubectl apply once one or more of the labels that are used for selecting change because kubeclt apply will look at kubectl.kubernetes.io/last-applied-configuration when comparing changes and that annotation will only contain the user input when he created the resource and none of the defaulted fields. You’ll get an error because it cannot calculate the diff like: spec.template.metadata.labels: Invalid value: {"app":"nginx"}: `selector` does not match template `labels` As you can see, this is a pretty big shortcoming since it means you can not change any of the labels that are being used as a selector label or it would completely break your deployment flow. It was “fixed” in apps/v1beta2 by requiring selectors to be explicitly defined, disallowing mutation on those fields. So in your example, you actually don’t have to define them! The creation will work and will use your .spec.template.labels by default. But yeah, in the near future when you have to use v1beta2, the field will be mandatory. I hope this kind of answers your question and I didn’t make it any more confusing ;)
Kubernetes
50,309,057
78
I am running minikube v0.24.1. In this minikube, I will create a Pod for my nginx application. And also I want to pass data from my local directory. That means I want to mount my local $HOME/go/src/github.com/nginx into my Pod How can I do this? apiVersion: v1 kind: Pod metadata: name: nginx spec: containers: - image: nginx:0.1 name: nginx volumeMounts: - mountPath: /data name: volume volumes: - name: volume hostPath: path: /data
You can't mount your local directory into your Pod directly. First, you need to mount your directory $HOME/go/src/github.com/nginx into your minikube. $ minikube start --mount-string="$HOME/go/src/github.com/nginx:/data" --mount Then If you mount /data into your Pod using hostPath, you will get you local directory data into Pod. There is another way Host's $HOME directory gets mounted into minikube's /hosthome directory. Here you will get your data $ ls -la /hosthome/go/src/github.com/nginx So to mount this directory, you can change your Pod's hostPath hostPath: path: /hosthome/go/src/github.com/nginx
Kubernetes
48,534,980
78
I have a Kubernetes cluster on Google Cloud Platform. It has a persistent Volume Claim with a Capacity of 1GB. The persistent volume claim is bound to many deployments. I would like to identify the space left in the persistent Volume Claim in order to know if 1GB is sufficient for my application. I have used the command "kubectl get pv" but this does not show the storage space left.
If there's a running pod with mounted PV from the PVC, kubectl -n <namespace> exec <pod-name> -- df -ah ...will list all file systems, including the mounted volumes, and their free disk space.
Kubernetes
53,200,828
77
When i run the kubectl version command , I get the following error message. kubectl version Client Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.0", GitCommit:"925c127ec6b946659ad0fd596fa959be43f0cc05", GitTreeState:"clean", BuildDate:"2017-12-15T21:07:38Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"} Unable to connect to the server: dial tcp 192.168.99.100:8443: i/o timeout How do I resolve this?
You can get relevant information about the client-server status by using the following command. kubectl config view Now you can update or set k8s context accordingly with the following command. kubectl config use-context CONTEXT-CHOSEN-FROM-PREVIOUS-COMMAND-OUTPUT you can do further action on kubeconfig file. the following command will provide you with all necessary information. kubectl config --help
Kubernetes
49,260,135
77
I've created a Kubernetes cluster on AWS with kops and can successfully administer it via kubectl from my local machine. I can view the current config with kubectl config view as well as directly access the stored state at ~/.kube/config, such as: apiVersion: v1 clusters: - cluster: certificate-authority-data: REDACTED server: https://api.{CLUSTER_NAME} name: {CLUSTER_NAME} contexts: - context: cluster: {CLUSTER_NAME} user: {CLUSTER_NAME} name: {CLUSTER_NAME} current-context: {CLUSTER_NAME} kind: Config preferences: {} users: - name: {CLUSTER_NAME} user: client-certificate-data: REDACTED client-key-data: REDACTED password: REDACTED username: admin - name: {CLUSTER_NAME}-basic-auth user: password: REDACTED username: admin I need to enable other users to also administer. This user guide describes how to define these on another users machine, but doesn't describe how to actually create the user's credentials within the cluster itself. How do you do this? Also, is it safe to just share the cluster.certificate-authority-data?
For a full overview on Authentication, refer to the official Kubernetes docs on Authentication and Authorization For users, ideally you use an Identity provider for Kubernetes (OpenID Connect). If you are on GKE / ACS you integrate with respective Identity and Access Management frameworks If you self-host kubernetes (which is the case when you use kops), you may use coreos/dex to integrate with LDAP / OAuth2 identity providers - a good reference is this detailed 2 part SSO for Kubernetes article. kops (1.10+) now has built-in authentication support which eases the integration with AWS IAM as identity provider if you're on AWS. for Dex there are a few open source cli clients as follows: Nordstrom/kubelogin pusher/k8s-auth-example If you are looking for a quick and easy (not most secure and easy to manage in the long run) way to get started, you may abuse serviceaccounts - with 2 options for specialised Policies to control access. (see below) NOTE since 1.6 Role Based Access Control is strongly recommended! this answer does not cover RBAC setup EDIT: Great, but outdated (2017-2018), guide by Bitnami on User setup with RBAC is also available. Steps to enable service account access are (depending on if your cluster configuration includes RBAC or ABAC policies, these accounts may have full Admin rights!): EDIT: Here is a bash script to automate Service Account creation - see below steps Create service account for user Alice kubectl create sa alice Get related secret secret=$(kubectl get sa alice -o json | jq -r .secrets[].name) Get ca.crt from secret (using OSX base64 with -D flag for decode) kubectl get secret $secret -o json | jq -r '.data["ca.crt"]' | base64 -D > ca.crt Get service account token from secret user_token=$(kubectl get secret $secret -o json | jq -r '.data["token"]' | base64 -D) Get information from your kubectl config (current-context, server..) # get current context c=$(kubectl config current-context) # get cluster name of context name=$(kubectl config get-contexts $c | awk '{print $3}' | tail -n 1) # get endpoint of current context endpoint=$(kubectl config view -o jsonpath="{.clusters[?(@.name == \"$name\")].cluster.server}") On a fresh machine, follow these steps (given the ca.cert and $endpoint information retrieved above: Install kubectl brew install kubectl Set cluster (run in directory where ca.crt is stored) kubectl config set-cluster cluster-staging \ --embed-certs=true \ --server=$endpoint \ --certificate-authority=./ca.crt Set user credentials kubectl config set-credentials alice-staging --token=$user_token Define the combination of alice user with the staging cluster kubectl config set-context alice-staging \ --cluster=cluster-staging \ --user=alice-staging \ --namespace=alice Switch current-context to alice-staging for the user kubectl config use-context alice-staging To control user access with policies (using ABAC), you need to create a policy file (for example): { "apiVersion": "abac.authorization.kubernetes.io/v1beta1", "kind": "Policy", "spec": { "user": "system:serviceaccount:default:alice", "namespace": "default", "resource": "*", "readonly": true } } Provision this policy.json on every master node and add --authorization-mode=ABAC --authorization-policy-file=/path/to/policy.json flags to API servers This would allow Alice (through her service account) read only rights to all resources in default namespace only.
Kubernetes
42,170,380
77
I am trying to use kubectl run command to pull an image from private registry and run a command from that. But I don't see an option to specify image pull secret. It looks like it is not possible to pass image secret as part for run command. Is there any alternate option to pull a container and run a command using kubectl? The command output should be seen on the console. Also once the command finishes the pod should die.
You can use the overrides if you specify it right, it's an array in the end, that took me a bit to figure out, the below works on Kubernetes of at least 1.6: --overrides='{ "spec": { "template": { "spec": { "imagePullSecrets": [{"name": "your-registry-secret"}] } } } }' for example kubectl run -i -t hello-world --rm --generator=run-pod/v1 \ --image=eu.gcr.io/your-registry/hello-world \ --image-pull-policy="IfNotPresent" \ --overrides='{ "spec": { "template": { "spec": { "imagePullSecrets": [{"name": "your-registry-secret"}] } } } }'
Kubernetes
40,288,077
77
While using kubectl port-forward function I was able to succeed in port forwarding a local port to a remote port. However it seems that after a few minutes idling the connection is dropped. Not sure why that is so. Here is the command used to portforward: kubectl --namespace somenamespace port-forward somepodname 50051:50051 Error message: Forwarding from 127.0.0.1:50051 -> 50051 Forwarding from [::1]:50051 -> 50051 E1125 17:18:55.723715 9940 portforward.go:178] lost connection to pod Was hoping to be able to keep the connection up
Setting kube's streaming-connection-idle-timeout to 0 should be a right solution, but if you don't want to change anything, you can use while-do construction Format: while true; do <<YOUR COMMAND HERE>>; done So just inputing in CLI: while true; do kubectl --namespace somenamespace port-forward somepodname 50051:50051; done should keep kubectl reconnecting on connection lost
Kubernetes
47,484,312
76
I have worked on Kubernetes and currently reading about Service Fabric, I know Service Fabric provides microservices framework models like stateful, stateless and actor but other than that it also provides GuestExecutables or Containers as well which is what Kubernetes also does manage/orchestrate containers. Can anyone explain a detailed difference between the two?
Caveat: as noted by joniba in the comments, the original answer (see below) presents Fabric and Kubernetes are somehow similar, with the differences being nuanced. That contasts with Ben Morris's take, which asked in Feb. 2019: "Now that Kubernetes is on Azure, what is Service Fabric for?": One of the sticking points of Service Fabric has always been the difficulty involved in managing a cluster with patchy documentation and a tendency towards unhelpful error messages. Deploying a cluster with Azure Service Fabric spares you some of the operational pain around node management, but it doesn't change the experience of building applications using the underlying SDKs. For the "nuances" differences, read on (original answer): Original answer: You can see in this project paolosalvatori/service-fabric-acs-kubernetes-multi-container-appthe same containers implemented both in Service Fabric, and in Kubernetes. Their "service" (for external ingress access) is different, with Kubernetes being a bit more complete and diverse: see Services. The reality is: there are "two slightly different offering" because of market pressure. The Microsoft Azure platform, initially released in 2010, has implemented its own Microsoft Azure Fabric Controller, in order to ensure the services and environment do not fail if one or more of the servers fails within the Microsoft data center, and which also provides the management of the user's Web application such as memory allocation and load balancing. But in order to attract other clients on their own Microsoft Data Center, they had to adapt to Kubernetes, released initially in 2014, which is now (2018) either adopted or closely considered by... pretty much everybody (as reported in late December) (That does not mean one is "better" than the other, only that the "other" is more "visible" than the first ;) ) So it is less about "a detailed difference between the two", and more about the ability to integrate Kubernetes-based system on Microsoft Data Centers. This is in line (source: detailed here) with Microsoft continued its unprecedented shift toward an open (read: non-proprietary) staging platform for Azure (with Deis). And Kubernetes orchestrator is available on Microsoft's Azure Container Service since February 2017. You can see other differences in their architecture of a deployed application: Service Fabric: Vs. Kubernetes: thieme mentions in the comments the article "Service Fabric and Kubernetes comparison, part 1 – Distributed Systems Architecture", from Marcin Kosieradzki.
Kubernetes
48,415,057
75
I created a PersistentVolume sourced from a Google Compute Engine persistent disk that I already formatted and provision with data. Kubernetes says the PersistentVolume is available. kind: PersistentVolume apiVersion: v1 metadata: name: models-1-0-0 labels: name: models-1-0-0 spec: capacity: storage: 200Gi accessModes: - ReadOnlyMany gcePersistentDisk: pdName: models-1-0-0 fsType: ext4 readOnly: true I then created a PersistentVolumeClaim so that I could attach this volume to multiple pods across multiple nodes. However, kubernetes indefinitely says it is in a pending state. kind: PersistentVolumeClaim apiVersion: v1 metadata: name: models-1-0-0-claim spec: accessModes: - ReadOnlyMany resources: requests: storage: 200Gi selector: matchLabels: name: models-1-0-0 Any insights? I feel there may be something wrong with the selector... Is it even possible to preconfigure a persistent disk with data and have pods across multiple nodes all be able to read from it?
I quickly realized that PersistentVolumeClaim defaults the storageClassName field to standard when not specified. However, when creating a PersistentVolume, storageClassName does not have a default, so the selector doesn't find a match. The following worked for me: kind: PersistentVolume apiVersion: v1 metadata: name: models-1-0-0 labels: name: models-1-0-0 spec: capacity: storage: 200Gi storageClassName: standard accessModes: - ReadOnlyMany gcePersistentDisk: pdName: models-1-0-0 fsType: ext4 readOnly: true --- kind: PersistentVolumeClaim apiVersion: v1 metadata: name: models-1-0-0-claim spec: accessModes: - ReadOnlyMany resources: requests: storage: 200Gi selector: matchLabels: name: models-1-0-0
Kubernetes
44,891,319
75
I am trying to create a Helm Chart with the following resources: Secret ConfigMap Service Job Deployment These are also in the order that I would like them to be deployed. I have put a hook in the Deployment so that it is post-install, but then Helm does not see it as a resource and I have to manually manage it. The Job needs the information in the Secret and ConfigMap, otherwise I would make that a pre-install hook. But I can't make everything a hook or nothing will be managed in my release. Does anyone have a solution or idea to be able to manage all of the resources within the Helm release AND make sure the Job finishes before the Deployment begins? My only thought right now is two make two Charts: One with 1-4 and the second with 5 which would depend on the first.
Helm collects all of the resources in a given Chart and it's dependencies, groups them by resource type, and then installs them in the following order (see here - Helm 2.10): Namespace ResourceQuota LimitRange PodSecurityPolicy Secret ConfigMap StorageClass PersistentVolume PersistentVolumeClaim ServiceAccount CustomResourceDefinition ClusterRole ClusterRoleBinding Role RoleBinding Service DaemonSet Pod ReplicationController ReplicaSet Deployment StatefulSet Job CronJob Ingress APIService During uninstallation of a release, the order is reversed (see here). Following this logic, in your case when your Job resource is created, both the Secret and the ConfigMap will already be applied, but Helm won't wait for the Job to complete before applying the Deployment. If you split your Chart to two parts (1-4, 5) and install them sequentially you would still have the problem of the Deployment being possibly applied before the Job is completed. What I would suggest is splitting your Chart to two parts (1-3, 4-5), in which the the Job has a pre-install hook, which would make sure it completes before your Deployment is applied.
Kubernetes
51,957,676
74
The best source for restart policies in Kubernetes I have found is this: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy But it only lists the possible restartPolicy values and does not explain them. What is the difference between Always and OnFailure? Mustn't the thing fail before it can be restarted?
Always means that the container will be restarted even if it exited with a zero exit code (i.e. successfully). This is useful when you don't care why the container exited, you just want to make sure that it is always running (e.g. a web server). This is the default. OnFailure means that the container will only be restarted if it exited with a non-zero exit code (i.e. something went wrong). This is useful when you want accomplish a certain task with the pod, and ensure that it completes successfully - if it doesn't it will be restarted until it does. Never means that the container will not be restarted regardless of why it exited. These different restart policies basically map to the different controller types as you can see from kubectl run --help: --restart="Always": The restart policy for this Pod. Legal values [Always, OnFailure, Never]. If set to 'Always' a deployment is created for this pod, if set to 'OnFailure', a job is created for this pod, if set to 'Never', a regular pod is created. For the latter two --replicas must be 1. Default 'Always' And the pod user-guide: ReplicationController is only appropriate for pods with RestartPolicy = Always. Job is only appropriate for pods with RestartPolicy equal to OnFailure or Never.
Kubernetes
40,530,946
74
How do I make an optional block in the values file and then refer to it in the template? For examples, say I have a values file that looks like the following: # values.yaml foo: bar: "something" And then I have a helm template that looks like this: {{ .Values.foo.bar }} What if I want to make the foo.bar in the values file optional? An error is raised if the foo key does not exist in the values. I've tried adding as an if conditional. However, this still fails if the foo key is missing: {{ if .Values.foo.bar }} {{ .Values.foo.bar }} {{ end }}
Simple workaround Wrap each nullable level with parentheses (). {{ ((.Values.foo).bar) }} Or {{ if ((.Values.foo).bar) }} {{ .Values.foo.bar }} {{ end }} How does it work? Helm uses the go text/template and inherits the behaviours from there. Each pair of parentheses () can be considered a pipeline. From the doc (https://pkg.go.dev/text/template#hdr-Actions) It is: The default textual representation (the same as would be printed by fmt.Print)... With the behaviour: If the value of the pipeline is empty, no output is generated... The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. As such, by wrapping each nullable level with parentheses, when they are chained, the predecessor nil pointer gracefully generates no output to the successor and so on, achieving the nested nullable fields workaround.
Kubernetes
59,795,596
73
I'm following that tutorial (https://www.baeldung.com/spring-boot-minikube) I want to create Kubernetes deployment in yaml file (simple-crud-dpl.yaml): apiVersion: apps/v1 kind: Deployment metadata: name: simple-crud spec: selector: matchLabels: app: simple-crud replicas: 3 template: metadata: labels: app: simple-crud spec: containers: - name: simple-crud image: simple-crud:latest imagePullPolicy: Never ports: - containerPort: 8080 but when I run kubectl create -f simple-crud-dpl.yaml i got: error: SchemaError(io.k8s.api.autoscaling.v2beta2.MetricTarget): invalid object doesn't have additional properties I'm using the newest version of kubectl: kubectl version Client Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.11", GitCommit:"637c7e288581ee40ab4ca210618a89a555b6e7e9", GitTreeState:"clean", BuildDate:"2018-11-26T14:38:32Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"darwin/amd64"} Server Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.0", GitCommit:"641856db18352033a0d96dbc99153fa3b27298e5", GitTreeState:"clean", BuildDate:"2019-03-25T15:45:25Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"linux/amd64"} I'm also using minikube locally as it's described in tutorial. Everything is working till deployment and service. I'm not able to do it.
After installing kubectl with brew you should run: rm /usr/local/bin/kubectl brew link --overwrite kubernetes-cli And also optionally: brew link --overwrite --dry-run kubernetes-cli.
Kubernetes
55,417,410
73
I have a bunch of pods in kubernetes which are completed (successfully or unsuccessfully) and I'd like to clean up the output of kubectl get pods. Here's what I see when I run kubectl get pods: NAME READY STATUS RESTARTS AGE intent-insights-aws-org-73-ingest-391c9384 0/1 ImagePullBackOff 0 8d intent-postgres-f6dfcddcc-5qwl7 1/1 Running 0 23h redis-scheduler-dev-master-0 1/1 Running 0 10h redis-scheduler-dev-metrics-85b45bbcc7-ch24g 1/1 Running 0 6d redis-scheduler-dev-slave-74c7cbb557-dmvfg 1/1 Running 0 10h redis-scheduler-dev-slave-74c7cbb557-jhqwx 1/1 Running 0 5d scheduler-5f48b845b6-d5p4s 2/2 Running 0 36m snapshot-169-5af87b54 0/1 Completed 0 20m snapshot-169-8705f77c 0/1 Completed 0 1h snapshot-169-be6f4774 0/1 Completed 0 1h snapshot-169-ce9a8946 0/1 Completed 0 1h snapshot-169-d3099b06 0/1 ImagePullBackOff 0 24m snapshot-204-50714c88 0/1 Completed 0 21m snapshot-204-7c86df5a 0/1 Completed 0 1h snapshot-204-87f35e36 0/1 ImagePullBackOff 0 26m snapshot-204-b3a4c292 0/1 Completed 0 1h snapshot-204-c3d90db6 0/1 Completed 0 1h snapshot-245-3c9a7226 0/1 ImagePullBackOff 0 28m snapshot-245-45a907a0 0/1 Completed 0 21m snapshot-245-71911b06 0/1 Completed 0 1h snapshot-245-a8f5dd5e 0/1 Completed 0 1h snapshot-245-b9132236 0/1 Completed 0 1h snapshot-76-1e515338 0/1 Completed 0 22m snapshot-76-4a7d9a30 0/1 Completed 0 1h snapshot-76-9e168c9e 0/1 Completed 0 1h snapshot-76-ae510372 0/1 Completed 0 1h snapshot-76-f166eb18 0/1 ImagePullBackOff 0 30m train-169-65f88cec 0/1 Error 0 20m train-169-9c92f72a 0/1 Error 0 1h train-169-c935fc84 0/1 Error 0 1h train-169-d9593f80 0/1 Error 0 1h train-204-70729e42 0/1 Error 0 20m train-204-9203be3e 0/1 Error 0 1h train-204-d3f2337c 0/1 Error 0 1h train-204-e41a3e88 0/1 Error 0 1h train-245-7b65d1f2 0/1 Error 0 19m train-245-a7510d5a 0/1 Error 0 1h train-245-debf763e 0/1 Error 0 1h train-245-eec1908e 0/1 Error 0 1h train-76-86381784 0/1 Completed 0 19m train-76-b1fdc202 0/1 Error 0 1h train-76-e972af06 0/1 Error 0 1h train-76-f993c8d8 0/1 Completed 0 1h webserver-7fc9c69f4d-mnrjj 2/2 Running 0 36m worker-6997bf76bd-kvjx4 2/2 Running 0 25m worker-6997bf76bd-prxbg 2/2 Running 0 36m and I'd like to get rid of the pods like train-204-d3f2337c. How can I do that?
You can do this a bit easier, now. You can list all completed pods by: kubectl get pod --field-selector=status.phase==Succeeded delete all completed pods by: kubectl delete pod --field-selector=status.phase==Succeeded and delete all errored pods by: kubectl delete pod --field-selector=status.phase==Failed
Kubernetes
55,072,235
73