Skip to main content

Optimum design of chamfer masks using symmetric mean absolute percentage error

Abstract

Distance transform, a central operation in image and video analysis, involves finding the shortest path between feature and non-feature entries of a binary image. The process may be implemented using chamfer-based sequential algorithms that apply small-neighborhood masks to estimate the Euclidean metric. Success of these algorithms depends on the cost function used to optimize chamfer weights. And, for years, mean absolute error and mean squared error have been used for optimization. However, studies have revealed weaknesses of these cost functions—sensitivity against outliers, lack of symmetry, and biasedness—which limit their application. In this work, we have proposed a robust and a more accurate cost function, symmetric mean absolute percentage error, which attempts to address some weaknesses. The proposed function averages the absolute percentage errors in a set of measurements and offers interesting mathematical properties (smoothness, differentiability, boundedness, and robustness) that allow easy interpretation and analysis of the results. Numerical results show that chamfer masks designed under our optimization criterion generate lower errors. The present work has also proposed an automatic algorithm that converts coefficients of the designed real-valued masks into integers, which are preferable in most practical computing devices. Lastly, we have modified the chamfer algorithm to improve its speed and then embedded the proposed weights into the algorithm to compute distance maps of real images. Results show that the proposed algorithm is faster and uses fewer number of operations compared with those consumed by the classical chamfer algorithm. Our results may be useful in robotics to address the matching problem.

1 Introduction

In computer vision and image processing fields, a distance transform (DT) refers to an operation that measures the degree of closeness between object and non-object features in a binary image. The result of DT defines a map that holds grayscale values, with each value denoting the distance of an object from the nearest edge. DTs are useful in various image analysis tasks, such as skeletonization, segmentation, shape description, object detection and recognition, multi-scale morphological filtering, and feature analysis [1, 2].

Traditionally, the Euclidean metric—a distance function that obeys four well-established axioms: non-negativity, symmetry, identity of indiscernibles, and subadditivity—has been used to compute DTs. The Euclidean distance transform (EDT) possesses an isotropic nature, a desirable property required by sophisticated applications. But implementation of EDT follows irregular patterns that limit the development processes. Also, certain simple applications only demand rough distance estimations, which can quickly be computed in linear times. Therefore, variants of EDT algorithms that reasonably approximate the classical Euclidean metric have been proposed to address these research gaps [315].

Among a class of efficient algorithms to approximate EDT include those based on the chamfer metric [1, 1625]. The chamfer-driven DTs use weighted masks to propagate local distances over an image. The chamfering process can be engineered in two modes: parallel, which applies the whole mask to estimate EDT; and sequential, which requires that the mask is split into two halves, forward and backward masks. The parallel mode demands a special computing device with optimized computational resources. Our work is built on chamfer-based sequential algorithms, which can be implemented in both special and general purpose processors.

The challenging task in DTs based on the chamfer metric is to design weights for the masks that can estimate more accurately the Euclidean metric. Chamfer masks are usually designed using cost functions and, for decades, mean absolute error (MAE) and mean squared error (MSE) have been used for this purpose. But both MAE and MSE endure some weaknesses: biasedness, lack of symmetry, and sensitivity to outliers [26], which may limit their usefulness.

In this work, we have proposed an alternative cost function, symmetric mean absolute percentage error (SMAPE), to design chamfer masks. SMAPE, which is widely used in weather forecasting applications, is a bounded function (0−100%)—a property that makes it easier to analyze and interpret—that computes average of the relative accuracy between reference and estimated values. SMAPE robustly rejects outliers and efficiently lowers influences of noise in the data [27, 28].

In resource-limited settings, practitioners discourage real-valued chamfer masks because they limit speed and waste hardware computational resources. We have addressed this issue by developing an algorithm that automatically maps values in the designed masks into integers. The proposed weights were applied to the modified chamfer algorithm to produce distance maps of real edge images.

Experimental results demonstrate that most distance maps generated through the proposed weights give lower values of SMAPE, MAE, and MSE compared with those produced by previous studies. The observation confirms that our weights are relatively more accurate and may be applied in critical tasks.

Additionally, we have analyzed the first-pass stage of the original chamfer algorithm and developed a strategy to discard unnecessary operations. Experiments on synthetic single-feature images show that the proposed strategy raises significantly speed of the classical chamfer algorithm, a result that may add value in real-world applications of DTs.

2 Methods

2.1 Preliminaries

Chamfer masks may be characterized based on two factors: size, which defines the physical dimensions of the mask, and local weights (Fig. 1). In the chamfering process, the algorithm estimates distance maps by propagating the local weights over an image. Larger chamfer masks holding accurate and optimized weights generate lower estimation errors.

Fig. 1
figure 1

Chamfer masks. From the center moving outwards, thick lines indicate 3×3, blue; 5×5, red; and 7×7, green. Forward and backward masks are obtained by splitting the mask along the dotted lines

The classical EDT gives a uniform disc of radius, r; the chamfer algorithm generates a regular polygon with number of sides dependent on the size of the mask. For example, a 3×3 mask produces an octagon. Each side of the polygon obeys the equation Uy+Vx=r, where U and V represent coefficients that define mask size. For instance, the 3×3 mask contains \(a\in \mathbb {R}\) and \(b\in \mathbb {R}\) as its local weights: U=ba and V=a.

Figure 2a illustrates an octant part of the chamfer polygon generated by the 3×3 mask. We shall use this figure to generalize formulations for all mask sizes. Let f(θ) be a function that defines the length of \(\vec {t}\), an arbitrary distance from the polygon’s side to the center. Using side-angle relationship rules from trigonometry, we have

$$ f(\theta)=\frac{r\sin\theta_{1}}{V\sin(\theta+\theta_{1})} $$
(1)
Fig. 2
figure 2

Octant portion of the chamfer polygon generated by a 3×3 mask. \(\overline {AC}\) and \(\overline {A'C'}\) satisfy the equation l:(ba)y+ax=r, where a and b represent local distances of the mask. a Euclidean weights, A=(r,0) and \(C=\left (\frac {r}{\sqrt {2}}, \frac {r}{\sqrt {2}}\right)\). b Optimized weights, \(A^{\prime } = \left (\frac {r}{a}, 0\right), C^{\prime } = \left (\frac {r}{b}, \frac {r}{b}\right)\), and \(\overline {OA^{\prime }} = \overline {OC^{\prime }}\)

and

$$ \sin\theta_{1}=\frac{V}{\sqrt{U^{2}+V^{2}}}. $$
(2)

Combining (1) and (2), then simplifying the resulting equation, we get

$$ f(\theta)=\frac{r}{U\sin\theta+V\cos\theta}, $$
(3)

in which f(θ) may be regarded as the radius of a chamfer polygon that estimates the Euclidean disc: U (coefficient of sinθ) and V (coefficient of cosθ) are functions of the chamfer weights.

SMAPE, detailed in the next sections, between r and f is then calculated as

$$ Z(\theta)=\frac{r-f(\theta)}{r+f(\theta)}=\frac{U\sin\theta+V\cos\theta-1}{U\sin\theta+V\cos\theta+1}, $$
(4)

which signifies mean of the positive difference between r and f. Chamfer polygons are symmetrical with respect to the coordinate axes, and thus the function Z is analyzed in an octant part or within θ[0,45]. Z=0% when r=f, perfect match; and Z=100% when f=0, perfect mismatch. Robustness of SMAPE against outliers can be attributed from the averaging operation 1/(r+f) in Z. Therefore, for a series of data, SMAPE minimizes the effect of unusual measurements.

2.2 Optimization of chamfer masks

2.2.1 General principles

The primary goal when designing chamfer masks is to compute optimal weights in the masks that minimize the maximum possible error. In our case, SMAPE has been opted as an optimization criterion. Equivalently, we want to compute weights that minimize the maximum SMAPE within the defined region of the chamfer polygon.

For demonstration purposes, we give two scenarios to justify our decision to select SMAPE as an optimization rule:

  1. (1)

    Imagine two sets of measurements: r1=1, f1(θ)=0.75 and r2=0.75,f2(θ)=1. Note that (r1,r2) may be regarded as radii of the Euclidean disc, and (f1,f2) as the lengths of vectors touching perpendicularly the polygon’s side. The absolute error in both cases is 0.25. But applying MAE on the measurements yields 25% and 33% for the first and the second cases, respectively. This variability of results makes MAE a poor statistical estimator. On the contrary, each of the pairs of measurements give a SMAPE value of 14.30%—signaling stability of the metric.

  2. (2)

    Let f(θ) be corrupted by an additive noise, η. Incorporating this condition into (4) and simplifying the result, we get

    $$ Z_{\eta}(\theta)=\frac{1-\frac{f(\theta)}{r} + \frac{\eta}{r}}{1+\frac{f(\theta)}{r} + \frac{\eta}{r}}. $$
    (5)

    The term \(\frac {\eta }{r}\) in (5) minimizes the influence of noise in f(θ) or lowers the quantity |Zη(θ)−Z(θ)|.

In an unoptimized case, chamfer masks of sizes above three generate SMAPE curves with a single major error lobe—which defines the longest polygon’s edge and associates the global peak of Z—and several minor error lobes controlled by local weights with insignificant impacts on the maximum error (unless for improperly designed chamfer weights; a 3×3 mask contains a single error lobe).

Butt et al. proposed large-neighborhood masks to achieve even better approximations to the Euclidean distance [29]. The authors recommended that the main lobe can be optimized by using the following techniques:

  1. (1)

    Considering −Z(0)=Zm, where

    $$ Z_{\mathrm{m}}=\frac{\sqrt{U^{2}+V^{2}} - 1}{\sqrt{U^{2}+V^{2}}+1} $$
    (6)

    denotes the global maximum of Z that occurs at

    $$ \theta_{\mathrm{m}}=\arctan\left(\frac{U}{V}\right); \text{~~and~~} $$
    (7)
  2. (2)

    Ensuring that the border line segments subtended by an angle

    $$ \alpha=\arccos\left(\frac{V-U\sqrt{U^{2}+V^{2}-1}}{U^{2}+V^{2}}\right) $$
    (8)

    in the chamfer octant are equal.

The maximum error can also be located at α. Hence, the maximum SMAPE on the major error lobe can be computed by the equation

$$ M=\max\{|Z_{m}|,|Z(\alpha)|\}. $$
(9)

General proofs shared by all chamfer masks are shown in Appendices Appendix 1: Existence of maximum in SMAPE, Appendix 2: Intercepts on the SMAPE curve, and Appendix 3: Optimum chamfer weights: existence of the maximum on the SMAPE curve, intercepts of Z on the θ-axis, and computation of optimal chamfer weights, respectively.

2.2.2 3×3 neighborhood

In a 3×3 mask, two non-redundant local distances, a and b, should be optimized (Fig. 1). Let \(\vec {t}\) be a vector from the disc’s origin to an edge of the chamfer polygon, and r be the radius of a disc generated by the global Euclidean metric. Then, optimization demands values of a and b that minimize the maximum of an error \(|r-{\lVert }{\vec {t}}|{\rVert }/(r+{\lVert }{\vec {t}}{\rVert })\). We analyze errors in the wedge-shaped region {(x,y):x≥0, y≥0, and yx} because the chamfer polygon supports symmetry properties along the axes and diagonals (Fig. 2). In this region, points on portion of the polygon’s side, line segment \(\overline {AC}\), satisfy the equation (ba)y+ax=r.

The length of \(\vec {t}\) is given by

$$ f(\theta)=\frac{r\sin\theta_{1}}{a\sin(\theta+\theta_{1})}, $$
(10)

where

$$\theta_{1}=\arctan\left(\frac{a}{b-a}\right).$$

Simplifying (10) yields

$$ f(\theta)=\frac{r}{(b-a)\sin\theta+a\cos\theta}. $$
(11)

Plugging (11) into the SMAPE formula, we have

$$ Z(\theta)=\frac{(b-a)\sin\theta+a\cos\theta-1}{(b-a)\sin\theta+a\cos\theta+1}. $$
(12)

Thus, (comparing Eqs. 4 and 12) U=ba and V=a. For the Euclidean metric, a=1 and \(b=\sqrt {2}\). Therefore, the maximum of Z becomes

$$ Z_{\mathrm{m}}=\frac{\sqrt{(\sqrt{2}-1)^{2}+1} - 1}{\sqrt{(\sqrt{2}-1)^{2}+1} + 1}=3.96\% $$
(13)

and is located at

