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... | 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.
... | 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.... | 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):
contour... | 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?
T... | 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... | 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 ... | 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 ... | 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... | 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) # ... | 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 ... | 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.... | 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, ... | 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),... | 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_dens... | 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 bounda... | 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 informat... | 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 t... |
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... | 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_IMA... | 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 publish... | 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
... | 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 ... | 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. W... | 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... | 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 | 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 Matp... | 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):
... | 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_N... | 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 mos... | 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 ... | 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;
Ro... | 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... | 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-densit... | 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 fi... | 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... | 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"... | 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... | 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]
# h... | 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]
c... | 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.ara... | 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... | 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 th... | 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 ... | 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 differe... | 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 work... | 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... | 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... | 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)) ... | 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)
... | 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 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 ... | 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 );... | 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>
... | 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::Rec... | 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... | 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 pr... | 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 try... | 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 issue... | 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 m... | 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, ... | 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 a... | 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)
... | 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, s... | 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... | 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 ... | 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 ... | 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.m... | 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(... | 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... | 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, ... | 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... | 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
}
T... | 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 connecto... | 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). ... | 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 i... | 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... | 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... | 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:... | 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,... | 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,BDmatri... | 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 th... | 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 o... | 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... | 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.... | 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... | 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, floa... | 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 ... | 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... | 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 o... | 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]; %//... | 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)*... | 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 ... | 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 absol... | 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,... | 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... | 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 ... | 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... | 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... | 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... | 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-dime... | 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.rand... | 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 wa... | 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 ... | 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... | 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 upda... | 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://ch... | 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:
- cont... | 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 g... | 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 s... | 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 ... | 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 ... | 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 fi... | 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:
... | 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... | 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 RO... | 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 ... | 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 containe... | 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... | 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 know... | 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 wh... | 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 fol... | 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 wheth... | 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" d... | 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 ... | 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 ... | 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 e... | 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 se... | 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 t... | 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... | 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. Bu... | 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_PASSWOR... | 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
... | 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
... | 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:... | 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 ... | 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... | 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... | 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... | 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
... | 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 c... | 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" m... | 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 a... | 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 Kustomi... | 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 ... | 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 vers... | 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 swit... | 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, upgrad... | 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... | 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 "... | 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 arg... | 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.
#
api... | 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-... | 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
m... | 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.... | 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:
- i... | 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 dat... | 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 comm... | 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:"... | 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 f... | 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: REDA... | 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 (w... | 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 kub... | 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 --... | 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... | 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;... | 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 anyon... | 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 ... | 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: 200G... | 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... | 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... | 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
CustomR... | 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 c... | 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 resta... | 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 va... | 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 (htt... | 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:... | 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-391... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.