1 /*====================================================================*
2  -  Copyright (C) 2001 Leptonica.  All rights reserved.
3  -
4  -  Redistribution and use in source and binary forms, with or without
5  -  modification, are permitted provided that the following conditions
6  -  are met:
7  -  1. Redistributions of source code must retain the above copyright
8  -     notice, this list of conditions and the following disclaimer.
9  -  2. Redistributions in binary form must reproduce the above
10  -     copyright notice, this list of conditions and the following
11  -     disclaimer in the documentation and/or other materials
12  -     provided with the distribution.
13  -
14  -  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15  -  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16  -  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17  -  A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ANY
18  -  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  -  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  -  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  -  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  -  OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
23  -  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  -  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *====================================================================*/
26 
27 /*!
28  * \file ccthin.c
29  * <pre>
30  *
31  *     PIXA   *pixaThinConnected()
32  *     PIX    *pixThinConnected()
33  *     PIX    *pixThinConnectedBySet()
34  *     SELA   *selaMakeThinSets()
35  * </pre>
36  */
37 
38 #include "allheaders.h"
39 
40     /* ------------------------------------------------------------
41      * The sels used here (and their rotated counterparts) are the
42      * useful 3x3 Sels for thinning.   They are defined in sel2.c,
43      * and the sets are constructed in selaMakeThinSets().
44      * The notation is based on "Connectivity-preserving morphological
45      * image transformations", a version of which can be found at
46      *           http://www.leptonica.com/papers/conn.pdf
47      * ------------------------------------------------------------ */
48 
49 /*----------------------------------------------------------------*
50  *                      CC-preserving thinning                    *
51  *----------------------------------------------------------------*/
52 /*!
53  * \brief   pixaThinConnected()
54  *
55  * \param[in]    pixas  of 1 bpp pix
56  * \param[in]    type L_THIN_FG, L_THIN_BG
57  * \param[in]    connectivity 4 or 8
58  * \param[in]    maxiters max number of iters allowed; use 0 to iterate
59  *                        until completion
60  * \return  pixds, or NULL on error
61  *
62  * <pre>
63  * Notes:
64  *      (1) See notes in pixThinConnected().
65  * </pre>
66  */
67 PIXA *
pixaThinConnected(PIXA * pixas,l_int32 type,l_int32 connectivity,l_int32 maxiters)68 pixaThinConnected(PIXA    *pixas,
69                   l_int32  type,
70                   l_int32  connectivity,
71                   l_int32  maxiters)
72 {
73 l_int32  i, n, d, same;
74 PIX     *pix1, *pix2;
75 PIXA    *pixad;
76 SELA    *sela;
77 
78     PROCNAME("pixaThinConnected");
79 
80     if (!pixas)
81         return (PIXA *)ERROR_PTR("pixas not defined", procName, NULL);
82     if (type != L_THIN_FG && type != L_THIN_BG)
83         return (PIXA *)ERROR_PTR("invalid fg/bg type", procName, NULL);
84     if (connectivity != 4 && connectivity != 8)
85         return (PIXA *)ERROR_PTR("connectivity not 4 or 8", procName, NULL);
86     if (maxiters == 0) maxiters = 10000;
87 
88     pixaVerifyDepth(pixas, &same, &d);
89     if (d != 1)
90         return (PIXA *)ERROR_PTR("pix are not all 1 bpp", procName, NULL);
91 
92     if (connectivity == 4)
93         sela = selaMakeThinSets(1, 0);
94     else  /* connectivity == 8 */
95         sela = selaMakeThinSets(5, 0);
96 
97     n = pixaGetCount(pixas);
98     pixad = pixaCreate(n);
99     for (i = 0; i < n; i++) {
100         pix1 = pixaGetPix(pixas, i, L_CLONE);
101         pix2 = pixThinConnectedBySet(pix1, type, sela, maxiters);
102         pixaAddPix(pixad, pix2, L_INSERT);
103         pixDestroy(&pix1);
104     }
105 
106     selaDestroy(&sela);
107     return pixad;
108 }
109 
110 
111 /*!
112  * \brief   pixThinConnected()
113  *
114  * \param[in]    pixs 1 bpp
115  * \param[in]    type L_THIN_FG, L_THIN_BG
116  * \param[in]    connectivity 4 or 8
117  * \param[in]    maxiters max number of iters allowed; use 0 to iterate
118  *                        until completion
119  * \return  pixd, or NULL on error
120  *
121  * <pre>
122  * Notes:
123  *      (1) See "Connectivity-preserving morphological image transformations,"
124  *          Dan S. Bloomberg, in SPIE Visual Communications and Image
125  *          Processing, Conference 1606, pp. 320-334, November 1991,
126  *          Boston, MA.   A web version is available at
127  *              http://www.leptonica.com/papers/conn.pdf
128  *      (2) This is a simple interface for two of the best iterative
129  *          morphological thinning algorithms, for 4-c.c and 8-c.c.
130  *          Each iteration uses a mixture of parallel operations
131  *          (using several different 3x3 Sels) and serial operations.
132  *          Specifically, each thinning iteration consists of
133  *          four sequential thinnings from each of four directions.
134  *          Each of these thinnings is a parallel composite
135  *          operation, where the union of a set of HMTs are set
136  *          subtracted from the input.  For 4-cc thinning, we
137  *          use 3 HMTs in parallel, and for 8-cc thinning we use 4 HMTs.
138  *      (3) A "good" thinning algorithm is one that generates a skeleton
139  *          that is near the medial axis and has neither pruned
140  *          real branches nor left extra dendritic branches.
141  *      (4) Duality between operations on fg and bg require switching
142  *          the connectivity.  To thin the foreground, which is the usual
143  *          situation, use type == L_THIN_FG.  Thickening the foreground
144  *          is equivalent to thinning the background (type == L_THIN_BG),
145  *          where the alternate connectivity gets preserved.
146  *          For example, to thicken the fg with 2 rounds of iterations
147  *          using 4-c.c., thin the bg using Sels that preserve 8-connectivity:
148  *             Pix *pix = pixThinConnected(pixs, L_THIN_BG, 8, 2);
149  *      (5) This makes and destroys the sela set each time. It's not a large
150  *          overhead, but if you are calling this thousands of times on
151  *          very small images, you can avoid the overhead; e.g.
152  *             Sela *sela = selaMakeThinSets(1, 0);  // for 4-c.c.
153  *             Pix *pix = pixThinConnectedBySet(pixs, L_THIN_FG, sela, 0);
154  *          using set 1 for 4-c.c. and set 5 for 8-c.c operations.
155  * </pre>
156  */
157 PIX *
pixThinConnected(PIX * pixs,l_int32 type,l_int32 connectivity,l_int32 maxiters)158 pixThinConnected(PIX     *pixs,
159                  l_int32  type,
160                  l_int32  connectivity,
161                  l_int32  maxiters)
162 {
163 PIX   *pixd;
164 SELA  *sela;
165 
166     PROCNAME("pixThinConnected");
167 
168     if (!pixs)
169         return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
170     if (pixGetDepth(pixs) != 1)
171         return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, NULL);
172     if (type != L_THIN_FG && type != L_THIN_BG)
173         return (PIX *)ERROR_PTR("invalid fg/bg type", procName, NULL);
174     if (connectivity != 4 && connectivity != 8)
175         return (PIX *)ERROR_PTR("connectivity not 4 or 8", procName, NULL);
176     if (maxiters == 0) maxiters = 10000;
177 
178     if (connectivity == 4)
179         sela = selaMakeThinSets(1, 0);
180     else  /* connectivity == 8 */
181         sela = selaMakeThinSets(5, 0);
182 
183     pixd = pixThinConnectedBySet(pixs, type, sela, maxiters);
184 
185     selaDestroy(&sela);
186     return pixd;
187 }
188 
189 
190 /*!
191  * \brief   pixThinConnectedBySet()
192  *
193  * \param[in]    pixs 1 bpp
194  * \param[in]    type L_THIN_FG, L_THIN_BG
195  * \param[in]    sela of Sels for parallel composite HMTs
196  * \param[in]    maxiters max number of iters allowed; use 0 to iterate
197  *                        until completion
198  * \return  pixd, or NULL on error
199  *
200  * <pre>
201  * Notes:
202  *      (1) See notes in pixThinConnected().
203  *      (2) This takes a sela representing one of 11 sets of HMT Sels.
204  *          The HMTs from this set are run in parallel and the result
205  *          is OR'd before being subtracted from the source.  For each
206  *          iteration, this "parallel" thin is performed four times
207  *          sequentially, for sels rotated by 90 degrees in all four
208  *          directions.
209  *      (3) The "parallel" and "sequential" nomenclature is standard
210  *          in digital filtering.  Here, "parallel" operations work on the
211  *          same source (pixd), and accumulate the results in a temp
212  *          image before actually applying them to the source (in this
213  *          case, using an in-place subtraction).  "Sequential" operations
214  *          operate directly on the source (pixd) to produce the result
215  *          (in this case, with four sequential thinning operations, one
216  *          from each of four directions).
217  * </pre>
218  */
219 PIX *
pixThinConnectedBySet(PIX * pixs,l_int32 type,SELA * sela,l_int32 maxiters)220 pixThinConnectedBySet(PIX     *pixs,
221                       l_int32  type,
222                       SELA    *sela,
223                       l_int32  maxiters)
224 {
225 l_int32  i, j, r, nsels, same;
226 PIXA    *pixahmt;
227 PIX    **pixhmt;  /* array owned by pixahmt; do not destroy! */
228 PIX     *pix1, *pix2, *pixd;
229 SEL     *sel, *selr;
230 
231     PROCNAME("pixThinConnectedBySet");
232 
233     if (!pixs)
234         return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
235     if (pixGetDepth(pixs) != 1)
236         return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, NULL);
237     if (type != L_THIN_FG && type != L_THIN_BG)
238         return (PIX *)ERROR_PTR("invalid fg/bg type", procName, NULL);
239     if (!sela)
240         return (PIX *)ERROR_PTR("sela not defined", procName, NULL);
241     if (maxiters == 0) maxiters = 10000;
242 
243         /* Set up array of temp pix to hold hmts */
244     nsels = selaGetCount(sela);
245     pixahmt = pixaCreate(nsels);
246     for (i = 0; i < nsels; i++) {
247         pix1 = pixCreateTemplate(pixs);
248         pixaAddPix(pixahmt, pix1, L_INSERT);
249     }
250     pixhmt = pixaGetPixArray(pixahmt);
251     if (!pixhmt) {
252         pixaDestroy(&pixahmt);
253         return (PIX *)ERROR_PTR("pixhmt array not made", procName, NULL);
254     }
255 
256         /* Set up initial image for fg thinning */
257     if (type == L_THIN_FG)
258         pixd = pixCopy(NULL, pixs);
259     else  /* bg thinning */
260         pixd = pixInvert(NULL, pixs);
261 
262         /* Thin the fg, with up to maxiters iterations */
263     for (i = 0; i < maxiters; i++) {
264         pix1 = pixCopy(NULL, pixd);  /* test for completion */
265         for (r = 0; r < 4; r++) {  /* over 90 degree rotations of Sels */
266             for (j = 0; j < nsels; j++) {  /* over individual sels in sela */
267                 sel = selaGetSel(sela, j);  /* not a copy */
268                 selr = selRotateOrth(sel, r);
269                 pixHMT(pixhmt[j], pixd, selr);
270                 selDestroy(&selr);
271                 if (j > 0)
272                     pixOr(pixhmt[0], pixhmt[0], pixhmt[j]);  /* accum result */
273             }
274             pixSubtract(pixd, pixd, pixhmt[0]);  /* remove result */
275         }
276         pixEqual(pixd, pix1, &same);
277         pixDestroy(&pix1);
278         if (same) {
279 /*            L_INFO("%d iterations to completion\n", procName, i); */
280             break;
281         }
282     }
283 
284         /* This is a bit tricky. If we're thickening the foreground, then
285          * we get a fg border of thickness equal to the number of
286          * iterations.  This border is connected to all components that
287          * were initially touching the border, but as it grows, it does
288          * not touch other growing components -- it leaves a 1 pixel wide
289          * background between it and the growing components, and that
290          * thin background prevents the components from growing further.
291          * This border can be entirely removed as follows:
292          * (1) Subtract the original (unthickened) image pixs from the
293          *     thickened image. This removes the pixels that were originally
294          *     touching the border.
295          * (2) Get all remaining pixels that are connected to the border.
296          * (3) Remove those pixels from the thickened image.  */
297     if (type == L_THIN_BG) {
298         pixInvert(pixd, pixd);  /* finish with duality */
299         pix1 = pixSubtract(NULL, pixd, pixs);
300         pix2 = pixExtractBorderConnComps(pix1, 4);
301         pixSubtract(pixd, pixd, pix2);
302         pixDestroy(&pix1);
303         pixDestroy(&pix2);
304     }
305 
306     pixaDestroy(&pixahmt);
307     return pixd;
308 }
309 
310 
311 /*!
312  * \brief   selaMakeThinSets()
313  *
314  * \param[in]    index  into specific sets
315  * \param[in]    debug  1 to output display of sela
316  * \return  sela, or NULL on error
317  *
318  * <pre>
319  * Notes:
320  *      (1) These are specific sets of HMTs to be used in parallel for
321  *          for thinning from each of four directions.
322  *      (2) The sets are indexed as follows:
323  *          For thinning (e.g., run to completion):
324  *              index = 1     sel_4_1, sel_4_2, sel_4_3
325  *              index = 2     sel_4_1, sel_4_5, sel_4_6
326  *              index = 3     sel_4_1, sel_4_7, sel_4_7_rot
327  *              index = 4     sel_48_1, sel_48_1_rot, sel_48_2
328  *              index = 5     sel_8_2, sel_8_3, sel_8_5, sel_8_6
329  *              index = 6     sel_8_2, sel_8_3, sel_48_2
330  *              index = 7     sel_8_1, sel_8_5, sel_8_6
331  *              index = 8     sel_8_2, sel_8_3, sel_8_8, sel_8_9
332  *              index = 9     sel_8_5, sel_8_6, sel_8_7, sel_8_7_rot
333  *          For thickening (e.g., just a few iterations):
334  *              index = 10    sel_4_2, sel_4_3
335  *              index = 11    sel_8_4
336  *      (3) For a very smooth skeleton, use set 1 for 4 connected and
337  *          set 5 for 8 connected thins.
338  * </pre>
339  */
340 SELA *
selaMakeThinSets(l_int32 index,l_int32 debug)341 selaMakeThinSets(l_int32  index,
342                  l_int32  debug)
343 {
344 SEL   *sel;
345 SELA  *sela1, *sela2, *sela3;
346 
347     PROCNAME("selaMakeThinSets");
348 
349     if (index < 1 || index > 11)
350         return (SELA *)ERROR_PTR("invalid index", procName, NULL);
351 
352     sela2 = selaCreate(4);
353     switch(index)
354     {
355     case 1:
356         sela1 = sela4ccThin(NULL);
357         selaFindSelByName(sela1, "sel_4_1", NULL, &sel);
358         selaAddSel(sela2, sel, NULL, L_COPY);
359         selaFindSelByName(sela1, "sel_4_2", NULL, &sel);
360         selaAddSel(sela2, sel, NULL, L_COPY);
361         selaFindSelByName(sela1, "sel_4_3", NULL, &sel);
362         selaAddSel(sela2, sel, NULL, L_COPY);
363         break;
364     case 2:
365         sela1 = sela4ccThin(NULL);
366         selaFindSelByName(sela1, "sel_4_1", NULL, &sel);
367         selaAddSel(sela2, sel, NULL, L_COPY);
368         selaFindSelByName(sela1, "sel_4_5", NULL, &sel);
369         selaAddSel(sela2, sel, NULL, L_COPY);
370         selaFindSelByName(sela1, "sel_4_6", NULL, &sel);
371         selaAddSel(sela2, sel, NULL, L_COPY);
372         break;
373     case 3:
374         sela1 = sela4ccThin(NULL);
375         selaFindSelByName(sela1, "sel_4_1", NULL, &sel);
376         selaAddSel(sela2, sel, NULL, L_COPY);
377         selaFindSelByName(sela1, "sel_4_7", NULL, &sel);
378         selaAddSel(sela2, sel, NULL, L_COPY);
379         sel = selRotateOrth(sel, 1);
380         selaAddSel(sela2, sel, "sel_4_7_rot", L_INSERT);
381         break;
382     case 4:
383         sela1 = sela4and8ccThin(NULL);
384         selaFindSelByName(sela1, "sel_48_1", NULL, &sel);
385         selaAddSel(sela2, sel, NULL, L_COPY);
386         sel = selRotateOrth(sel, 1);
387         selaAddSel(sela2, sel, "sel_48_1_rot", L_INSERT);
388         selaFindSelByName(sela1, "sel_48_2", NULL, &sel);
389         selaAddSel(sela2, sel, NULL, L_COPY);
390         break;
391     case 5:
392         sela1 = sela8ccThin(NULL);
393         selaFindSelByName(sela1, "sel_8_2", NULL, &sel);
394         selaAddSel(sela2, sel, NULL, L_COPY);
395         selaFindSelByName(sela1, "sel_8_3", NULL, &sel);
396         selaAddSel(sela2, sel, NULL, L_COPY);
397         selaFindSelByName(sela1, "sel_8_5", NULL, &sel);
398         selaAddSel(sela2, sel, NULL, L_COPY);
399         selaFindSelByName(sela1, "sel_8_6", NULL, &sel);
400         selaAddSel(sela2, sel, NULL, L_COPY);
401         break;
402     case 6:
403         sela1 = sela8ccThin(NULL);
404         sela3 = sela4and8ccThin(NULL);
405         selaFindSelByName(sela1, "sel_8_2", NULL, &sel);
406         selaAddSel(sela2, sel, NULL, L_COPY);
407         selaFindSelByName(sela1, "sel_8_3", NULL, &sel);
408         selaAddSel(sela2, sel, NULL, L_COPY);
409         selaFindSelByName(sela3, "sel_48_2", NULL, &sel);
410         selaAddSel(sela2, sel, NULL, L_COPY);
411         selaDestroy(&sela3);
412         break;
413     case 7:
414         sela1 = sela8ccThin(NULL);
415         selaFindSelByName(sela1, "sel_8_1", NULL, &sel);
416         selaAddSel(sela2, sel, NULL, L_COPY);
417         selaFindSelByName(sela1, "sel_8_5", NULL, &sel);
418         selaAddSel(sela2, sel, NULL, L_COPY);
419         selaFindSelByName(sela1, "sel_8_6", NULL, &sel);
420         selaAddSel(sela2, sel, NULL, L_COPY);
421         break;
422     case 8:
423         sela1 = sela8ccThin(NULL);
424         selaFindSelByName(sela1, "sel_8_2", NULL, &sel);
425         selaAddSel(sela2, sel, NULL, L_COPY);
426         selaFindSelByName(sela1, "sel_8_3", NULL, &sel);
427         selaAddSel(sela2, sel, NULL, L_COPY);
428         selaFindSelByName(sela1, "sel_8_8", NULL, &sel);
429         selaAddSel(sela2, sel, NULL, L_COPY);
430         selaFindSelByName(sela1, "sel_8_9", NULL, &sel);
431         selaAddSel(sela2, sel, NULL, L_COPY);
432         break;
433     case 9:
434         sela1 = sela8ccThin(NULL);
435         selaFindSelByName(sela1, "sel_8_5", NULL, &sel);
436         selaAddSel(sela2, sel, NULL, L_COPY);
437         selaFindSelByName(sela1, "sel_8_6", NULL, &sel);
438         selaAddSel(sela2, sel, NULL, L_COPY);
439         selaFindSelByName(sela1, "sel_8_7", NULL, &sel);
440         selaAddSel(sela2, sel, NULL, L_COPY);
441         sel = selRotateOrth(sel, 1);
442         selaAddSel(sela2, sel, "sel_8_7_rot", L_INSERT);
443         break;
444     case 10:  /* thicken for this one; use just a few iterations */
445         sela1 = sela4ccThin(NULL);
446         selaFindSelByName(sela1, "sel_4_2", NULL, &sel);
447         selaAddSel(sela2, sel, NULL, L_COPY);
448         selaFindSelByName(sela1, "sel_4_3", NULL, &sel);
449         selaAddSel(sela2, sel, NULL, L_COPY);
450         break;
451     case 11:  /* thicken for this one; use just a few iterations */
452         sela1 = sela8ccThin(NULL);
453         selaFindSelByName(sela1, "sel_8_4", NULL, &sel);
454         selaAddSel(sela2, sel, NULL, L_COPY);
455         break;
456     }
457 
458         /* Optionally display the sel set */
459     if (debug) {
460         PIX  *pix1;
461         char  buf[32];
462         lept_mkdir("/lept/sels");
463         pix1 = selaDisplayInPix(sela2, 35, 3, 15, 4);
464         snprintf(buf, sizeof(buf), "/tmp/lept/sels/set%d.png", index);
465         pixWrite(buf, pix1, IFF_PNG);
466         pixDisplay(pix1, 100, 100);
467         pixDestroy(&pix1);
468     }
469 
470     selaDestroy(&sela1);
471     return sela2;
472 }
473 
474