$$ \theta_{\mathrm{m}}=\arctan(\sqrt{2}-1)=22.5^{\circ}. $$
(14)

Under optimal conditions, \(b=\sqrt {2}a\) or \(\overline {OA'}=\overline {OC'}\) in Fig. 2b, and

$$ -\frac{a-1}{a+1}=\frac{\sqrt{(b-a)^{2}+a^{2}} - 1}{\sqrt{(b-a)^{2}+a^{2}} + 1} $$

or −Z(0)=Zm, which simplify to the optimal weights

$$a_{\text{opt}}=\frac{1}{\sqrt[4]{(\sqrt{2}-1)^{2}+1}}=0.9612 $$

and bopt=1.3593. These proposed weights give a maximum SMAPE of 1.979%, a value that improves an error of EDT by 50% (Fig. 3).

Fig. 3
figure 3

Symmetric mean absolute percentage error (left column) and edge geometry (right column) generated by 3×3 chamfer mask. a Euclidean weights, a=1 and \(b=\sqrt {2}\). b Euclidean weights, a=1, \(b=\sqrt {2}\), and r=1c. Our weights, a=0.9612 and b=1.3593d. Our weights, a=0.9612, b=1.3593, and r=1

2.2.3 5×5 neighborhood

The 5×5 mask holds three non-redundant local distances: a, horizontal/vertical; b, diagonal; and c, off-diagonal knight’s move (Fig. 1). If all weights are used, the mask generates a regular hexadecagon that contains wedge-shaped octants, each extended by two line segments. Same as before, symmetry allows us to analyze errors within an octant.

From Fig. 4, applying the sine rule yields the length of \(\vec {t}\) as

$$ f_{1}(\theta) = \frac{r\sin\theta_{1}}{a\sin(\theta+\theta_{1})}=\frac{r}{(c-2a)\sin\theta+a\cos\theta} $$
(15)
Fig. 4
figure 4

Octant portion of the chamfer polygon generated by a 5×5 mask. Lines that overlap the polygon’s sides are defined by l1:(c−2a)y+ax=r and l2:(2bc)y+(cb)x=r. Critical corner points are \(A\left (\frac {r}{a},0\right)\), \(C\left (\frac {r}{b},\frac {r}{b}\right)\), \(E\left (\frac {2r}{c},\frac {r}{c}\right)\), and \(F\left (\frac {r}{c-b},0\right)\). For the Euclidean local neighborhood, a=1, \(b=\sqrt {2}\), and \(c=\sqrt {5}\)

and that of \(\vec {s}\) as

$$ {}{\begin{aligned} f_{2}(\theta) = \frac{r\sin\theta_{2}}{(c-b)\sin(\theta+\theta_{2})}=\frac{r}{(2b-c)\sin\theta+(c-b)\cos\theta}, \end{aligned}} $$
(16)

where

$$\begin{array}{*{20}l} \theta_{1}=\arctan\left(\frac{a}{c-2a}\right) \text{~~and~~}\theta_{2}=\arctan\left(\frac{c-b}{2b-c}\right). \end{array} $$

The SMAPE formulae corresponding to f1 and f2 are

$$ {}Z_{1}(\theta)\,=\,\frac{(c-2a)\sin\theta+a\cos\theta-1}{(c-2a)\sin\theta+a\cos\theta+1}\text{~~~~~for }\theta\in[0^{\circ},26.57^{\circ}], $$
(17)

major error lobe; and

$$ {}{\begin{aligned} Z_{2}(\theta)=\frac{(2b-c)\sin\theta+(c-b)\cos\theta-1}{(2b-c)\sin\theta+(c-b)\cos\theta+1}\text{~~~~~for }\theta\in[26.57^{\circ},45^{\circ}], \end{aligned}} $$
(18)

minor error lobe.

Considering the major error lobe, we have U=c−2a and V=a. In the Euclidean case, a=1 and \(c=\sqrt {5}\). These unoptimized values give a maximum SMAPE of

$$Z_{\mathrm{1m}}=\frac{\sqrt{(\sqrt{5}-2)^{2}+1} - 1}{\sqrt{(\sqrt{5}-2)^{2}+1} + 1}=1.36\% $$

that occurs at \(\arctan \left (\sqrt {5}-2\right)=13.28^{\circ }\).

Using the similar optimization strategy, \(\overline {AE}\) in Fig. 4 must be pushed outwards such that −Z1(0)=Z1m and \(c=\sqrt {5}a\). These conditions give

$$a_{\text{opt}}=\frac{1}{\sqrt[4]{(\sqrt{5}-2)^{2}+1}}=0.9865 $$

and copt=2.2059 as optimal weights of the chamfer mask. In this case, the maximum SMAPE reduces to Z1opt=0.68% (Fig. 5).

Fig. 5
figure 5

Symmetric mean absolute percentage error or SMAPE (left column) and edge geometry (right column) generated by a 5×5 chamfer kernel. a Euclidean weights, a=1, \(b=\sqrt {2}\), and \(c=\sqrt {5}\). b Euclidean weights, a=1, \(b=\sqrt {2}\), \(c=\sqrt {5}\), and r=1. c Our weights, a=0.9865, \(b=\sqrt {2}\), and c=2.2059. d Our weights, a=0.9865, \(b=\sqrt {2}\), c=2.2059, and r=1

The value of b should be selected carefully such that growth of the minor lobe is restricted to the bound given by Z1opt. That is, allowable ranges of b can be obtained by solving

$$ {}{\begin{aligned} \left|\frac{(2b-c_{\text{opt}})^{2}+(c_{\text{opt}}-b)^{2}-\sqrt{(c_{\text{opt}}-b)^{2}+(2b-c_{\text{opt}})^{2}}}{(2b-c_{\text{opt}})^{2}+(c_{\text{opt}}-b)^{2}+\sqrt{(c_{\text{opt}}-b)^{2}+(2b-c_{\text{opt}})^{2}}}\right|\le Z_{\mathrm{1opt}}. \end{aligned}} $$
(19)

Simplifying (19) yields

$$ {}{\begin{aligned} 25Jb^{4}&-60Jb^{3}c_{\text{opt}}+\left(56Jc_{\text{opt}}^{2}-5\right)b^{2}+\left(6c_{\text{opt}}-24Jc_{\text{opt}}^{3}\right)\!b\\&+\left(4Jc_{\text{opt}}^{4}-2c_{\text{opt}}^{2}\right)=0, \end{aligned}} $$
(20)

where

$$ J=\left(\frac{1\pm Z_{\mathrm{1opt}}}{1\mp Z_{\mathrm{1opt}}}\right)^{2}. $$
(21)

The roots of (20) are 1.2193, 1.3189, 1.3281, and 1.4276. Hence, we recommend to select b between 1.2193<b<1.3189 or 1.3281<b<1.4276. Figure 6a shows how b influences SMAPE values within the minor lobe.

Fig. 6
figure 6

Variation of symmetric mean absolute percentage error (SMAPE) with non-redundant local distances controlling minor lobes. a 5×5 kernel. b 7×7 kernel. c 7×7 kernel, e=3.5830.d 7×7 Kernel, \(c=\sqrt {5}\)

2.2.4 7×7 neighborhood

This mask uses five non-redundant local distances, namely a, b, c, d, and e, to generate a 32-sided regular polygon, which is more accurate compared to those generated by 3×3 and 5×5 masks. Some weights in the 7×7 mask are unimportant because they form multiples of other variables in the mask (Fig. 1).

Consider the four-sided portion of the chamfer polygon generated by a 7×7 mask (Fig. 7). Also, let f1(θ), f2(θ), f3(θ), and f4(θ) be the lengths of \(\vec {t}\), \(\vec {s}\), \(\vec {q}\), and \(\vec {p}\), respectively. Applying the sine rule, we get

$$ f_{1}(\theta)=\frac{r\sin\theta_{1}}{a\sin(\theta+\theta_{1})}=\frac{r}{(d-3a)\sin\theta+a\cos\theta}, $$
(22)
Fig. 7
figure 7

Octant portion of the chamfer polygon generated by a 7×7 mask. l1:(d−3a)y+ax=r, l2:(3c−2d)y+(dc)x=r, l3:(2e−3c)y+(2ce)x=r, and l4:(3be)y+(e−2b)x=r. AOE=45 and corner points are \(A(\frac {r}{a},0)\), \(B(\frac {3r}{d},\frac {r}{d})\), \(C(\frac {2r}{c},\frac {r}{c})\), \(D(\frac {3r}{e},\frac {2r}{e})\), \(E(\frac {r}{b},\frac {r}{b})\), \(P(\frac {r}{d-c},0)\), \(Q(\frac {r}{2c-e},0)\), and \(R(\frac {r}{e-2b},0)\)

$$ {}{\begin{aligned} f_{2}(\theta)=\frac{r\sin\theta_{2}}{(d-c)\sin(\theta+\theta_{2})}=\frac{r}{(3c-2d)\sin\theta+(d-c)\cos\theta}, \end{aligned}} $$
(23)
$$ {}{\begin{aligned} f_{3}(\theta)=\frac{r\sin\theta_{3}}{(2c-e)\sin(\theta+\theta_{3})}=\frac{r}{(2e-3c)\sin\theta+(2c-e)\cos\theta}, \end{aligned}} $$
(24)

and

$$ {}{\begin{aligned} f_{4}(\theta)=\frac{r\sin\theta_{4}}{(e-2b)\sin(\theta+\theta_{4})}=\frac{r}{(3b-e)\sin\theta+(e-2b)\cos\theta}, \end{aligned}} $$
(25)

where

$$ {}{\begin{aligned} \theta_{1}=\arctan\left(\frac{a}{d-3a}\right),~~ \theta_{2}=\arctan\left(\frac{d-c}{3c-2d}\right),\\ \theta_{3}=\arctan\left(\frac{2c-e}{2e-3c}\right), \text{~~and~~}\theta_{4}=\arctan\left(\frac{e-2b}{3b-e}\right). \end{aligned}} $$
(26)

Therefore, the SMAPE formulae corresponding to f1, f2, f3, and f4 are

$$ Z_{1}(\theta)=\frac{(d-3a)\sin\theta+a\cos\theta-1}{(d-3a)\sin\theta+a\cos\theta+1}~~~~\theta\in[0^{\circ},18.43^{\circ}]\!, $$
(27)
$$ {}{\begin{aligned} Z_{2}(\theta)=\frac{(3c-2d)\sin\theta+(d-c)\cos\theta-1}{(3c-2d)\sin\theta+(d-c)\cos\theta+1}~~~~\theta\in[18.43^{\circ},26.57^{\circ}], \end{aligned}} $$
(28)
$$ {}{\begin{aligned} Z_{3}(\theta)=\frac{(2e-3c)\sin\theta+(2c-e)\cos\theta-1}{(2e-3c)\sin\theta+(2c-e)\cos\theta+1}~~~~\theta\in[26.57^{\circ},33.69^{\circ}], \end{aligned}} $$
(29)

and

$$ {}{\begin{aligned} Z_{4}(\theta)=\frac{(3b-e)\sin\theta+(e-2b)\cos\theta-1}{(3b-e)\sin\theta+(e-2b)\cos\theta+1}~~~~\theta\in[33.69^{\circ},45.00^{\circ}]. \end{aligned}} $$
(30)

Considering Z1(θ), the major error lobe, we have U=d−3a and V=a. For the Euclidean case, a=1 and \(d=\sqrt {10}\). These values produce a maximum SMAPE of

$$Z_{\mathrm{1m}}=\frac{\sqrt{(\sqrt{10}-3)^{2}+1} - 1}{\sqrt{(\sqrt{10}-3)^{2}+1} + 1}=0.65\% $$

that occurs at \(\arctan (\sqrt {10}-3)=9.22^{\circ }\). To reduce Z1m, we consider the conditions \(d=\sqrt {10}a\) and −Z1(0)=Z1m and obtain the optimal weights

$$a_{\text{opt}}=\frac{1}{\sqrt[4]{(\sqrt{10}-3)^{2}+1}}=0.9935 $$

and dopt=3.1417, which give a maximum SMAPE of Z1opt=0.32% (Fig. 8).

Fig. 8
figure 8

