I am trying to fill some empty areas and remove protruding areas to make the image smoother. But it works to an extent only. The largest contour needs to be made smoother. Input Image:
import os
import sys
import cv2
import numpy as np
Dd = cv2.imread('images/input.png', 0)
kernel = np.ones((6,6),np.uint8)
DdErode = 1;
DdDilate = 1;
Dd = cv2.erode(Dd,kernel,iterations = DdErode)
Dd = cv2.dilate(Dd,kernel,iterations = DdDilate)
im2, contours, hierarchy = cv2.findContours(Dd, cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
maxArea = 0;
position = 0;
maxPosition =0;
for cont in contours :
area = cv2.contourArea(cont);
if area > maxArea :
maxArea = area;
maxPosition = position;
position = position + 1;
# print (maxArea);
epsilon = 0.001*cv2.arcLength(contours[maxPosition],True)
epsilon = 0.001*cv2.arcLength(contours[maxPosition],True)
approx = cv2.approxPolyDP(contours[maxPosition],epsilon,True)
cv2.drawContours(Dd, [approx], -1, (255, 255, 0), -1)
cv2.imwrite('images/output.jpg', Dd)
The output of the program
But I was trying for something without the dents and protruding parts as below. Is there a way to do it?
You're using a square kernel, which will give your shapes square corners. Using a circular one will give smoother, rounded corners. Also, using a kernel with an even number of pixels each side will cause your shape to shift slightly. Odd numbers are better for kernel sizes.
Also, the more iterations you use, the more smoothing you get. If you use too many iterations, it will start to remove important details. So, start with 1 iteration, and increase iterations until you are happy.
I got this result using a 7x7 circular kernel, 5 iterations of erosion followed by 5 iterations of dilation:
Code:
Dd = cv2.imread('images/input.png', 0)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))
Dd = cv2.erode(Dd,kernel,iterations = 5)
Dd = cv2.dilate(Dd,kernel,iterations = 5)
cv2.imwrite('images/output.png', Dd)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.