Noise removal
If we don't remove the noise, we can detect more objects than we expect because noise is normally represented as small points in the image and can be segmented as an object. The sensor and scanner circuit normally produces this noise. This variation of brightness or color can be represented in different types, such as Gaussian noise, spike noise, and shot noise.
There are different techniques that can be used to remove the noise. Here, we are going to use a smooth operation, but depending on the type of noise, some are better than others. A median filter is normally used for removing salt-and-pepper noise; for example, consider the following image:
The preceding image is the original input with salt-and-pepper noise. If we apply a median blur, we get an awesome result in which we lose small details. For example, we lose the borders of the screw, but we maintain perfect edges. See the result in the following image:
If we apply a box filter or Gaussian filter, the noise is not removed but made smooth, and the details of the objects are lost and smoothened too. See the following image for the result:
OpenCV brings us the medianBlur function, which requires three parameters:
- An input image with the 1, 3, or 4 channel's image. When the kernel size is bigger than 5, the image depth can only be CV_8U.
- An output image, which is the resulting image on applying median blur with the same type and depth as the input.
- Kernel size, which is an aperture size greater than 1 and odd, for example, 3, 5, 7, and so on.
The following code is used to remove noise:
Mat img_noise; medianBlur(img, img_noise, 3);