Symmetric mean absolute percentage error and edge geometries generated by a 7×7 chamfer kernel. a Euclidean weights, a=1, \(b=\sqrt {2}\), \(c=\sqrt {5}\), \(d=\sqrt {10}\), and \(e=\sqrt {13}\). b Euclidean weights, a=0.9935, \(b=\sqrt {2}\), \(c=\sqrt {5}\), d=3.1417, and e=3.5830. c Our weights, a=0.9935, \(b=\sqrt {2}\), \(c=\sqrt {(5)}\), d=3.1417, and e=3.5830. d Our weights, a=0.9935, \(b=\sqrt {2}\), \(c=\sqrt {5}\), d=3.1417, and e=3.5830

The values of b, c, and e are less important, but they should be chosen such that the minor lobes fail to explode above Z1opt, or

$$ \left|\frac{U^{2}+V^{2}-\sqrt{U^{2}+V^{2}}}{U^{2}+V^{2}+\sqrt{U^{2}+V^{2}}}\right|\le Z_{\mathrm{1opt}}, $$
(31)

where Z2,(U,V)=(3c−2d,dc); Z3,(U,V)=(2e−3c,2ce); and Z4,(U,V)=(3be,e−2b). Substituting definitions of U and V into (31), then rewriting and simplifying the resulting equations, we get

$$ {}{\begin{aligned} 100Jc^{4}&-280Jd_{\text{opt}}c^{3}+\left(296d_{\text{opt}}^{2}J-10\right)c^{2}\\&+\left(14d_{\text{opt}}-140Jd_{\text{opt}}^{3}\right)c+\left(25Jd_{\text{opt}}^{4}-5d_{\text{opt}}^{2}\right)=0, \end{aligned}} $$
(32)
$$ {}{\begin{aligned} 25Je^{4}&-160Jce^{3}+(386Jc^{2}-5)e^{2}+(16c-416c^{3}J)e\\&+(169Jc^{4}-13c^{2})=0, \end{aligned}} $$
(33)

and

$$ {}{\begin{aligned} 169Jb^{4}&-260Jeb^{3}+\left(152Je^{2}-13\right)b^{2}+\left(10e-40Je^{3}\right)b\\&+\left(4Je^{4}-2e^{2}\right)=0, \end{aligned}} $$
(34)

where J is as defined in (21). As depicted by Fig. 6b–d, solving (32) yields 2.1483<c<2.1979 and 2.2006<c<2.2502 as valid ranges of the local weight c. The natural choice is the Euclidean value \(c=\sqrt {5}\). Solving (33) and (34) is rather challenging because the values of b and e depend on each other and are implicitly defined in the equations. To address the problem, we substituted the chosen value of c into (33) and solved for the valid range of e, then selected the value of e in the range and substituted it into (34) to get the possible valid values of b. Lastly, the computed range of b was inspected for a subset that restricts errors in both minor and major lobes within the acceptable range (0% to 0.32%). Following this strategy, we achieved 3.5266<e<3.6288, e=3.5830; and 1.4051<b<1.4224, \(b=\sqrt {2}\). Figure 6b, d show the variations of SMAPE with the local weights b and e in minor error lobes, respectively.

3 Integer approximations

In previous sections, we have proposed real-valued chamfer weights for various sizes of masks. However, time-driven tasks require integers to accelerate computations. Additionally, integer-steered masks allow hardware platforms to use computational resources more efficiently, an advantage that lowers manufacturing costs. Therefore, an automatic and a simple technique has been developed to generate integers from real-valued masks. Our desire is to achieve the following qualities of integers: lower relative errors, common divisor, and convenient magnitudes—preferably in the order of ones, tens, or hundreds.

The proposed algorithm operates as follows: firstly, weights are multiplied by integers, i, between two and the selected maximum, say 1000. Next, each multiplication is treated by floor and ceil operators, one after another. Next, corresponding absolute values are taken. Finally, the value of i that minimizes errors due to all multiplied weights become a common divisor.

Algorithm 1 summarizes our approach to compute inter-valued chamfer masks. From the Algorithm, 0<ε<1 defines fidelity of the results and can be manually set: smaller values of ε give more accurate integer weights. This work used ε=0.0025 as a thresholding constant to convert real-valued chamfer weights into integers. And, for simplicity, we have selected a 3×3 mask—but the idea may be extended to larger chamfer masks.

4 Fast chamfer algorithm

Distance transforms may be implemented through the chamfering process that uses two masks, forward and backward, to propagate local distances over an image. The process undertakes two passes to estimate EDT and operates as follows: in the first pass, non-feature entries of a target image are initialized with a suitably large number, as Fig. 9a depicts. Next, the forward mask is pushed from left-right and top-down directions of an image, and at each movement step, masks’ weights are added to the corresponding image’s entries below them. Then, an entry in the image just below the zero-valued mask’s location (center of the whole mask) is replaced by minimum of the additions, as shown in Fig. 9b. These procedures are repeated until the forward mask covers pixels in the bottom right portion of the image. Lastly, the second pass applies the backward mask and uses similar operations like those in the forward mask to propagate distance vectors from the image’s right-left and bottom-up directions. Figure 9c shows the distance image after both first and second passes have been executed.

Fig. 9
figure 9

First and second passes of the chamfer algorithm. The asterisk represents a real number. a Initialization. b Forward pass. c Backward pass

The chamfer algorithm based on sequential masks is relatively fast because it involves only two passes to generate the distance image. Some previous works have shown that the computational times of both parallel and sequential driven algorithms are comparable ([30, 31], and references therein). Speed of the traditional chamfer algorithm can, however, be further improved.

Traditional implementation of the chamfer algorithm requires every location of an image to be operated by the masks. Observing results from the first pass, as demonstrated by Fig. 9b, we see that the process leaves some pixels in the image unchanged. In particular, for a 7×7 image with one feature pixel at its center, more than 55% of the pixels retain their initial states after execution. In this work, we have developed a simple strategy to skip these unnecessary operations in the first pass.

For demonstration purposes, consider a one-feature image with M1 rows and M2 columns. Then our technique operates as follows: Firstly, position (row,column) of a feature pixel is determined. Secondly, the for loops in the first pass are explored and their initial indices are updated accordingly to contain values of the determined position. Thirdly, the forward mask is moved along row from column to M2. Fourthly, column is decremented by one and a condition to check its lower bound is evaluated. The mask is allowed to move in this fashion until it reaches the bottom-right corner pixel of the image. As Fig. 9b depicts, the final image in the first pass contains a trapezium-shaped geometrical structure of the real-valued distance values. This way, less important operations are ignored.

