File size: 18,394 Bytes
55306cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Speech bubble detection: light, outlined, reasonably solid regions."""
import hashlib
from typing import List, Tuple

import numpy as np
from scipy import ndimage as ndi
from scipy.spatial import ConvexHull

try:
    from scipy.spatial import QhullError
except ImportError:  # scipy < 1.8
    from scipy.spatial.qhull import QhullError


class Bubble(object):
    """A detected bubble. Masks are crops; (y0, x0) is the crop origin in the image."""

    def __init__(self, y0, x0, comp, filled, body, color):
        self.y0 = y0
        self.x0 = x0
        self.comp = comp        # light pixels of the bubble
        self.filled = comp if filled is None else filled  # comp with holes (letters) filled
        self.body = body        # filled, with the tail removed
        self.color = color      # median bubble color (r, g, b)
        self.dark = False       # a near-black bubble with a bright outline
        self.outline_color = None  # dark bubbles: the color of that outline
        ys, xs = np.nonzero(body)
        self.cy = y0 + float(ys.mean())
        self.cx = x0 + float(xs.mean())
        self.area = int(self.filled.sum())

    def bbox(self):
        # type: () -> Tuple[int, int, int, int]
        ys, xs = np.nonzero(self.body)
        return (self.x0 + int(xs.min()), self.y0 + int(ys.min()),
                self.x0 + int(xs.max()) + 1, self.y0 + int(ys.max()) + 1)


def luminance(rgb):
    return rgb[..., 0] * 0.299 + rgb[..., 1] * 0.587 + rgb[..., 2] * 0.114


def detect_bubbles(rgb, white_threshold=120, min_area=0.0015, max_area=0.6,

                   min_outline=0.8, rtl=False):
    # type: (np.ndarray, int, float, float, float, bool) -> List[Bubble]
    """Find speech bubbles in an RGB uint8 array.



    A bubble is a flat, unsaturated fill enclosed by a dark outline, with a smooth,

    nearly convex shape. Its brightness does not matter beyond white_threshold: models

    with a muted palette draw gray bubbles, sometimes darker than the wall behind.

    """
    # Finding the bubbles is the slowest step, and the same image is asked about again and
    # again: by arrange() and by draw(), and on every change made in the editor.
    key = (hashlib.md5(np.ascontiguousarray(rgb).tobytes()).hexdigest(), rgb.shape, white_threshold, min_area,
           max_area, min_outline)
    found = _FOUND.get(key)
    if found is None:
        found = [_take_in_letters(item["bubble"]) for item in scan(rgb, white_threshold, min_area, max_area)
                 if is_bubble(item, min_outline)]
        while len(_FOUND) >= 6:
            _FOUND.pop(next(iter(_FOUND)))
        _FOUND[key] = found
    return _reading_order(list(found), rtl)


_FOUND = {}  # the bubbles of the last few images asked about; the Bubble objects are never changed


SMALL = 0.003  # share of the image below which a bubble has to pass the stricter test
SMALL_FLATNESS = 1.2  # a tiny bubble with a word or two: 1.05 on a real one; nothing else that small passed up to 1.2


def _is_dark_bubble(item, min_outline):
    """Near-black bubbles with light letters. Shoes, hair, an open mouth, a hood and shadows are

    dark too; they are less convex (0.65 to 0.87) or open. Measured on 16 scenes asked for dark

    bubbles and 16 of dark and small look-alikes, besides the scenes with light bubbles."""
    near_black = max(item["bubble"].color) <= DARK_BLACK
    shape = (near_black and item["share"] >= DARK_SHARE and item["flatness"] <= 1.3 and item["body"] >= 0.9
             and 0.6 <= item["extent"] < 0.94)
    return ((item["flatness"] <= 2.5 and item["solidity"] >= 0.9
             and 0.45 <= item["extent"] < 0.96 and item["outline"] >= max(min_outline, 0.85)
             and item["body"] >= 0.55 and item["line_contrast"] >= 80.0)
            # On a light ground there is no line of its own to see (the contrast is about 0): the
            # shape has to say it, and the ground has to be light all round.
            or (shape and item["solidity"] >= 0.9 and item["outline"] >= 0.93)
            # A bright line with gaps in it, but a strong one.
            or (shape and item["solidity"] >= 0.88 and item["outline"] >= 0.74 and item["line_contrast"] >= 70.0)
            # Scalloped, so less convex, and closed all round by a strong line.
            or (shape and item["solidity"] >= 0.8 and item["outline"] >= 0.98 and item["line_contrast"] >= 100.0))


DARK_BLACK = 12      # the brightest channel of a dark bubble's fill: they are drawn near black
DARK_SHARE = 0.008   # of the image


def is_bubble(item, min_outline=0.8):
    """Thresholds measured on real generations: they tell a bubble from a pale face,

    an ear, a wall patch or a picture frame, which are also light and outlined.



    Real bubbles there: flatness up to 0.8, outline 0.88 or more, solidity 0.92 or

    more. The nearest look-alikes: flatness 1.5 and up, or outline under 0.8.

    """
    if item["bubble"].dark:
        return _is_dark_bubble(item, min_outline)
    color = item["bubble"].color
    bright = color[0] * 0.299 + color[1] * 0.587 + color[2] * 0.114
    if bright < DIM_FILL and item["outline"] < DIM_OUTLINE:
        # A dim gray fill with a line most of the way round: a face or a wall in a dark
        # scene. The real bubbles of a muted palette are closed all round.
        return False
    if max(color) - min(color) > 32:
        # A tinted fill (cream, beige paper) is also what skin in a dim scene looks like:
        # a face passed as a bubble. Measured on real generations, paper bubbles are
        # bright (181), flat (0.70) and plump with a closed outline; the face was dim
        # (139), less flat (1.18) and less convex (0.89). A cream bubble full of large
        # letters is less flat than that; it passes when it is bright and closed all round.
        if not (sum(color) / 3.0 >= 160 and item["flatness"] <= 0.9 and item["solidity"] >= 0.93
                and item["outline"] >= max(min_outline, 0.9)):
            return (bright >= RAGGED_BRIGHT and item["outline"] >= max(min_outline, RAGGED_OUTLINE)
                    and (_is_smooth(item, min_outline) or _is_ragged(item, min_outline)))
    if item["share"] < SMALL:
        # Small ones (the detector used to stop at SMALL): cuffs, window panes and the
        # insides of big letters are just as flat and outlined. On real generations a
        # small bubble is plump (extent 0.79 and up) with a closed outline; the
        # look-alikes are thinner or more ragged (extent up to 0.67).
        return (item["flatness"] <= SMALL_FLATNESS and item["solidity"] >= 0.95 and 0.7 <= item["extent"] < 0.96
                and item["outline"] >= max(min_outline, 0.95) and item["body"] >= 0.55)
    return _is_smooth(item, min_outline) or _is_ragged(item, min_outline)


SMOOTH_FLATNESS = 1.4  # large letters in a bubble make its fill less flat: 1.33 on a real one


def _is_smooth(item, min_outline):
    return (item["flatness"] <= SMOOTH_FLATNESS and item["solidity"] >= 0.85
            and 0.45 <= item["extent"] < 0.96 and item["outline"] >= min_outline
            and item["body"] >= 0.55)


# A bubble with spikes or scallops (a shout, a burst) is much less convex than a smooth one, so
# it fails the solidity test above. What keeps look-alikes out then is everything else being
# stricter: a clean fill, a closed outline, a size that is not small, and no tint.
# Measured on two corpora of generated scenes: 49 without bubbles, then 16 with jagged, cloud and
# wavy bubbles and 16 without. Real jagged bubbles full of shouted letters measured flatness 1.14
# to 2.02, solidity 0.55 to 0.79, extent 0.40 to 0.65, a line 0.967 to 1.0 of the way round, and
# fills of brightness 205 and up. Nothing in the scenes without bubbles is bright, closed all round
# and that large at once.
RAGGED_SOLIDITY = 0.52  # spikes: the real ones 0.55 to 0.79
RAGGED_FLATNESS = 2.1   # large letters fill a shout: up to 2.02 on a real one
RAGGED_EXTENT = 0.38    # long spikes leave much of the box empty: 0.40 on a real one
RAGGED_OUTLINE = 0.96   # a line right round it: 0.967 and up on the real ones
RAGGED_SHARE = 0.009    # of the image: a spiky speck is a splash of foam, a star, a cuff
RAGGED_BRIGHT = 190     # the fill's brightness: a pale wall or skin in shade is darker
RAGGED_BODY = 0.6
RAGGED_ASPECT = 3.0     # the longer side of its box over the shorter: 1.85 at most on the real ones, 4.5 on a
                        # strip of white ground between an arm and a dark dress
DIM_FILL = 185          # a fill darker than this ...
DIM_OUTLINE = 0.95      # ... has to be closed all round: dim false finds (faces, a wall) had 0.82 to 0.93,
                        # the real dim bubbles 0.99 and 1.0


def _is_ragged(item, min_outline):
    """A bright, flat, closed bubble that is not convex. Measured on generated scenes without

    any bubble (white dresses with lace, foam, clouds, fur, stickers, starbursts), none passes;

    spiky bubbles, drawn and generated, do."""
    color = item["bubble"].color
    bright = color[0] * 0.299 + color[1] * 0.587 + color[2] * 0.114
    ys, xs = np.nonzero(item["bubble"].filled)
    height, width = ys.max() - ys.min() + 1, xs.max() - xs.min() + 1
    if max(height, width) > RAGGED_ASPECT * min(height, width):
        return False  # a strip of white ground between an arm and a dark dress, not a shout
    return (item["share"] >= RAGGED_SHARE and item["flatness"] <= RAGGED_FLATNESS
            and item["solidity"] >= RAGGED_SOLIDITY and RAGGED_EXTENT <= item["extent"] < 0.96
            and item["outline"] >= max(min_outline, RAGGED_OUTLINE) and item["body"] >= RAGGED_BODY
            and bright >= RAGGED_BRIGHT)


def _reading_order(bubbles, rtl):
    """Rows top to bottom; bubbles that overlap vertically share a row."""
    rows = []
    for bubble in sorted(bubbles, key=lambda b: b.cy):
        if rows:
            _, top, _, bottom = rows[-1][0].bbox()
            if top <= bubble.cy < bottom:
                rows[-1].append(bubble)
                continue
        rows.append([bubble])
    ordered = []
    for row in rows:
        ordered.extend(sorted(row, key=lambda b: -b.cx if rtl else b.cx))
    return ordered


def _solidity(mask):
    """Area of the mask divided by the area of its convex hull."""
    ys, xs = np.nonzero(mask ^ ndi.binary_erosion(mask))
    try:
        hull = ConvexHull(np.stack([xs, ys], axis=1)).volume
    except (QhullError, ValueError):
        return 0.0
    return float(mask.sum()) / hull if hull > 0 else 0.0


# How far apart the color channels of a light fill may be. Paper-colored bubbles (cream,
# beige) reach the mid thirties; skin starts around sixty.
MAX_TINT = 48


def scan(rgb, floor=120, min_area=0.0015, max_area=0.6, ceiling=60):
    """Yield every flat region that could be a bubble, with the measurements used to judge it.



    Two kinds are looked for: a light, unsaturated fill inside a dark outline, and a

    near-black fill (darker than `ceiling`) inside a bright outline.

    """
    lum = luminance(rgb.astype(np.float32))
    mn = rgb.min(axis=2)
    mx = rgb.max(axis=2)
    smooth = (ndi.maximum_filter(lum, size=3) - ndi.minimum_filter(lum, size=3)) <= 8.0
    light = smooth & ((mx.astype(np.int16) - mn) <= MAX_TINT) & (lum >= floor)
    for item in _scan_pass(rgb, lum, light, False, min_area, max_area):
        yield item
    for item in _scan_pass(rgb, lum, smooth & (lum <= ceiling), True, min_area, max_area):
        yield item


def _scan_pass(rgb, lum, flat, dark_fill, min_area, max_area):
    h, w = rgb.shape[:2]
    labels, count = ndi.label(flat)
    if count == 0:
        return
    areas = np.bincount(labels.ravel())
    total = h * w
    for idx, sl in enumerate(ndi.find_objects(labels), start=1):
        area = int(areas[idx])
        if area < total * min_area * 0.6 or area > total * max_area:
            continue
        ring_w = max(3, int(0.015 * np.sqrt(area)))
        pad = 2 * ring_w + 12
        y0 = max(0, sl[0].start - pad)
        y1 = min(h, sl[0].stop + pad)
        x0 = max(0, sl[1].start - pad)
        x1 = min(w, sl[1].stop + pad)
        comp = labels[y0:y1, x0:x1] == idx
        filled = ndi.binary_fill_holes(comp)
        filled_area = int(filled.sum())
        if filled_area < total * min_area:
            continue
        pixels = rgb[y0:y1, x0:x1][comp]
        color = tuple(int(v) for v in np.median(pixels, axis=0))
        fill_lum = color[0] * 0.299 + color[1] * 0.587 + color[2] * 0.114
        ys, xs = np.nonzero(filled)
        box = (ys.max() - ys.min() + 1) * (xs.max() - xs.min() + 1)
        # Outline: the share of the perimeter that has a line right next to it: a dark
        # line around a light bubble, a bright one around a dark bubble.
        # Measured along the edge, not by ring area, so a thin line counts in full.
        # Where the region runs into the image border there is no line: that part
        # counts as open.
        reach = ring_w + 3
        band = ndi.binary_dilation(filled, iterations=reach) & ~filled
        if dark_fill:
            line = band & (lum[y0:y1, x0:x1] > fill_lum + 70.0)
        else:
            line = band & (lum[y0:y1, x0:x1] < min(110.0, fill_lum - 40.0))
        edge = ndi.binary_dilation(filled) & ~filled
        covered = int((ndi.binary_dilation(line, iterations=reach) & edge).sum())
        # Is it a line, or just a different background? Compare its color with what
        # lies further out. A black shoe on a light floor has no line around it.
        contrast = 0.0
        beyond = (ndi.binary_dilation(filled, iterations=2 * reach + 2)
                  & ~ndi.binary_dilation(filled, iterations=reach + 1))
        if line.any() and beyond.any():
            crop = rgb[y0:y1, x0:x1].astype(np.float32)
            contrast = float(np.linalg.norm(np.median(crop[line], axis=0) - np.median(crop[beyond], axis=0)))
        on_border = 0
        if y0 == 0:
            on_border += int(filled[0].sum())
        if y1 == h:
            on_border += int(filled[-1].sum())
        if x0 == 0:
            on_border += int(filled[:, 0].sum())
        if x1 == w:
            on_border += int(filled[:, -1].sum())
        perimeter = int(edge.sum()) + on_border
        outline = covered / float(perimeter) if perimeter else 0.0
        body = _body(filled)
        if body is None:
            continue
        bubble = Bubble(y0, x0, comp, filled, body, color)
        if dark_fill:
            bubble.dark = True
            if line.any():
                bubble.outline_color = tuple(int(v) for v in np.median(rgb[y0:y1, x0:x1][line], axis=0))
        yield {
            "bubble": bubble,
            "share": filled_area / float(total),
            "flatness": float(pixels.mean(axis=1).std()),
            "solidity": _solidity(filled),
            "extent": filled_area / float(box),
            "outline": outline,
            "line_contrast": contrast,
            "body": float(body.sum()) / filled_area,
        }


def _body(filled):
    """The bubble without its tail: what survives an opening with a large radius, or None."""
    radius = max(2.0, 0.10 * np.sqrt(float(filled.sum())))
    dist = ndi.distance_transform_edt(np.pad(filled, 1))[1:-1, 1:-1]
    core = dist > radius
    core_labels, core_count = ndi.label(core)
    if core_count == 0:
        return None
    if core_count > 1:
        sizes = np.bincount(core_labels.ravel())
        sizes[0] = 0
        core = core_labels == int(sizes.argmax())
    return (ndi.distance_transform_edt(~core) <= radius) & filled


LETTER_STROKE = 0.12   # of the square root of a bubble's area: the widest letter stroke closed over
BAY_OPEN = 0.12        # the share of a bay's edge that may face away from the bubble: 0.25 took in gaps between spikes


def _take_in_letters(bubble):
    # type: (Bubble) -> Bubble
    """The bubble with the letters that touch its outline taken in. Such a letter is not a hole

    in the fill, so it was left on the page and the text had to keep off it; a shout drawn with

    huge letters had almost no room left. A letter makes a bay in the fill: narrow strokes, with

    fill on nearly every side. The gaps between the spikes of a jagged outline are open to the

    outside instead, and stay out."""
    filled = bubble.filled
    r = max(2, int(round(LETTER_STROKE * np.sqrt(float(filled.sum())))))
    yy, xx = np.ogrid[-r:r + 1, -r:r + 1]
    disk = xx * xx + yy * yy <= r * r
    padded = np.pad(filled, r + 1)
    closed = ndi.binary_fill_holes(ndi.binary_closing(padded, structure=disk))[r + 1:-(r + 1), r + 1:-(r + 1)]
    bays = closed & ~filled
    if not bays.any():
        return bubble
    labels, count = ndi.label(bays)
    outside = ~closed
    taken = np.zeros_like(filled)
    for index in range(1, count + 1):
        bay = labels == index
        edge = ndi.binary_dilation(bay) & ~bay
        if edge.any() and (edge & outside).sum() <= BAY_OPEN * edge.sum():
            taken |= bay
    if not taken.any():
        return bubble
    grown = ndi.binary_fill_holes(filled | taken)
    body = _body(grown)
    if body is None:
        return bubble
    wider = Bubble(bubble.y0, bubble.x0, bubble.comp, grown, body, bubble.color)
    wider.dark, wider.outline_color = bubble.dark, bubble.outline_color
    return wider


def erase_letters(rgb, bubble):
    """Paint over everything enclosed by the bubble (the model's letters). In place."""
    holes = bubble.filled & ~bubble.comp
    if not holes.any():
        return
    paint = ndi.binary_dilation(holes, iterations=2) & bubble.filled
    h, w = paint.shape
    region = rgb[bubble.y0:bubble.y0 + h, bubble.x0:bubble.x0 + w]
    region[paint] = bubble.color


def edge_energy(rgb, y0, y1):
    """Mean gradient magnitude of a horizontal band: low means a calm area."""
    lum = luminance(rgb[y0:y1].astype(np.float32))
    if lum.shape[0] < 2 or lum.shape[1] < 2:
        return 0.0
    return float(np.abs(np.diff(lum, axis=0)).mean() + np.abs(np.diff(lum, axis=1)).mean())