I am detecting a contour of a smooth metal. I do binarization first then use openCV contour function. But sometimes the metal has defects such as dots or dusts at edge. This leads a unsmooth edge. Is there any way I can detect these defects with openCV function or some math calculation? This is the contour result. This is zoomed images for defected contour result.
My suggestion: find the center, calculate the distance of each pixel to the center. If a given distance is too (above threshold) different from the neighborhood then it's a defect. Other possibility is to fit a figure model if you always have the same shape and then calculate the error.
Couple of approaches come to mind: you could pick an arbitrary "first" red pixel, then take a square of say 5×5 pixels around it, and simply figure out which quadratic function is a best fit for these, and infer the curvature from that.
Pick an arbitrary direction to start from that point and pick the next pixels; calculate the curvature of the 5×5 square surrounding that pixel. Find the absolute difference between last and current curvature; if it changed too much, you've found an abrupt corner.
In your specific example, applying to the whole image a 5×5 moving average filter would also suffice: Far as I can tell, there shouldn't be more than a relatively low number of red pixels in every 5×5 square, so if there's one with more, you've got your type of defect.
Other options include morphological classical tricks like erosion / dilation: use one operation to surround every red pixels with a fixed-diameter disk of red. Then do the same, with a diameter one linewidth (or more) larger disk, with the white in the picture. Check whether anything remains red afterwards.
PS: JPEG is the wrong image format / compression for line-style graphics. You'd want to work with PNG.