To count the algorithmic number of operations, we employed a simple strategy of embedding counters into the inner for loops of the algorithm. During program execution of the forward pass, the first counter iteratively gets updated to record the temporary value of the number of operations. In the backward pass, the second counter builds from the first one to accumulate the total algorithmic operations count. The algorithm can be tested on all types of binary images, but superior results may be achieved for larger images with many non-feature entries.

Algorithm 2 summarizes the technique to improve speed of the chamfering process. Figure 10 shows that the proposed chamfer algorithm executes fewer operations compared with those pursued by the classical chamfer algorithm. This speed improvement may benefit applications that demand real-time processing of input images.

Fig. 10
figure 10

Performances of the classical and proposed chamfer algorithms

5 Experiments

Several experiments were conducted to test performances of our methods. In the first experiment, we evaluated the speed of the modified chamfer algorithm using single-feature binary images of different resolutions, 300×300 to 6000×6000. The second experiment compared performances of our local weights and those proposed from previous studies: Euclidean DT [11, 3234], Butt et al. [29], and Verwer [35]. Therefore, masks of different sizes were applied to estimate chamfer balls of radii r=1. Next, three error metrics, namely SMAPE, MAE, and MSE, were used to compute the approximation errors. In the third experiment, the purpose was to compute distance fields from real images. To this end, we used cameras embedded in the surface mount technology machine of our laboratory to capture images of surface mount devices with small-outline packages. Then, the images were thresholded to create edge maps that DT operators could act upon (Fig. 11). Lastly, the images were operated by DTs to produce their corresponding distance and error maps. As in the first experiment, we used SMAPE, MAE, and MSE to evaluate accuracies of both designed and classical weights.

Fig. 11
figure 11

Real devices (first row) and their respective thresholded versions (second row). a SOP1. b SOP2. c SOP3

6 Results and discussions

Figure 10 demonstrates that the proposed DT algorithm to estimate EDT is faster because it requires approximately 37.58% operations of the classical chamfer algorithm. This speed improvement is attributed to the reduced number of operations in the first-pass stage of the old chamfer algorithm. In future, it may be interesting to explore the second-pass stage for redundancies and unnecessary executions.

Results from Table 1 show that the new weights achieve lower SMAPE in all cases. One would expect this observation because weights from the classical methods were designed using MAE and MSE cost functions. Nevertheless, a robust cost function should produce optimal weights with higher degree of accuracies for all evaluation indices. As expected, the last column of Table 1 shows that our approach, which is adapted to SMAPE, produces MAE values slightly higher than those of Butt et al. These two methods are competitive and hence were considered further in the next experiments to evaluate a superior one.

Table 1 Errors generated by chamfer masks

Table 2 shows that the proposed real-valued weights generate lower values of SMAPE, MAE, and MSE compared with those of Butt et al. Furthermore, for the 3×3 and 5×5 masks, our integer-valued masks demonstrate superior performances. This evidence suggests a possible usefulness of our weights to practical computing devices. Also, the results emphasizes on the earlier assertion that SMAPE offers higher robustness capabilities. But the 7×7 mask embedded with the proposed integer-valued weights demonstrates relatively higher error values, and we think that the result may be attributed to the higher sensitivity of the larger chamfer masks to local weights: a marginal departure of the integer-valued weights from the optimal real-valued weights amplifies the errors. Additionally, visual results show that the present approach produces distance maps with lower errors (Fig. 12) and that are closer to the reference distance maps (Fig. 13).

Fig. 12
figure 12

Error maps of portion of SOP3 generated by a 7×7 chamfer mask. Mean absolute error (MAE) and mean squared error (MSE) are computed from the selected portion of the map. The reference error map has all entries zeros (100% black). a Butt et al. (total error = 0.0383). b Proposed (total error = 0.0173)

Fig. 13
figure 13

Distance maps generated by the 7×7 chamfer masks: first row, reference (Euclidean metric); and second row, proposed DT. a SOP1. b SOP2. c SOP3

Table 2 Errors generated by chamfer masks applied to real images

In [36], the authors proposed the RLog metric to optimize chamfer masks. This metric finds the relative logarithm between the estimated and the ideal disc. Both SMAPE, proposed in the current work, and RLog generate similar weights of the chamfer masks, but SMAPE offers an additional advantage of being robust against outliers and noise. When applied as a performance evaluation index, the averaging characteristic of SMAPE helps to suppress extraneous details. Therefore, derivations of the chamfer masks may remain accurate even under undesirable conditions of data.

Our derivations of chamfer masks have been presented for two-dimensional cases. Hence, the proposed masks can be applied on two-dimensional images to compute distance maps. Future studies may explore possibilities of extending our ideas to higher dimensional planes. Derivation of the 3×3 three-dimensional chamfer masks, for instance, require extending Fig. 2 to a sphere containing a chamfer polygon with sides representing planes. This modification may be useful in various vision-related tasks, including those based on the analysis and interpretation of 3D medical images.

7 Conclusion

This work has proposed the cost function, SMAPE, that helps to derive optimization problems for designing chamfer masks. Results show that the function generates more accurate local weights—which give lower errors even when tested under MAE and MSE criteria—compared with those proposed from previous researches. Also, the present study has given formulations to show how ranges of some masks’ weights can be selected, and this selection procedure is important because it restricts the maximum error of minor lobes from exploding beyond the defined limits.

Additionally, an automatic algorithm has been proposed to compute integer-valued chamfer masks from their corresponding real-valued counterparts. The algorithm produces masks with simple integers that depict lower errors. The reason for mapping real-valued masks into integers is to allow DTs optimize computational resources and accelerate speed.

Furthermore, we have proposed a technique to boost speed of the classical chamfer algorithm. In particular, the technique exploits unimportant cells in the image covered by the moving forward mask and skips unnecessary operations. Consequently, the evolving system halts prematurely with results similar to those achieved by the old approach.

Finally, the designed local weights and the modified chamfer algorithm were applied on real images to generate distance maps. Empirical results show that our weights produce lower visible errors that reflect smaller values of SMAPE, MAE, and MSE.

8 Appendix 1: Existence of maximum in SMAPE

Given that the SMAPE error curve, Z(θ) with θ[0,45], is smooth and differentiable to the second order. We want to prove that Z contains a maximum, which occurs when the function qualifies the second derivative test, Zθθ≤0. Computing first and second derivatives of Z gives

$$ Z_{\theta}=\frac{2(U\cos\theta-V\sin\theta)}{(U\sin\theta+V\cos\theta+1)^{2}} $$
(35)

and

$$ {}{\begin{aligned} Z_{\theta\theta}=-\left(2\frac{U\sin\theta+V\cos\theta}{(U\sin\theta+V\cos\theta+1)^{2}}+4\frac{(U\cos\theta-V\sin\theta)^{2}}{(U\sin\theta+V\cos\theta+1)^{3}}\right)\le 0, \end{aligned}} $$
(36)

where U sinθ+V cosθ≠−1. From Zθθ in (36), Z possesses the maximum.

9 Appendix 2: Intercepts on the SMAPE curve

Locations on the chamfer polygon with radius f(θ)=r and touching the reference disc of radius r have Z=0. Substituting the condition in the SMAPE formula, we find that the curve Z(θ) crosses the θ-axis when

$$ \theta=\arccos\left(\frac{V\pm U\sqrt{U^{2}+V^{2}-1}}{U^{2}+V^{2}}\right). $$
(37)

10 Appendix 3: Optimum chamfer weights

When designing coefficients in the chamfer kernels, the optimality conditions are −Z(0)=Z(θm), or

$$ -\frac{V-1}{V+1}=\frac{\sqrt{U^{2}+V^{2}} - 1}{\sqrt{U^{2}+V^{2}} + 1}, $$
(38)

and

$$ U=(\beta+\gamma)V, $$
(39)

where β and γ depends on the size of the mask (Table 3). Substituting the value of U in (39) into (38), we get

$$ V=\frac{1}{\sqrt[4]{(\beta+\gamma)^{2}+1}}. $$
(40)
Table 3 Values of β and γ for different kernel sizes

The general Eqs. (39) and (40) can be used to compute optimal values for any size of the chamfer masks. Entries of Table 1 can be extended using the Farey sequences [29, 37], which define corner points of the chamfer polygon.

Availability of data and materials

Data and implementation codes for all experiments have been shared in the MATLAB CentralFootnote 1.

Notes

  1. http://www.mathworks.com/matlabcentral/fileexchange/59162-optimization-of-chamfer-masks

Abbreviations

DT:

Distance transform

EDT:

Euclidean distance transform

MAE:

Mean absolute error

MSE:

Mean squared error

SMAPE:

Symmetric mean absolute percentage error

