I am trying to perform image erosion with OpenCV. I want to do it like this: Suppose I have four different elements
S1 = [ 0 1 0, 0 1 0, 0 1 0 ]
S2 = [ 0 0 0, 1 1 1, 0 0 0 ]
S3 = [ 0 0 1, 0 1 0, 1 0 0 ]
S4 = [ 0 1 0, 1 1 1, 0 1 0 ]
And I want to perform four different erosions with these elements on original image:
E1 = I & S1
E2 = I & S2
E3 = I & S3
E4 = I & S4
where “I” is the original image, and I used “&” to denote erosion for simplicity. Then I want to obtain the final erosion with the addition of these four:
E = E1 + E2 + E3 + E4
But when implementing these with opencv, I’ve encountered difficulties in early stages. I declared the elements like this:
int S1[3][3] = { { 0, 1, 0 }, { 0, 1, 0 }, { 0, 1, 0 } };
int S2[3][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 0, 0, 0 } };
int S3[3][3] = { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 0, 0 } };
int S4[3][3] = { { 0, 1, 0 }, { 1, 1, 1 }, { 0, 1, 0 } };
Then for using “cv::erode” I have difficulties with these elements since they are not the acceptable type. How can I use these elements to obtain my desired erosion mentioned above? Thank you in advance.
You’ll probably need to create a
cv::Matfrom your desired kernel shapes, these are known as Structuring elements, and OpenCV provides the getStructuringElement function to create a few common shapes.Alternatively, you can form your own by creating a new matrix from your data directly using something like:
You can confirm whether this is correct by displaying it in the terminal:
Once you’ve found your matrices, they can also be easily combined by simple arithmetic operations such as: