summaryrefslogtreecommitdiff
blob: 0f01ea210c3aca93f4e52c432486991e2d334b47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
/*====================================================================*
 -  Copyright (C) 2001 Leptonica.  All rights reserved.
 -
 -  Redistribution and use in source and binary forms, with or without
 -  modification, are permitted provided that the following conditions
 -  are met:
 -  1. Redistributions of source code must retain the above copyright
 -     notice, this list of conditions and the following disclaimer.
 -  2. Redistributions in binary form must reproduce the above
 -     copyright notice, this list of conditions and the following
 -     disclaimer in the documentation and/or other materials
 -     provided with the distribution.
 -
 -  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 -  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 -  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 -  A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ANY
 -  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 -  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 -  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 -  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 -  OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 -  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 -  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *====================================================================*/

/*!
 * \file morph.c
 * <pre>
 *
 *     Generic binary morphological ops implemented with rasterop
 *         PIX     *pixDilate()
 *         PIX     *pixErode()
 *         PIX     *pixHMT()
 *         PIX     *pixOpen()
 *         PIX     *pixClose()
 *         PIX     *pixCloseSafe()
 *         PIX     *pixOpenGeneralized()
 *         PIX     *pixCloseGeneralized()
 *
 *     Binary morphological (raster) ops with brick Sels
 *         PIX     *pixDilateBrick()
 *         PIX     *pixErodeBrick()
 *         PIX     *pixOpenBrick()
 *         PIX     *pixCloseBrick()
 *         PIX     *pixCloseSafeBrick()
 *
 *     Binary composed morphological (raster) ops with brick Sels
 *         l_int32  selectComposableSels()
 *         l_int32  selectComposableSizes()
 *         PIX     *pixDilateCompBrick()
 *         PIX     *pixErodeCompBrick()
 *         PIX     *pixOpenCompBrick()
 *         PIX     *pixCloseCompBrick()
 *         PIX     *pixCloseSafeCompBrick()
 *
 *     Functions associated with boundary conditions
 *         void     resetMorphBoundaryCondition()
 *         l_int32  getMorphBorderPixelColor()
 *
 *     Static helpers for arg processing
 *         static PIX     *processMorphArgs1()
 *         static PIX     *processMorphArgs2()
 *
 *  You are provided with many simple ways to do binary morphology.
 *  In particular, if you are using brick Sels, there are six
 *  convenient methods, all specially tailored for separable operations
 *  on brick Sels.  A "brick" Sel is a Sel that is a rectangle
 *  of solid SEL_HITs with the origin at or near the center.
 *  Note that a brick Sel can have one dimension of size 1.
 *  This is very common.  All the brick Sel operations are
 *  separable, meaning the operation is done first in the horizontal
 *  direction and then in the vertical direction.  If one of the
 *  dimensions is 1, this is a special case where the operation is
 *  only performed in the other direction.
 *
 *  These six brick Sel methods are enumerated as follows:
 *
 *  (1) Brick Sels: pix*Brick(), where * = {Dilate, Erode, Open, Close}.
 *      These are separable rasterop implementations.  The Sels are
 *      automatically generated, used, and destroyed at the end.
 *      You can get the result as a new Pix, in-place back into the src Pix,
 *      or written to another existing Pix.
 *
 *  (2) Brick Sels: pix*CompBrick(), where * = {Dilate, Erode, Open, Close}.
 *      These are separable, 2-way composite, rasterop implementations.
 *      The Sels are automatically generated, used, and destroyed at the end.
 *      You can get the result as a new Pix, in-place back into the src Pix,
 *      or written to another existing Pix.  For large Sels, these are
 *      considerably faster than the corresponding pix*Brick() functions.
 *      N.B.:  The size of the Sels that are actually used are typically
 *      close to, but not exactly equal to, the size input to the function.
 *
 *  (3) Brick Sels: pix*BrickDwa(), where * = {Dilate, Erode, Open, Close}.
 *      These are separable dwa (destination word accumulation)
 *      implementations.  They use auto-gen'd dwa code.  You can get
 *      the result as a new Pix, in-place back into the src Pix,
 *      or written to another existing Pix.  This is typically
 *      about 3x faster than the analogous rasterop pix*Brick()
 *      function, but it has the limitation that the Sel size must
 *      be less than 63.  This is pre-set to work on a number
 *      of pre-generated Sels.  If you want to use other Sels, the
 *      code can be auto-gen'd for them; see the instructions in morphdwa.c.
 *
 *  (4) Same as (1), but you run it through pixMorphSequence(), with
 *      the sequence string either compiled in or generated using snprintf.
 *      All intermediate images and Sels are created, used and destroyed.
 *      You always get the result as a new Pix.  For example, you can
 *      specify a separable 11 x 17 brick opening as "o11.17",
 *      or you can specify the horizontal and vertical operations
 *      explicitly as "o11.1 + o1.11".  See morphseq.c for details.
 *
 *  (5) Same as (2), but you run it through pixMorphCompSequence(), with
 *      the sequence string either compiled in or generated using snprintf.
 *      All intermediate images and Sels are created, used and destroyed.
 *      You always get the result as a new Pix.  See morphseq.c for details.
 *
 *  (6) Same as (3), but you run it through pixMorphSequenceDwa(), with
 *      the sequence string either compiled in or generated using snprintf.
 *      All intermediate images and Sels are created, used and destroyed.
 *      You always get the result as a new Pix.  See morphseq.c for details.
 *
 *  If you are using Sels that are not bricks, you have two choices:
 *      (a) simplest: use the basic rasterop implementations (pixDilate(), ...)
 *      (b) fastest: generate the destination word accumumlation (dwa)
 *          code for your Sels and compile it with the library.
 *
 *      For an example, see flipdetect.c, which gives implementations
 *      using hit-miss Sels with both the rasterop and dwa versions.
 *      For the latter, the dwa code resides in fliphmtgen.c, and it
 *      was generated by prog/flipselgen.c.  Both the rasterop and dwa
 *      implementations are tested by prog/fliptest.c.
 *
 *  A global constant MORPH_BC is used to set the boundary conditions
 *  for rasterop-based binary morphology.  MORPH_BC, in morph.c,
 *  is set by default to ASYMMETRIC_MORPH_BC for a non-symmetric
 *  convention for boundary pixels in dilation and erosion:
 *      All pixels outside the image are assumed to be OFF
 *      for both dilation and erosion.
 *  To use a symmetric definition, see comments in pixErode()
 *  and reset MORPH_BC to SYMMETRIC_MORPH_BC, using
 *  resetMorphBoundaryCondition().
 *
 *  Boundary artifacts are possible in closing when the non-symmetric
 *  boundary conditions are used, because foreground pixels very close
 *  to the edge can be removed.  This can be avoided by using either
 *  the symmetric boundary conditions or the function pixCloseSafe(),
 *  which adds a border before the operation and removes it afterwards.
 *
 *  The hit-miss transform (HMT) is the bit-and of 2 erosions:
 *     (erosion of the src by the hits)  &  (erosion of the bit-inverted
 *                                           src by the misses)
 *
 *  The 'generalized opening' is an HMT followed by a dilation that uses
 *  only the hits of the hit-miss Sel.
 *  The 'generalized closing' is a dilation (again, with the hits
 *  of a hit-miss Sel), followed by the HMT.
 *  Both of these 'generalized' functions are idempotent.
 *
 *  These functions are extensively tested in prog/binmorph1_reg.c,
 *  prog/binmorph2_reg.c, and prog/binmorph3_reg.c.
 * </pre>
 */

#ifdef HAVE_CONFIG_H
#include <config_auto.h>
#endif  /* HAVE_CONFIG_H */

#include <math.h>
#include "allheaders.h"

    /* Global constant; initialized here; must be declared extern
     * in other files to access it directly.  However, in most
     * cases that is not necessary, because it can be reset
     * using resetMorphBoundaryCondition().  */
LEPT_DLL l_int32  MORPH_BC = ASYMMETRIC_MORPH_BC;

    /* We accept this cost in extra rasterops for decomposing exactly. */
static const l_int32  ACCEPTABLE_COST = 5;

    /* Static helpers for arg processing */
static PIX * processMorphArgs1(PIX *pixd, PIX *pixs, SEL *sel, PIX **ppixt);
static PIX * processMorphArgs2(PIX *pixd, PIX *pixs, SEL *sel);


/*-----------------------------------------------------------------*
 *    Generic binary morphological ops implemented with rasterop   *
 *-----------------------------------------------------------------*/
/*!
 * \brief   pixDilate()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) This dilates src using hits in Sel.
 *      (2) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (3) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixDilate(NULL, pixs, ...);
 *          (b) pixDilate(pixs, pixs, ...);
 *          (c) pixDilate(pixd, pixs, ...);
 *      (4) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixDilate(PIX  *pixd,
          PIX  *pixs,
          SEL  *sel)
{
l_int32  i, j, w, h, sx, sy, cx, cy, seldata;
PIX     *pixt;

    PROCNAME("pixDilate");

    if ((pixd = processMorphArgs1(pixd, pixs, sel, &pixt)) == NULL)
        return (PIX *)ERROR_PTR("processMorphArgs1 failed", procName, pixd);

    pixGetDimensions(pixs, &w, &h, NULL);
    selGetParameters(sel, &sy, &sx, &cy, &cx);
    pixClearAll(pixd);
    for (i = 0; i < sy; i++) {
        for (j = 0; j < sx; j++) {
            seldata = sel->data[i][j];
            if (seldata == 1) {   /* src | dst */
                pixRasterop(pixd, j - cx, i - cy, w, h, PIX_SRC | PIX_DST,
                            pixt, 0, 0);
            }
        }
    }

    pixDestroy(&pixt);
    return pixd;
}


/*!
 * \brief   pixErode()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) This erodes src using hits in Sel.
 *      (2) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (3) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixErode(NULL, pixs, ...);
 *          (b) pixErode(pixs, pixs, ...);
 *          (c) pixErode(pixd, pixs, ...);
 *      (4) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixErode(PIX  *pixd,
         PIX  *pixs,
         SEL  *sel)
{
l_int32  i, j, w, h, sx, sy, cx, cy, seldata;
l_int32  xp, yp, xn, yn;
PIX     *pixt;

    PROCNAME("pixErode");

    if ((pixd = processMorphArgs1(pixd, pixs, sel, &pixt)) == NULL)
        return (PIX *)ERROR_PTR("processMorphArgs1 failed", procName, pixd);

    pixGetDimensions(pixs, &w, &h, NULL);
    selGetParameters(sel, &sy, &sx, &cy, &cx);
    pixSetAll(pixd);
    for (i = 0; i < sy; i++) {
        for (j = 0; j < sx; j++) {
            seldata = sel->data[i][j];
            if (seldata == 1) {   /* src & dst */
                    pixRasterop(pixd, cx - j, cy - i, w, h, PIX_SRC & PIX_DST,
                                pixt, 0, 0);
            }
        }
    }

        /* Clear near edges.  We do this for the asymmetric boundary
         * condition convention that implements erosion assuming all
         * pixels surrounding the image are OFF.  If you use a
         * use a symmetric b.c. convention, where the erosion is
         * implemented assuming pixels surrounding the image
         * are ON, these operations are omitted.  */
    if (MORPH_BC == ASYMMETRIC_MORPH_BC) {
        selFindMaxTranslations(sel, &xp, &yp, &xn, &yn);
        if (xp > 0)
            pixRasterop(pixd, 0, 0, xp, h, PIX_CLR, NULL, 0, 0);
        if (xn > 0)
            pixRasterop(pixd, w - xn, 0, xn, h, PIX_CLR, NULL, 0, 0);
        if (yp > 0)
            pixRasterop(pixd, 0, 0, w, yp, PIX_CLR, NULL, 0, 0);
        if (yn > 0)
            pixRasterop(pixd, 0, h - yn, w, yn, PIX_CLR, NULL, 0, 0);
    }

    pixDestroy(&pixt);
    return pixd;
}


/*!
 * \brief   pixHMT()
 *
 * \param[in]    pixd   [optional]; this can be null, equal to pixs,
 *                      or different from pixs
 * \param[in]    pixs   1 bpp
 * \param[in]    sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) The hit-miss transform erodes the src, using both hits
 *          and misses in the Sel.  It ANDs the shifted src for hits
 *          and ANDs the inverted shifted src for misses.
 *      (2) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (3) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixHMT(NULL, pixs, ...);
 *          (b) pixHMT(pixs, pixs, ...);
 *          (c) pixHMT(pixd, pixs, ...);
 *      (4) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixHMT(PIX  *pixd,
       PIX  *pixs,
       SEL  *sel)
{
l_int32  i, j, w, h, sx, sy, cx, cy, firstrasterop, seldata;
l_int32  xp, yp, xn, yn;
PIX     *pixt;

    PROCNAME("pixHMT");

    if ((pixd = processMorphArgs1(pixd, pixs, sel, &pixt)) == NULL)
        return (PIX *)ERROR_PTR("processMorphArgs1 failed", procName, pixd);

    pixGetDimensions(pixs, &w, &h, NULL);
    selGetParameters(sel, &sy, &sx, &cy, &cx);
    firstrasterop = TRUE;
    for (i = 0; i < sy; i++) {
        for (j = 0; j < sx; j++) {
            seldata = sel->data[i][j];
            if (seldata == 1) {  /* hit */
                if (firstrasterop == TRUE) {  /* src only */
                    pixClearAll(pixd);
                    pixRasterop(pixd, cx - j, cy - i, w, h, PIX_SRC,
                                pixt, 0, 0);
                    firstrasterop = FALSE;
                } else {   /* src & dst */
                    pixRasterop(pixd, cx - j, cy - i, w, h, PIX_SRC & PIX_DST,
                                pixt, 0, 0);
                }
            } else if (seldata == 2) {  /* miss */
                if (firstrasterop == TRUE) {  /* ~src only */
                    pixSetAll(pixd);
                    pixRasterop(pixd, cx - j, cy - i, w, h, PIX_NOT(PIX_SRC),
                             pixt, 0, 0);
                    firstrasterop = FALSE;
                } else {  /* ~src & dst */
                    pixRasterop(pixd, cx - j, cy - i, w, h,
                                PIX_NOT(PIX_SRC) & PIX_DST,
                                pixt, 0, 0);
                }
            }
        }
    }

        /* Clear near edges */
    selFindMaxTranslations(sel, &xp, &yp, &xn, &yn);
    if (xp > 0)
        pixRasterop(pixd, 0, 0, xp, h, PIX_CLR, NULL, 0, 0);
    if (xn > 0)
        pixRasterop(pixd, w - xn, 0, xn, h, PIX_CLR, NULL, 0, 0);
    if (yp > 0)
        pixRasterop(pixd, 0, 0, w, yp, PIX_CLR, NULL, 0, 0);
    if (yn > 0)
        pixRasterop(pixd, 0, h - yn, w, yn, PIX_CLR, NULL, 0, 0);

    pixDestroy(&pixt);
    return pixd;
}


/*!
 * \brief   pixOpen()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) Generic morphological opening, using hits in the Sel.
 *      (2) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (3) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixOpen(NULL, pixs, ...);
 *          (b) pixOpen(pixs, pixs, ...);
 *          (c) pixOpen(pixd, pixs, ...);
 *      (4) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixOpen(PIX  *pixd,
        PIX  *pixs,
        SEL  *sel)
{
PIX  *pixt;

    PROCNAME("pixOpen");

    if ((pixd = processMorphArgs2(pixd, pixs, sel)) == NULL)
        return (PIX *)ERROR_PTR("pixd not returned", procName, pixd);

    if ((pixt = pixErode(NULL, pixs, sel)) == NULL)
        return (PIX *)ERROR_PTR("pixt not made", procName, pixd);
    pixDilate(pixd, pixt, sel);
    pixDestroy(&pixt);

    return pixd;
}


/*!
 * \brief   pixClose()
 *
 * \param[in]    pixd [optional]; this can be null, equal to pixs,
 *                    or different from pixs
 * \param[in]    pixs 1 bpp
 * \param[in]    sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) Generic morphological closing, using hits in the Sel.
 *      (2) This implementation is a strict dual of the opening if
 *          symmetric boundary conditions are used (see notes at top
 *          of this file).
 *      (3) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (4) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixClose(NULL, pixs, ...);
 *          (b) pixClose(pixs, pixs, ...);
 *          (c) pixClose(pixd, pixs, ...);
 *      (5) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixClose(PIX  *pixd,
         PIX  *pixs,
         SEL  *sel)
{
PIX  *pixt;

    PROCNAME("pixClose");

    if ((pixd = processMorphArgs2(pixd, pixs, sel)) == NULL)
        return (PIX *)ERROR_PTR("pixd not returned", procName, pixd);

    if ((pixt = pixDilate(NULL, pixs, sel)) == NULL)
        return (PIX *)ERROR_PTR("pixt not made", procName, pixd);
    pixErode(pixd, pixt, sel);
    pixDestroy(&pixt);

    return pixd;
}


/*!
 * \brief   pixCloseSafe()
 *
 * \param[in]    pixd   [optional]; this can be null, equal to pixs,
 *                      or different from pixs
 * \param[in]    pixs   1 bpp
 * \param[in]    sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) Generic morphological closing, using hits in the Sel.
 *      (2) If non-symmetric boundary conditions are used, this
 *          function adds a border of OFF pixels that is of
 *          sufficient size to avoid losing pixels from the dilation,
 *          and it removes the border after the operation is finished.
 *          It thus enforces a correct extensive result for closing.
 *      (3) If symmetric b.c. are used, it is not necessary to add
 *          and remove this border.
 *      (4) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (5) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixCloseSafe(NULL, pixs, ...);
 *          (b) pixCloseSafe(pixs, pixs, ...);
 *          (c) pixCloseSafe(pixd, pixs, ...);
 *      (6) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixCloseSafe(PIX  *pixd,
             PIX  *pixs,
             SEL  *sel)
{
l_int32  xp, yp, xn, yn, xmax, xbord;
PIX     *pixt1, *pixt2;

    PROCNAME("pixCloseSafe");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (!sel)
        return (PIX *)ERROR_PTR("sel not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);

        /* Symmetric b.c. handles correctly without added pixels */
    if (MORPH_BC == SYMMETRIC_MORPH_BC)
        return pixClose(pixd, pixs, sel);

    selFindMaxTranslations(sel, &xp, &yp, &xn, &yn);
    xmax = L_MAX(xp, xn);
    xbord = 32 * ((xmax + 31) / 32);  /* full 32 bit words */

    if ((pixt1 = pixAddBorderGeneral(pixs, xbord, xbord, yp, yn, 0)) == NULL)
        return (PIX *)ERROR_PTR("pixt1 not made", procName, pixd);
    pixClose(pixt1, pixt1, sel);
    if ((pixt2 = pixRemoveBorderGeneral(pixt1, xbord, xbord, yp, yn)) == NULL)
        return (PIX *)ERROR_PTR("pixt2 not made", procName, pixd);
    pixDestroy(&pixt1);

    if (!pixd)
        return pixt2;

    pixCopy(pixd, pixt2);
    pixDestroy(&pixt2);
    return pixd;
}


/*!
 * \brief   pixOpenGeneralized()
 *
 * \param[in]    pixd   [optional]; this can be null, equal to pixs,
 *                      or different from pixs
 * \param[in]    pixs   1 bpp
 * \param[in]    sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) Generalized morphological opening, using both hits and
 *          misses in the Sel.
 *      (2) This does a hit-miss transform, followed by a dilation
 *          using the hits.
 *      (3) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (4) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixOpenGeneralized(NULL, pixs, ...);
 *          (b) pixOpenGeneralized(pixs, pixs, ...);
 *          (c) pixOpenGeneralized(pixd, pixs, ...);
 *      (5) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixOpenGeneralized(PIX  *pixd,
                   PIX  *pixs,
                   SEL  *sel)
{
PIX  *pixt;

    PROCNAME("pixOpenGeneralized");

    if ((pixd = processMorphArgs2(pixd, pixs, sel)) == NULL)
        return (PIX *)ERROR_PTR("pixd not returned", procName, pixd);

    if ((pixt = pixHMT(NULL, pixs, sel)) == NULL)
        return (PIX *)ERROR_PTR("pixt not made", procName, pixd);
    pixDilate(pixd, pixt, sel);
    pixDestroy(&pixt);
    return pixd;
}


/*!
 * \brief   pixCloseGeneralized()
 *
 * \param[in]    pixd   [optional]; this can be null, equal to pixs,
 *                      or different from pixs
 * \param[in]    pixs   1 bpp
 * \param[in]    sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) Generalized morphological closing, using both hits and
 *          misses in the Sel.
 *      (2) This does a dilation using the hits, followed by a
 *          hit-miss transform.
 *      (3) This operation is a dual of the generalized opening.
 *      (4) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (5) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixCloseGeneralized(NULL, pixs, ...);
 *          (b) pixCloseGeneralized(pixs, pixs, ...);
 *          (c) pixCloseGeneralized(pixd, pixs, ...);
 *      (6) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixCloseGeneralized(PIX  *pixd,
                    PIX  *pixs,
                    SEL  *sel)
{
PIX  *pixt;

    PROCNAME("pixCloseGeneralized");

    if ((pixd = processMorphArgs2(pixd, pixs, sel)) == NULL)
        return (PIX *)ERROR_PTR("pixd not returned", procName, pixd);

    if ((pixt = pixDilate(NULL, pixs, sel)) == NULL)
        return (PIX *)ERROR_PTR("pixt not made", procName, pixd);
    pixHMT(pixd, pixt, sel);
    pixDestroy(&pixt);

    return pixd;
}


/*-----------------------------------------------------------------*
 *          Binary morphological (raster) ops with brick Sels      *
 *-----------------------------------------------------------------*/
/*!
 * \brief   pixDilateBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do separably if both hsize and vsize are > 1.
 *      (4) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (5) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixDilateBrick(NULL, pixs, ...);
 *          (b) pixDilateBrick(pixs, pixs, ...);
 *          (c) pixDilateBrick(pixd, pixs, ...);
 *      (6) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixDilateBrick(PIX     *pixd,
               PIX     *pixs,
               l_int32  hsize,
               l_int32  vsize)
{
PIX  *pixt;
SEL  *sel, *selh, *selv;

    PROCNAME("pixDilateBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);
    if (hsize == 1 || vsize == 1) {  /* no intermediate result */
        sel = selCreateBrick(vsize, hsize, vsize / 2, hsize / 2, SEL_HIT);
        if (!sel)
            return (PIX *)ERROR_PTR("sel not made", procName, pixd);
        pixd = pixDilate(pixd, pixs, sel);
        selDestroy(&sel);
    } else {
        if ((selh = selCreateBrick(1, hsize, 0, hsize / 2, SEL_HIT)) == NULL)
            return (PIX *)ERROR_PTR("selh not made", procName, pixd);
        if ((selv = selCreateBrick(vsize, 1, vsize / 2, 0, SEL_HIT)) == NULL) {
            selDestroy(&selh);
            return (PIX *)ERROR_PTR("selv not made", procName, pixd);
        }
        pixt = pixDilate(NULL, pixs, selh);
        pixd = pixDilate(pixd, pixt, selv);
        pixDestroy(&pixt);
        selDestroy(&selh);
        selDestroy(&selv);
    }

    return pixd;
}


/*!
 * \brief   pixErodeBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do separably if both hsize and vsize are > 1.
 *      (4) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (5) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixErodeBrick(NULL, pixs, ...);
 *          (b) pixErodeBrick(pixs, pixs, ...);
 *          (c) pixErodeBrick(pixd, pixs, ...);
 *      (6) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixErodeBrick(PIX     *pixd,
              PIX     *pixs,
              l_int32  hsize,
              l_int32  vsize)
{
PIX  *pixt;
SEL  *sel, *selh, *selv;

    PROCNAME("pixErodeBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);
    if (hsize == 1 || vsize == 1) {  /* no intermediate result */
        sel = selCreateBrick(vsize, hsize, vsize / 2, hsize / 2, SEL_HIT);
        if (!sel)
            return (PIX *)ERROR_PTR("sel not made", procName, pixd);
        pixd = pixErode(pixd, pixs, sel);
        selDestroy(&sel);
    } else {
        if ((selh = selCreateBrick(1, hsize, 0, hsize / 2, SEL_HIT)) == NULL)
            return (PIX *)ERROR_PTR("selh not made", procName, pixd);
        if ((selv = selCreateBrick(vsize, 1, vsize / 2, 0, SEL_HIT)) == NULL) {
            selDestroy(&selh);
            return (PIX *)ERROR_PTR("selv not made", procName, pixd);
        }
        pixt = pixErode(NULL, pixs, selh);
        pixd = pixErode(pixd, pixt, selv);
        pixDestroy(&pixt);
        selDestroy(&selh);
        selDestroy(&selv);
    }

    return pixd;
}


/*!
 * \brief   pixOpenBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do separably if both hsize and vsize are > 1.
 *      (4) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (5) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixOpenBrick(NULL, pixs, ...);
 *          (b) pixOpenBrick(pixs, pixs, ...);
 *          (c) pixOpenBrick(pixd, pixs, ...);
 *      (6) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixOpenBrick(PIX     *pixd,
             PIX     *pixs,
             l_int32  hsize,
             l_int32  vsize)
{
PIX  *pixt;
SEL  *sel, *selh, *selv;

    PROCNAME("pixOpenBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);
    if (hsize == 1 || vsize == 1) {  /* no intermediate result */
        sel = selCreateBrick(vsize, hsize, vsize / 2, hsize / 2, SEL_HIT);
        if (!sel)
            return (PIX *)ERROR_PTR("sel not made", procName, pixd);
        pixd = pixOpen(pixd, pixs, sel);
        selDestroy(&sel);
    } else {  /* do separably */
        if ((selh = selCreateBrick(1, hsize, 0, hsize / 2, SEL_HIT)) == NULL)
            return (PIX *)ERROR_PTR("selh not made", procName, pixd);
        if ((selv = selCreateBrick(vsize, 1, vsize / 2, 0, SEL_HIT)) == NULL) {
            selDestroy(&selh);
            return (PIX *)ERROR_PTR("selv not made", procName, pixd);
        }
        pixt = pixErode(NULL, pixs, selh);
        pixd = pixErode(pixd, pixt, selv);
        pixDilate(pixt, pixd, selh);
        pixDilate(pixd, pixt, selv);
        pixDestroy(&pixt);
        selDestroy(&selh);
        selDestroy(&selv);
    }

    return pixd;
}


/*!
 * \brief   pixCloseBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do separably if both hsize and vsize are > 1.
 *      (4) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (5) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixCloseBrick(NULL, pixs, ...);
 *          (b) pixCloseBrick(pixs, pixs, ...);
 *          (c) pixCloseBrick(pixd, pixs, ...);
 *      (6) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixCloseBrick(PIX     *pixd,
              PIX     *pixs,
              l_int32  hsize,
              l_int32  vsize)
{
PIX  *pixt;
SEL  *sel, *selh, *selv;

    PROCNAME("pixCloseBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);
    if (hsize == 1 || vsize == 1) {  /* no intermediate result */
        sel = selCreateBrick(vsize, hsize, vsize / 2, hsize / 2, SEL_HIT);
        if (!sel)
            return (PIX *)ERROR_PTR("sel not made", procName, pixd);
        pixd = pixClose(pixd, pixs, sel);
        selDestroy(&sel);
    } else {  /* do separably */
        if ((selh = selCreateBrick(1, hsize, 0, hsize / 2, SEL_HIT)) == NULL)
            return (PIX *)ERROR_PTR("selh not made", procName, pixd);
        if ((selv = selCreateBrick(vsize, 1, vsize / 2, 0, SEL_HIT)) == NULL) {
            selDestroy(&selh);
            return (PIX *)ERROR_PTR("selv not made", procName, pixd);
        }
        pixt = pixDilate(NULL, pixs, selh);
        pixd = pixDilate(pixd, pixt, selv);
        pixErode(pixt, pixd, selh);
        pixErode(pixd, pixt, selv);
        pixDestroy(&pixt);
        selDestroy(&selh);
        selDestroy(&selv);
    }

    return pixd;
}


/*!
 * \brief   pixCloseSafeBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do separably if both hsize and vsize are > 1.
 *      (4) Safe closing adds a border of 0 pixels, of sufficient size so
 *          that all pixels in input image are processed within
 *          32-bit words in the expanded image.  As a result, there is
 *          no special processing for pixels near the boundary, and there
 *          are no boundary effects.  The border is removed at the end.
 *      (5) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (6) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixCloseBrick(NULL, pixs, ...);
 *          (b) pixCloseBrick(pixs, pixs, ...);
 *          (c) pixCloseBrick(pixd, pixs, ...);
 *      (7) The size of the result is determined by pixs.
 * </pre>
 */
PIX *
pixCloseSafeBrick(PIX     *pixd,
                  PIX     *pixs,
                  l_int32  hsize,
                  l_int32  vsize)
{
l_int32  maxtrans, bordsize;
PIX     *pixsb, *pixt, *pixdb;
SEL     *sel, *selh, *selv;

    PROCNAME("pixCloseSafeBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);

        /* Symmetric b.c. handles correctly without added pixels */
    if (MORPH_BC == SYMMETRIC_MORPH_BC)
        return pixCloseBrick(pixd, pixs, hsize, vsize);

    maxtrans = L_MAX(hsize / 2, vsize / 2);
    bordsize = 32 * ((maxtrans + 31) / 32);  /* full 32 bit words */
    pixsb = pixAddBorder(pixs, bordsize, 0);

    if (hsize == 1 || vsize == 1) {  /* no intermediate result */
        sel = selCreateBrick(vsize, hsize, vsize / 2, hsize / 2, SEL_HIT);
        if (!sel) {
            pixDestroy(&pixsb);
            return (PIX *)ERROR_PTR("sel not made", procName, pixd);
        }
        pixdb = pixClose(NULL, pixsb, sel);
        selDestroy(&sel);
    } else {  /* do separably */
        selh = selCreateBrick(1, hsize, 0, hsize / 2, SEL_HIT);
        selv = selCreateBrick(vsize, 1, vsize / 2, 0, SEL_HIT);
        if (!selh || !selv) {
            selDestroy(&selh);
            selDestroy(&selv);
            pixDestroy(&pixsb);
            return (PIX *)ERROR_PTR("selh and selv not both made",
                                    procName, pixd);
        }
        pixt = pixDilate(NULL, pixsb, selh);
        pixdb = pixDilate(NULL, pixt, selv);
        pixErode(pixt, pixdb, selh);
        pixErode(pixdb, pixt, selv);
        pixDestroy(&pixt);
        selDestroy(&selh);
        selDestroy(&selv);
    }

    pixt = pixRemoveBorder(pixdb, bordsize);
    pixDestroy(&pixsb);
    pixDestroy(&pixdb);

    if (!pixd) {
        pixd = pixt;
    } else {
        pixCopy(pixd, pixt);
        pixDestroy(&pixt);
    }
    return pixd;
}


/*-----------------------------------------------------------------*
 *     Binary composed morphological (raster) ops with brick Sels  *
 *-----------------------------------------------------------------*/
/* \brief   selectComposableSels()
 *
 * \param[in]    size         of composed sel
 * \param[in]    direction    L_HORIZ, L_VERT
 * \param[out]   psel1        [optional] contiguous sel; can be null
 * \param[out]   psel2        [optional] comb sel; can be null
 * \return   0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) When using composable Sels, where the original Sel is
 *          decomposed into two, the best you can do in terms
 *          of reducing the computation is by a factor:
 *
 *               2 * sqrt(size) / size
 *
 *          In practice, you get quite close to this.  E.g.,
 *
 *             Sel size     |   Optimum reduction factor
 *             --------         ------------------------
 *                36        |          1/3
 *                64        |          1/4
 *               144        |          1/6
 *               256        |          1/8
 * </pre>
 */
l_int32
selectComposableSels(l_int32  size,
                     l_int32  direction,
                     SEL    **psel1,
                     SEL    **psel2)
{
l_int32  factor1, factor2;

    PROCNAME("selectComposableSels");

    if (!psel1 && !psel2)
        return ERROR_INT("neither &sel1 nor &sel2 are defined", procName, 1);
    if (psel1) *psel1 = NULL;
    if (psel2) *psel2 = NULL;
    if (size < 1 || size > 10000)
        return ERROR_INT("size < 1 or size > 10000", procName, 1);
    if (direction != L_HORIZ && direction != L_VERT)
        return ERROR_INT("invalid direction", procName, 1);

    if (selectComposableSizes(size, &factor1, &factor2))
        return ERROR_INT("factors not found", procName, 1);

    if (psel1) {
        if (direction == L_HORIZ)
            *psel1 = selCreateBrick(1, factor1, 0, factor1 / 2, SEL_HIT);
        else
            *psel1 = selCreateBrick(factor1, 1, factor1 / 2 , 0, SEL_HIT);
    }
    if (psel2)
        *psel2 = selCreateComb(factor1, factor2, direction);
    return 0;
}


/*!
 * \brief   selectComposableSizes()
 *
 * \param[in]    size       of sel to be decomposed
 * \param[out]   pfactor1   larger factor
 * \param[out]   pfactor2   smaller factor
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This works for Sel sizes up to 10000, which seems sufficient.
 *      (2) The composable sel size is typically within +- 1 of
 *          the requested size.  Up to size = 300, the maximum difference
 *          is +- 2.
 *      (3) We choose an overall cost function where the penalty for
 *          the size difference between input and actual is 4 times
 *          the penalty for additional rasterops.
 *      (4) Returned values: factor1 >= factor2
 *          If size > 1, then factor1 > 1.
 * </pre>
 */
l_ok
selectComposableSizes(l_int32   size,
                      l_int32  *pfactor1,
                      l_int32  *pfactor2)
{
l_int32  i, midval, val1, val2m, val2p;
l_int32  index, prodm, prodp;
l_int32  mincost, totcost, rastcostm, rastcostp, diffm, diffp;
l_int32  lowval[256];
l_int32  hival[256];
l_int32  rastcost[256];  /* excess in sum of sizes (extra rasterops) */
l_int32  diff[256];  /* diff between product (sel size) and input size */

    PROCNAME("selectComposableSizes");

    if (size < 1 || size > 10000)
        return ERROR_INT("size < 1 or size > 10000", procName, 1);
    if (!pfactor1 || !pfactor2)
        return ERROR_INT("&factor1 or &factor2 not defined", procName, 1);

    midval = (l_int32)(sqrt((l_float64)size) + 0.001);
    if (midval * midval == size) {
        *pfactor1 = *pfactor2 = midval;
        return 0;
    }

        /* Set up arrays.  For each val1, optimize for lowest diff,
         * and save the rastcost, the diff, and the two factors. */
    for (val1 = midval + 1, i = 0; val1 > 0; val1--, i++) {
        val2m = size / val1;
        val2p = val2m + 1;
        prodm = val1 * val2m;
        prodp = val1 * val2p;
        rastcostm = val1 + val2m - 2 * midval;
        rastcostp = val1 + val2p - 2 * midval;
        diffm = L_ABS(size - prodm);
        diffp = L_ABS(size - prodp);
        if (diffm <= diffp) {
            lowval[i] = L_MIN(val1, val2m);
            hival[i] = L_MAX(val1, val2m);
            rastcost[i] = rastcostm;
            diff[i] = diffm;
        } else {
            lowval[i] = L_MIN(val1, val2p);
            hival[i] = L_MAX(val1, val2p);
            rastcost[i] = rastcostp;
            diff[i] = diffp;
        }
    }

        /* Choose the optimum factors; use cost ratio 4 on diff */
    mincost = 10000;
    index = 1;  /* unimportant initial value */
    for (i = 0; i < midval + 1; i++) {
        if (diff[i] == 0 && rastcost[i] < ACCEPTABLE_COST) {
            *pfactor1 = hival[i];
            *pfactor2 = lowval[i];
            return 0;
        }
        totcost = 4 * diff[i] + rastcost[i];
        if (totcost < mincost) {
            mincost = totcost;
            index = i;
        }
    }
    *pfactor1 = hival[index];
    *pfactor2 = lowval[index];

    return 0;
}


/*!
 * \brief   pixDilateCompBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do compositely for each dimension > 1.
 *      (4) Do separably if both hsize and vsize are > 1.
 *      (5) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (6) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixDilateCompBrick(NULL, pixs, ...);
 *          (b) pixDilateCompBrick(pixs, pixs, ...);
 *          (c) pixDilateCompBrick(pixd, pixs, ...);
 *      (7) The dimensions of the resulting image are determined by pixs.
 *      (8) CAUTION: both hsize and vsize are being decomposed.
 *          The decomposer chooses a product of sizes (call them
 *          'terms') for each that is close to the input size,
 *          but not necessarily equal to it.  It attempts to optimize:
 *             (a) for consistency with the input values: the product
 *                 of terms is close to the input size
 *             (b) for efficiency of the operation: the sum of the
 *                 terms is small; ideally about twice the square
 *                 root of the input size.
 *          So, for example, if the input hsize = 37, which is
 *          a prime number, the decomposer will break this into two
 *          terms, 6 and 6, so that the net result is a dilation
 *          with hsize = 36.
 * </pre>
 */
PIX *
pixDilateCompBrick(PIX     *pixd,
                   PIX     *pixs,
                   l_int32  hsize,
                   l_int32  vsize)
{
PIX  *pix1, *pix2, *pix3;
SEL  *selh1 = NULL;
SEL  *selh2 = NULL;
SEL  *selv1 = NULL;
SEL  *selv2 = NULL;

    PROCNAME("pixDilateCompBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);
    if (hsize > 1) {
        if (selectComposableSels(hsize, L_HORIZ, &selh1, &selh2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            return (PIX *)ERROR_PTR("horiz sels not made", procName, pixd);
        }
    }
    if (vsize > 1) {
        if (selectComposableSels(vsize, L_VERT, &selv1, &selv2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            selDestroy(&selv1);
            selDestroy(&selv2);
            return (PIX *)ERROR_PTR("vert sels not made", procName, pixd);
        }
    }

    pix1 = pixAddBorder(pixs, 32, 0);
    if (vsize == 1) {
        pix2 = pixDilate(NULL, pix1, selh1);
        pix3 = pixDilate(NULL, pix2, selh2);
    } else if (hsize == 1) {
        pix2 = pixDilate(NULL, pix1, selv1);
        pix3 = pixDilate(NULL, pix2, selv2);
    } else {
        pix2 = pixDilate(NULL, pix1, selh1);
        pix3 = pixDilate(NULL, pix2, selh2);
        pixDilate(pix2, pix3, selv1);
        pixDilate(pix3, pix2, selv2);
    }
    pixDestroy(&pix1);
    pixDestroy(&pix2);

    selDestroy(&selh1);
    selDestroy(&selh2);
    selDestroy(&selv1);
    selDestroy(&selv2);

    pix1 = pixRemoveBorder(pix3, 32);
    pixDestroy(&pix3);
    if (!pixd)
        return pix1;
    pixCopy(pixd, pix1);
    pixDestroy(&pix1);
    return pixd;
}


/*!
 * \brief   pixErodeCompBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do compositely for each dimension > 1.
 *      (4) Do separably if both hsize and vsize are > 1.
 *      (5) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (6) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixErodeCompBrick(NULL, pixs, ...);
 *          (b) pixErodeCompBrick(pixs, pixs, ...);
 *          (c) pixErodeCompBrick(pixd, pixs, ...);
 *      (7) The dimensions of the resulting image are determined by pixs.
 *      (8) CAUTION: both hsize and vsize are being decomposed.
 *          The decomposer chooses a product of sizes (call them
 *          'terms') for each that is close to the input size,
 *          but not necessarily equal to it.  It attempts to optimize:
 *             (a) for consistency with the input values: the product
 *                 of terms is close to the input size
 *             (b) for efficiency of the operation: the sum of the
 *                 terms is small; ideally about twice the square
 *                 root of the input size.
 *          So, for example, if the input hsize = 37, which is
 *          a prime number, the decomposer will break this into two
 *          terms, 6 and 6, so that the net result is a dilation
 *          with hsize = 36.
 * </pre>
 */
PIX *
pixErodeCompBrick(PIX     *pixd,
                  PIX     *pixs,
                  l_int32  hsize,
                  l_int32  vsize)
{
PIX  *pixt;
SEL  *selh1 = NULL;
SEL  *selh2 = NULL;
SEL  *selv1 = NULL;
SEL  *selv2 = NULL;

    PROCNAME("pixErodeCompBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);
    if (hsize > 1) {
        if (selectComposableSels(hsize, L_HORIZ, &selh1, &selh2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            return (PIX *)ERROR_PTR("horiz sels not made", procName, pixd);
        }
    }
    if (vsize > 1) {
        if (selectComposableSels(vsize, L_VERT, &selv1, &selv2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            selDestroy(&selv1);
            selDestroy(&selv2);
            return (PIX *)ERROR_PTR("vert sels not made", procName, pixd);
        }
    }

    if (vsize == 1) {
        pixt = pixErode(NULL, pixs, selh1);
        pixd = pixErode(pixd, pixt, selh2);
    } else if (hsize == 1) {
        pixt = pixErode(NULL, pixs, selv1);
        pixd = pixErode(pixd, pixt, selv2);
    } else {
        pixt = pixErode(NULL, pixs, selh1);
        pixd = pixErode(pixd, pixt, selh2);
        pixErode(pixt, pixd, selv1);
        pixErode(pixd, pixt, selv2);
    }
    pixDestroy(&pixt);

    selDestroy(&selh1);
    selDestroy(&selh2);
    selDestroy(&selv1);
    selDestroy(&selv2);
    return pixd;
}


/*!
 * \brief   pixOpenCompBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do compositely for each dimension > 1.
 *      (4) Do separably if both hsize and vsize are > 1.
 *      (5) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (6) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixOpenCompBrick(NULL, pixs, ...);
 *          (b) pixOpenCompBrick(pixs, pixs, ...);
 *          (c) pixOpenCompBrick(pixd, pixs, ...);
 *      (7) The dimensions of the resulting image are determined by pixs.
 *      (8) CAUTION: both hsize and vsize are being decomposed.
 *          The decomposer chooses a product of sizes (call them
 *          'terms') for each that is close to the input size,
 *          but not necessarily equal to it.  It attempts to optimize:
 *             (a) for consistency with the input values: the product
 *                 of terms is close to the input size
 *             (b) for efficiency of the operation: the sum of the
 *                 terms is small; ideally about twice the square
 *                 root of the input size.
 *          So, for example, if the input hsize = 37, which is
 *          a prime number, the decomposer will break this into two
 *          terms, 6 and 6, so that the net result is a dilation
 *          with hsize = 36.
 * </pre>
 */
PIX *
pixOpenCompBrick(PIX     *pixd,
                 PIX     *pixs,
                 l_int32  hsize,
                 l_int32  vsize)
{
PIX  *pixt;
SEL  *selh1 = NULL;
SEL  *selh2 = NULL;
SEL  *selv1 = NULL;
SEL  *selv2 = NULL;

    PROCNAME("pixOpenCompBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);
    if (hsize > 1) {
        if (selectComposableSels(hsize, L_HORIZ, &selh1, &selh2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            return (PIX *)ERROR_PTR("horiz sels not made", procName, pixd);
        }
    }
    if (vsize > 1) {
        if (selectComposableSels(vsize, L_VERT, &selv1, &selv2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            selDestroy(&selv1);
            selDestroy(&selv2);
            return (PIX *)ERROR_PTR("vert sels not made", procName, pixd);
        }
    }

    if (vsize == 1) {
        pixt = pixErode(NULL, pixs, selh1);
        pixd = pixErode(pixd, pixt, selh2);
        pixDilate(pixt, pixd, selh1);
        pixDilate(pixd, pixt, selh2);
    } else if (hsize == 1) {
        pixt = pixErode(NULL, pixs, selv1);
        pixd = pixErode(pixd, pixt, selv2);
        pixDilate(pixt, pixd, selv1);
        pixDilate(pixd, pixt, selv2);
    } else {  /* do separably */
        pixt = pixErode(NULL, pixs, selh1);
        pixd = pixErode(pixd, pixt, selh2);
        pixErode(pixt, pixd, selv1);
        pixErode(pixd, pixt, selv2);
        pixDilate(pixt, pixd, selh1);
        pixDilate(pixd, pixt, selh2);
        pixDilate(pixt, pixd, selv1);
        pixDilate(pixd, pixt, selv2);
    }
    pixDestroy(&pixt);

    selDestroy(&selh1);
    selDestroy(&selh2);
    selDestroy(&selv1);
    selDestroy(&selv2);
    return pixd;
}


/*!
 * \brief   pixCloseCompBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do compositely for each dimension > 1.
 *      (4) Do separably if both hsize and vsize are > 1.
 *      (5) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (6) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixCloseCompBrick(NULL, pixs, ...);
 *          (b) pixCloseCompBrick(pixs, pixs, ...);
 *          (c) pixCloseCompBrick(pixd, pixs, ...);
 *      (7) The dimensions of the resulting image are determined by pixs.
 *      (8) CAUTION: both hsize and vsize are being decomposed.
 *          The decomposer chooses a product of sizes (call them
 *          'terms') for each that is close to the input size,
 *          but not necessarily equal to it.  It attempts to optimize:
 *             (a) for consistency with the input values: the product
 *                 of terms is close to the input size
 *             (b) for efficiency of the operation: the sum of the
 *                 terms is small; ideally about twice the square
 *                 root of the input size.
 *          So, for example, if the input hsize = 37, which is
 *          a prime number, the decomposer will break this into two
 *          terms, 6 and 6, so that the net result is a dilation
 *          with hsize = 36.
 * </pre>
 */
PIX *
pixCloseCompBrick(PIX     *pixd,
                  PIX     *pixs,
                  l_int32  hsize,
                  l_int32  vsize)
{
PIX  *pixt;
SEL  *selh1 = NULL;
SEL  *selh2 = NULL;
SEL  *selv1 = NULL;
SEL  *selv2 = NULL;

    PROCNAME("pixCloseCompBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);
    if (hsize > 1) {
        if (selectComposableSels(hsize, L_HORIZ, &selh1, &selh2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            return (PIX *)ERROR_PTR("horiz sels not made", procName, pixd);
        }
    }
    if (vsize > 1) {
        if (selectComposableSels(vsize, L_VERT, &selv1, &selv2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            selDestroy(&selv1);
            selDestroy(&selv2);
            return (PIX *)ERROR_PTR("vert sels not made", procName, pixd);
        }
    }

    if (vsize == 1) {
        pixt = pixDilate(NULL, pixs, selh1);
        pixd = pixDilate(pixd, pixt, selh2);
        pixErode(pixt, pixd, selh1);
        pixErode(pixd, pixt, selh2);
    } else if (hsize == 1) {
        pixt = pixDilate(NULL, pixs, selv1);
        pixd = pixDilate(pixd, pixt, selv2);
        pixErode(pixt, pixd, selv1);
        pixErode(pixd, pixt, selv2);
    } else {  /* do separably */
        pixt = pixDilate(NULL, pixs, selh1);
        pixd = pixDilate(pixd, pixt, selh2);
        pixDilate(pixt, pixd, selv1);
        pixDilate(pixd, pixt, selv2);
        pixErode(pixt, pixd, selh1);
        pixErode(pixd, pixt, selh2);
        pixErode(pixt, pixd, selv1);
        pixErode(pixd, pixt, selv2);
    }
    pixDestroy(&pixt);

    selDestroy(&selh1);
    selDestroy(&selh2);
    selDestroy(&selv1);
    selDestroy(&selv2);
    return pixd;
}


/*!
 * \brief   pixCloseSafeCompBrick()
 *
 * \param[in]    pixd    [optional]; this can be null, equal to pixs,
 *                       or different from pixs
 * \param[in]    pixs    1 bpp
 * \param[in]    hsize   width of brick Sel
 * \param[in]    vsize   height of brick Sel
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Sel is a brick with all elements being hits
 *      (2) The origin is at (x, y) = (hsize/2, vsize/2)
 *      (3) Do compositely for each dimension > 1.
 *      (4) Do separably if both hsize and vsize are > 1.
 *      (5) Safe closing adds a border of 0 pixels, of sufficient size so
 *          that all pixels in input image are processed within
 *          32-bit words in the expanded image.  As a result, there is
 *          no special processing for pixels near the boundary, and there
 *          are no boundary effects.  The border is removed at the end.
 *      (6) There are three cases:
 *          (a) pixd == null   (result into new pixd)
 *          (b) pixd == pixs   (in-place; writes result back to pixs)
 *          (c) pixd != pixs   (puts result into existing pixd)
 *      (7) For clarity, if the case is known, use these patterns:
 *          (a) pixd = pixCloseSafeCompBrick(NULL, pixs, ...);
 *          (b) pixCloseSafeCompBrick(pixs, pixs, ...);
 *          (c) pixCloseSafeCompBrick(pixd, pixs, ...);
 *      (8) The dimensions of the resulting image are determined by pixs.
 *      (9) CAUTION: both hsize and vsize are being decomposed.
 *          The decomposer chooses a product of sizes (call them
 *          'terms') for each that is close to the input size,
 *          but not necessarily equal to it.  It attempts to optimize:
 *             (a) for consistency with the input values: the product
 *                 of terms is close to the input size
 *             (b) for efficiency of the operation: the sum of the
 *                 terms is small; ideally about twice the square
 *                 root of the input size.
 *          So, for example, if the input hsize = 37, which is
 *          a prime number, the decomposer will break this into two
 *          terms, 6 and 6, so that the net result is a dilation
 *          with hsize = 36.
 * </pre>
 */
PIX *
pixCloseSafeCompBrick(PIX     *pixd,
                      PIX     *pixs,
                      l_int32  hsize,
                      l_int32  vsize)
{
l_int32  maxtrans, bordsize;
PIX     *pixsb, *pixt, *pixdb;
SEL     *selh1 = NULL;
SEL     *selh2 = NULL;
SEL     *selv1 = NULL;
SEL     *selv2 = NULL;

    PROCNAME("pixCloseSafeCompBrick");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);
    if (hsize < 1 || vsize < 1)
        return (PIX *)ERROR_PTR("hsize and vsize not >= 1", procName, pixd);

    if (hsize == 1 && vsize == 1)
        return pixCopy(pixd, pixs);

        /* Symmetric b.c. handles correctly without added pixels */
    if (MORPH_BC == SYMMETRIC_MORPH_BC)
        return pixCloseCompBrick(pixd, pixs, hsize, vsize);

    if (hsize > 1) {
        if (selectComposableSels(hsize, L_HORIZ, &selh1, &selh2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            return (PIX *)ERROR_PTR("horiz sels not made", procName, pixd);
        }
    }
    if (vsize > 1) {
        if (selectComposableSels(vsize, L_VERT, &selv1, &selv2)) {
            selDestroy(&selh1);
            selDestroy(&selh2);
            selDestroy(&selv1);
            selDestroy(&selv2);
            return (PIX *)ERROR_PTR("vert sels not made", procName, pixd);
        }
    }

    maxtrans = L_MAX(hsize / 2, vsize / 2);
    bordsize = 32 * ((maxtrans + 31) / 32);  /* full 32 bit words */
    pixsb = pixAddBorder(pixs, bordsize, 0);

    if (vsize == 1) {
        pixt = pixDilate(NULL, pixsb, selh1);
        pixdb = pixDilate(NULL, pixt, selh2);
        pixErode(pixt, pixdb, selh1);
        pixErode(pixdb, pixt, selh2);
    } else if (hsize == 1) {
        pixt = pixDilate(NULL, pixsb, selv1);
        pixdb = pixDilate(NULL, pixt, selv2);
        pixErode(pixt, pixdb, selv1);
        pixErode(pixdb, pixt, selv2);
    } else {  /* do separably */
        pixt = pixDilate(NULL, pixsb, selh1);
        pixdb = pixDilate(NULL, pixt, selh2);
        pixDilate(pixt, pixdb, selv1);
        pixDilate(pixdb, pixt, selv2);
        pixErode(pixt, pixdb, selh1);
        pixErode(pixdb, pixt, selh2);
        pixErode(pixt, pixdb, selv1);
        pixErode(pixdb, pixt, selv2);
    }
    pixDestroy(&pixt);

    pixt = pixRemoveBorder(pixdb, bordsize);
    pixDestroy(&pixsb);
    pixDestroy(&pixdb);

    if (!pixd) {
        pixd = pixt;
    } else {
        pixCopy(pixd, pixt);
        pixDestroy(&pixt);
    }

    selDestroy(&selh1);
    selDestroy(&selh2);
    selDestroy(&selv1);
    selDestroy(&selv2);
    return pixd;
}


/*-----------------------------------------------------------------*
 *           Functions associated with boundary conditions         *
 *-----------------------------------------------------------------*/
/*!
 * \brief   resetMorphBoundaryCondition()
 *
 * \param[in]    bc    SYMMETRIC_MORPH_BC, ASYMMETRIC_MORPH_BC
 * \return  void
 */
void
resetMorphBoundaryCondition(l_int32  bc)
{
    PROCNAME("resetMorphBoundaryCondition");

    if (bc != SYMMETRIC_MORPH_BC && bc != ASYMMETRIC_MORPH_BC) {
        L_WARNING("invalid bc; using asymmetric\n", procName);
        bc = ASYMMETRIC_MORPH_BC;
    }
    MORPH_BC = bc;
    return;
}


/*!
 * \brief   getMorphBorderPixelColor()
 *
 * \param[in]    type L_MORPH_DILATE, L_MORPH_ERODE
 * \param[in]    depth of pix
 * \return  color of border pixels for this operation
 */
l_uint32
getMorphBorderPixelColor(l_int32  type,
                         l_int32  depth)
{
    PROCNAME("getMorphBorderPixelColor");

    if (type != L_MORPH_DILATE && type != L_MORPH_ERODE)
        return ERROR_INT("invalid type", procName, 0);
    if (depth != 1 && depth != 2 && depth != 4 && depth != 8 &&
        depth != 16 && depth != 32)
        return ERROR_INT("invalid depth", procName, 0);

    if (MORPH_BC == ASYMMETRIC_MORPH_BC || type == L_MORPH_DILATE)
        return 0;

        /* Symmetric & erosion */
    if (depth < 32)
        return ((1 << depth) - 1);
    else  /* depth == 32 */
        return 0xffffff00;
}


/*-----------------------------------------------------------------*
 *               Static helpers for arg processing                 *
 *-----------------------------------------------------------------*/
/*!
 * \brief   processMorphArgs1()
 *
 * \param[in]       pixd   [optional]; this can be null, equal to pixs,
 *                         or different from pixs
 * \param[in]       pixs   1 bpp
 * \param[in]       sel
 * \param[out]      ppixt  copy or clone of %pixs
 * \return  pixd, or NULL on error.
 *
 * <pre>
 * Notes:
 *      (1) This is used for generic erosion, dilation and HMT.
 * </pre>
 */
static PIX *
processMorphArgs1(PIX   *pixd,
                  PIX   *pixs,
                  SEL   *sel,
                  PIX  **ppixt)
{
l_int32  sx, sy;

    PROCNAME("processMorphArgs1");

    if (!ppixt)
        return (PIX *)ERROR_PTR("&pixt not defined", procName, pixd);
    *ppixt = NULL;
    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (!sel)
        return (PIX *)ERROR_PTR("sel not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);

    selGetParameters(sel, &sx, &sy, NULL, NULL);
    if (sx == 0 || sy == 0)
        return (PIX *)ERROR_PTR("sel of size 0", procName, pixd);

        /* We require pixd to exist and to be the same size as pixs.
         * Further, pixt must be a copy (or clone) of pixs.  */
    if (!pixd) {
        if ((pixd = pixCreateTemplate(pixs)) == NULL)
            return (PIX *)ERROR_PTR("pixd not made", procName, NULL);
        *ppixt = pixClone(pixs);
    } else {
        pixResizeImageData(pixd, pixs);
        if (pixd == pixs) {  /* in-place; must make a copy of pixs */
            if ((*ppixt = pixCopy(NULL, pixs)) == NULL)
                return (PIX *)ERROR_PTR("pixt not made", procName, pixd);
        } else {
            *ppixt = pixClone(pixs);
        }
    }
    return pixd;
}


/*!
 * \brief   processMorphArgs2()
 *
 *  This is used for generic openings and closings.
 */
static PIX *
processMorphArgs2(PIX   *pixd,
                  PIX   *pixs,
                  SEL   *sel)
{
l_int32  sx, sy;

    PROCNAME("processMorphArgs2");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);
    if (!sel)
        return (PIX *)ERROR_PTR("sel not defined", procName, pixd);
    if (pixGetDepth(pixs) != 1)
        return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, pixd);

    selGetParameters(sel, &sx, &sy, NULL, NULL);
    if (sx == 0 || sy == 0)
        return (PIX *)ERROR_PTR("sel of size 0", procName, pixd);

    if (!pixd)
        return pixCreateTemplate(pixs);
    pixResizeImageData(pixd, pixs);
    return pixd;
}