References

  1. PK Saha, G Borgefors, GS di Baja, A survey on skeletonization algorithms and their applications. Pattern Recogn. Lett.76:, 3–12 (2016).

    Article  Google Scholar 

  2. P Maragos, Differential morphology and image processing. IEEE Trans. Image Process.5(6), 922–937 (1996).

    Article  Google Scholar 

  3. GJ Grevera, in Deformable Models. Distance transform algorithms and their implementation and evaluation (SpringerNew York, 2007), pp. 33–60.

    Chapter  Google Scholar 

  4. W Liu, H Jiang, X Bai, G Tan, C Wang, W Liu, K Cai, Distance transform-based skeleton extraction and its applications in sensor networks. Parallel Distrib. Syst. IEEE Trans.24(9), 1763–1772 (2013).

    Article  Google Scholar 

  5. D Xu, H Li, Y Zhang, in Research in Computational Molecular Biology. Fast and accurate calculation of protein depth by Euclidean distance transform (SpringerNew York, 2013), pp. 304–316.

    Chapter  Google Scholar 

  6. Y Mishchenko, A fast algorithm for computation of discrete Euclidean distance transform in three or more dimensions on vector processing architectures. SIViP. 9:, 19–27 (2015).

    Article  Google Scholar 

  7. D Salvi, K Zheng, Y Zhou, S Wang, in Applications of Computer Vision (WACV), 2015 IEEE Winter Conference on. Distance transform based active contour approach for document image rectification (IEEENew York, 2015), pp. 757–764.

    Chapter  Google Scholar 

  8. JC Elizondo-Leal, EF Parra-González, JG Ramírez-Torres, The exact Euclidean distance transform: a new algorithm for universal path planning. Int. J. Adv. Robot. Syst.10:, 266–275 (2013).

    Article  Google Scholar 

  9. E Linnér, R Strand, in Discrete Geometry for Computer Imagery. Anti-aliased Euclidean distance transform on 3D sampling lattices (SpringerNew York, 2014), pp. 88–98.

    Google Scholar 

  10. KC Ciesielski, X Chen, JK Udupa, GJ Grevera, Linear time algorithms for exact distance transform. J. Math. Imaging Vis.39(3), 193–209 (2011).

    Article  MathSciNet  Google Scholar 

  11. CR Maurer, R Qi, V Raghavan, A linear time algorithm for computing exact Euclidean distance transforms of binary images in arbitrary dimensions. IEEE Trans. Pattern. Anal. Mach. Intell.25(2), 265–270 (2003).

    Article  Google Scholar 

  12. G Borgefors, Distance transformations in arbitrary dimensions. Comput. Vis. Graph. Image Proc.27(3), 321–345 (1984).

    Article  Google Scholar 

  13. R Strand, N Normand, Distance transform computation for digital distance functions. Theor. Comput. Sci.448:, 80–93 (2012).

    Article  MathSciNet  Google Scholar 

  14. R Strand, B Nagy, C Fouard, G Borgefors, Generating distance maps with neighbourhood sequences. Lect. Notes Comput. Sci. 4245:, 295 (2006).

    Article  Google Scholar 

  15. B Nagy, R Strand, N Normand, in International Symposium on Mathematical Morphology and Its Applications to Signal and Image Processing. A weight sequence distance function (SpringerNew York, 2013), pp. 292–301.

    Chapter  Google Scholar 

  16. J Dong, C Sun, W Yang, in Intelligence Science and Big Data Engineering. An improved method for oriented chamfer matching (SpringerNew York, 2013), pp. 875–879.

    Chapter  Google Scholar 

  17. D Tzionas, J Gall, in Pattern Recognition. A comparison of directional distances for hand pose estimation (SpringerNew York, 2013), pp. 131–141.

    Chapter  Google Scholar 

  18. P Kaliamoorthi, R Kakarala, Directional chamfer matching in 2.5 dimensions. Signal Process. Lett. IEEE. 20(12), 1151–1154 (2013).

    Article  Google Scholar 

  19. DT Nguyen, in Computer Vision and Pattern Recognition (CVPR), 2014 IEEE Conference on. A novel chamfer template matching method using variational mean field (IEEENew York, 2014), pp. 2425–2432.

    Chapter  Google Scholar 

  20. DW Paglieroni, Distance transforms: Properties and machine vision applications. CVGIP: Graph. Model. Image Process.54:, 56–74 (1992).

    Google Scholar 

  21. L Dantanarayana, R Ranasinghe, G Dissanayake, in 2013 IEEE/RSJ International Conference on Intelligent Robots and Systems. C-LOG: A Chamfer Distance based method for localisation in occupancy grid-maps (IEEENew York, 2013), pp. 376–381.

    Chapter  Google Scholar 

  22. T Ma, X Yang, LJ Latecki, in Computer Vision–ECCV 2010. Boosting chamfer matching by learning chamfer distance normalization (SpringerNew York, 2010), pp. 450–463.

    Chapter  Google Scholar 

  23. E Thiel, A Montanvert, in Visual Form. Shape splitting from medial lines using the 3–4 chamfer distance (SpringerNew York, 1992), pp. 537–546.

    Chapter  Google Scholar 

  24. MP Tran, 3D Contour Closing: A local operator based on Chamfer distance transformation (2013). https://hal.archives-ouvertes.fr/hal-00802068/file/cclose_tran.pdf.

  25. MK Bhuyan, VV Ramaraju, Y Iwahori, Hand gesture recognition and animation for local hand motions. Int. J. Mach. Learn. Cybern.5(4), 607–623 (2014).

    Article  Google Scholar 

  26. Z Wang, AC Bovik, Mean squared error: love it or leave it? A new look at signal fidelity measures. IEEE Signal Proc. Mag.26:, 98–117 (2009).

    Article  Google Scholar 

  27. S Kim, H Kim, A new metric of absolute percentage error for intermittent demand forecasts. Int. J. Forecast.32(3), 669–679 (2016).

    Article  Google Scholar 

  28. JS Armstrong, LR Forecasting, From crystal ball to computer (Wiley, New York, 1985).

    Google Scholar 

  29. MA Butt, P Maragos, Optimum design of chamfer distance transforms. Image Proc. IEEE Trans.7(10), 1477–1484 (1998).

    Article  Google Scholar 

  30. OK Kwon, JW Suh, Improved 3 × 3 sequential Euclidean distance transform. IEEJ Trans. Electr. Electron. Eng.8(3), 305–307 (2013).

    Article  Google Scholar 

  31. Y Dou, M Ye, P Xu, Pei L, Z Liu, Object detection based on two level fast matching. International Journal of Multimedia and Ubiquitous Engineering. 10(12), 381–394 (2015).

    Article  Google Scholar 

  32. O Cuisenaire, B Macq, Fast Euclidean distance transformation by propagation using multiple neighborhoods. Comp. Vision Image Underst.76(2), 163–172 (1999).

    Article  Google Scholar 

  33. T Saito, JI Toriwaki, New algorithms for euclidean distance transformation of an n-dimensional digitized picture with applications. Pattern Recog.27(11), 1551–1565 (1994).

    Article  Google Scholar 

  34. FY Shih, YT Wu, Fast Euclidean distance transformation in two scans using a 3 × 3 neighborhood. Comp. Vision Image Underst.93(2), 195–205 (2004).

    Article  Google Scholar 

  35. BJ Verwer, Local distances for distance transformations in two and three dimensions. Pattern Recogn. Lett.12(11), 671–682 (1991).

    Article  Google Scholar 

  36. BJ Maiseli, L Bai, X Yang, Y Gu, H Gao, Robust cost function for optimizing chamfer masks. Vis. Comput., 1–16 (2017).

  37. J Hulin, É Thiel, in International Workshop on Combinatorial Image Analysis. Farey sequences and the planar Euclidean medial axis test mask (SpringerNew York, 2009), pp. 82–95.

    Chapter  Google Scholar 

Download references

Acknowledgements

The author of the current manuscript would like to sincerely thank Prof. Huijun Gao and Prof. Yanfeng Gu from the Harbin Institute of Technology, P.R. China, for their guidance and support on this research. The raw images in Fig. 11 (first row) were adapted from the research laboratory under Prof. Huijun Gao.

Funding

This work was not funded by any organization.

Author information

Authors and Affiliations

Authors

Contributions

Authors’ contributions

The sole author of this manuscript undertook all the tasks: doing the experiments and writing and submitting the manuscript. The author read and approved the final manuscript.;

Authors’ information

Baraka Maiseli earned his Doctoral degree in 2015 from the Harbin Institute of Technology (HIT), PR China, where he was also awarded the honorary certificate as the best international scholar of the year. Currently, Maiseli pursues postdoctoral studies at HIT. He has published several articles in referred Journals, and is a verified peer reviewer for various international journals: IEEE Transactions on Industrial Electronics, Neurocomputing, IET Biometrics, Signal Processing, and International Journal of Remote Sensing, among others. His research interests are in machine learning, computer vision, image and video processing, artificial intelligence, and embedded electronics. Maiseli works at the University of Dar es Salaam (UDSM), Department of Electronics and Telecommunication Engineering, as a lecturer. With more than 10 years of teaching experience at UDSM, Maiseli has been supervising both undergraduate and postgraduate students in their projects, researches, and practical trainings.

Corresponding author

Correspondence to Baraka Jacob Maiseli.

Ethics declarations

Competing interests

The authors declare that they have no competing interests.

Additional information

Publisher’s Note

Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

Rights and permissions

Open Access This article is distributed under the terms of the Creative Commons Attribution 4.0 International License (http://creativecommons.org/licenses/by/4.0/), which permits unrestricted use, distribution, and reproduction in any medium, provided you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons license, and indicate if changes were made.

Reprints and permissions

About this article

Check for updates. Verify currency and authenticity via CrossMark

Cite this article

Maiseli, B.J. Optimum design of chamfer masks using symmetric mean absolute percentage error. J Image Video Proc. 2019, 74 (2019). https://doi.org/10.1186/s13640-019-0475-y

Download citation

  • Received:

  • Accepted:

  • Published:

  • DOI: https://doi.org/10.1186/s13640-019-0475-y

Keywords