File size: 64,015 Bytes
2a261b0 | 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 | """Replace gibberish text drawn inside a picture: find it, erase it, write over it.
All functions take and return RGB uint8 arrays. Nothing here knows about the host.
"""
import copy
from typing import List, Optional, Sequence, Tuple
import cv2
import numpy as np
from PIL import Image, ImageChops, ImageDraw, ImageFont
class Selection(object):
"""One line of text found in the image.
mask bool array of the image's size: the pixels of the letters
quad 4x2 float array, the straight box around the text: top left, top right,
bottom right, bottom left, as the text reads
color color of the letters (r, g, b)
along, down unit vectors of the box: the way the text runs, and across it
start where the text begins, measured along `along`
top, bottom polynomials of the distance from `start`: the upper and the lower edge
of the letters, measured along `down`. Straight text gives constants, text
that grows or shrinks gives lines, text on a bent surface gives parabolas.
"""
def __init__(self, mask, quad, color, along, down, start, top, bottom):
self.mask = mask
self.quad = quad
self.color = color
self.along = along
self.down = down
self.start = start
self.top = top
self.bottom = bottom
self.score = 0.0
# What erasing goes by: the height and the area of the old letters. They differ from
# height() and outline_points() once the place for the new text is set by hand, or
# when several lines are taken as one block.
self.letters = None # type: Optional[float]
self.letters_outline = None # type: Optional[np.ndarray]
def letters_height(self):
return self.letters if self.letters is not None else self.height()
def letters_area(self):
return self.letters_outline if self.letters_outline is not None else self.outline_points()
def carry(self, other):
"""Take over the letters' own size and area from the selection this one was made from."""
self.letters = other.letters_height()
self.letters_outline = other.letters_area()
return self
def width(self):
return float(np.linalg.norm(self.quad[1] - self.quad[0]))
def height(self):
"""The middle height of the letters."""
steps = np.linspace(0.0, self.width(), 16)
return float(np.median(np.polyval(self.bottom, steps) - np.polyval(self.top, steps)))
def outline_points(self, steps=24):
"""The edge of the text's area as a closed polygon, following its bend."""
along_steps = np.linspace(0.0, self.width(), steps)
upper = [(self.start + s, np.polyval(self.top, s)) for s in along_steps]
lower = [(self.start + s, np.polyval(self.bottom, s)) for s in along_steps[::-1]]
return np.array([self.along * a + self.down * d for a, d in upper + lower], np.float64)
def contains(self, x, y):
polygon = np.round(self.outline_points()).astype(np.int32)
return cv2.pointPolygonTest(polygon, (float(x), float(y)), False) >= 0
def shape_of(selection):
# type: (Selection) -> Tuple[np.ndarray, float]
"""The selection as the editor's handles show it: four corners (top left, top right,
bottom right, bottom left, as the text reads) and a bend. The bend is how far the
middle of the line lies above the straight line between its ends, in pixels."""
wide = selection.width()
ends = np.array([0.0, wide])
top = np.polyval(selection.top, ends)
bottom = np.polyval(selection.bottom, ends)
a = selection.start + ends
corners = np.array([selection.along * a[0] + selection.down * top[0],
selection.along * a[1] + selection.down * top[1],
selection.along * a[1] + selection.down * bottom[1],
selection.along * a[0] + selection.down * bottom[0]])
middle = wide / 2.0
straight_top = (top[0] + top[1]) / 2.0
straight_bottom = (bottom[0] + bottom[1]) / 2.0
bend = ((straight_top - np.polyval(selection.top, middle))
+ (straight_bottom - np.polyval(selection.bottom, middle))) / 2.0
return corners, float(bend)
def reshape(selection, corners, bend=0.0):
# type: (Selection, Sequence[Sequence[float]], float) -> Selection
"""The same letters to erase, with the place for the new text set by hand: four corners
as the text reads, and a bend that lifts the middle of the line (or lowers it, when
negative). The top edge runs from the first corner to the second; the bottom edge from
the fourth to the third, so the text may grow or shrink along the line."""
c = np.asarray(corners, np.float64).reshape(4, 2)
along = c[1] - c[0]
wide = float(np.linalg.norm(along))
if wide < 2:
return selection
along = along / wide
down = np.array([-along[1], along[0]])
start = float(c[0] @ along)
top_d = float(c[0] @ down)
a3, d3 = float(c[3] @ along) - start, float(c[3] @ down)
a2, d2 = float(c[2] @ along) - start, float(c[2] @ down)
slope = (d2 - d3) / (a2 - a3) if abs(a2 - a3) > 1e-6 else 0.0
curve = np.array([4.0 * bend / wide ** 2, -4.0 * bend / wide, 0.0]) # 0 at the ends, -bend in the middle
top = curve + np.array([0.0, 0.0, top_d])
bottom = curve + np.array([0.0, slope, d3 - slope * a3])
steps = np.linspace(0.0, wide, 9)
if (np.polyval(bottom, steps) - np.polyval(top, steps)).min() < 2:
return selection # turned inside out: keep what there was
return Selection(selection.mask, c, selection.color, along, down, start, top, bottom).carry(selection)
def join(selections):
# type: (Sequence[Optional[Selection]]) -> Optional[Selection]
"""Several lines taken as one block (the lines of a speech bubble, of a sign): their
letters together, in one straight box along the first line. The new text for it may
have line breaks."""
selections = [selection for selection in selections if selection is not None]
if not selections:
return None
if len(selections) == 1:
return selections[0]
first = selections[0]
mask = np.zeros_like(first.mask)
for selection in selections:
mask |= selection.mask
ys, xs = np.nonzero(mask)
points = np.stack([xs, ys], axis=1).astype(np.float64)
a, d = points @ first.along, points @ first.down
start, wide = float(a.min()), float(a.max() + 1 - a.min())
top, bottom = float(d.min()), float(d.max() + 1)
quad = np.array([first.along * p + first.down * q for p, q in
[(start, top), (start + wide, top), (start + wide, bottom), (start, bottom)]])
block = Selection(mask, quad, first.color, first.along, first.down, start, np.array([top]), np.array([bottom]))
# Erasing goes by the height of one line, not of the whole block, and by the area of the
# lines themselves.
block.letters = float(np.median([selection.letters_height() for selection in selections]))
outlines = [np.round(selection.letters_area()).astype(np.int32) for selection in selections]
hull = cv2.convexHull(np.concatenate(outlines).reshape(-1, 1, 2))
block.letters_outline = hull.reshape(-1, 2).astype(np.float64)
return block
def paint(selection, strokes):
# type: (Selection, Sequence[Tuple[Sequence[Sequence[float]], float]]) -> Selection
"""More to erase with the letters: brush strokes, each (points, radius)."""
if not strokes:
return selection
mask = selection.mask.astype(np.uint8)
for points, radius in strokes:
line = np.round(np.asarray(points, np.float64)).astype(np.int32).reshape(-1, 1, 2)
size = max(1, int(round(radius)))
if len(line) > 1:
cv2.polylines(mask, [line], False, 1, 2 * size, cv2.LINE_8)
for point in (line[0, 0], line[-1, 0]):
cv2.circle(mask, (int(point[0]), int(point[1])), size, 1, -1)
return Selection(mask > 0, selection.quad, selection.color, selection.along, selection.down, selection.start,
selection.top, selection.bottom).carry(selection)
class PathSelection(Selection):
"""The same letters to erase, with the new text written along a path drawn by hand: a
polyline through the middle of the new letters, from where the text starts to where it
ends. The letters keep the old ones' height."""
def __init__(self, selection, path, tall):
ends = path[-1] - path[0]
span = float(np.linalg.norm(ends))
along = ends / span if span > 1e-6 else np.array([1.0, 0.0])
down = np.array([-along[1], along[0]])
start = float(path[0] @ along)
middle = float(np.median(path @ down))
top, bottom = middle - tall / 2.0, middle + tall / 2.0
quad = np.array([along * start + down * top, along * (start + span) + down * top,
along * (start + span) + down * bottom, along * start + down * bottom])
Selection.__init__(self, selection.mask, quad, selection.color, along, down, start,
np.array([top]), np.array([bottom]))
self.carry(selection)
self.path = path
self.tall = float(tall)
self.length = float(np.sum(np.linalg.norm(np.diff(path, axis=0), axis=1)))
def width(self):
return self.length
def height(self):
return self.tall
def outline_points(self, steps=24):
"""The path widened to the letters' height on both sides."""
pick = np.linspace(0, len(self.path) - 1, min(len(self.path), max(steps, 2))).round().astype(int)
points = self.path[pick]
ahead = np.gradient(points, axis=0)
ahead /= np.maximum(np.linalg.norm(ahead, axis=1, keepdims=True), 1e-6)
side = np.stack([-ahead[:, 1], ahead[:, 0]], axis=1) * (self.tall / 2.0)
return np.concatenate([points - side, (points + side)[::-1]])
def follow_path(selection, points):
# type: (Selection, Sequence[Sequence[float]]) -> Selection
"""Write the new text along a path drawn by hand instead of where the old text was."""
path = np.asarray(points, np.float64).reshape(-1, 2)
if len(path) < 2:
return selection
tall = selection.letters_height()
# Even steps along the path, then smoothed, so that a shaky hand does not shake the letters.
lengths = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(path, axis=0), axis=1))])
if lengths[-1] < max(4.0, tall):
return selection
step = max(1.5, tall / 8.0)
at = np.linspace(0.0, lengths[-1], max(2, int(lengths[-1] / step) + 1))
even = np.stack([np.interp(at, lengths, path[:, 0]), np.interp(at, lengths, path[:, 1])], axis=1)
if len(even) > 4:
width = 5
padded = np.concatenate([np.repeat(even[:1], width // 2, 0), even, np.repeat(even[-1:], width // 2, 0)])
kernel = np.ones(width) / width
smooth = np.stack([np.convolve(padded[:, k], kernel, mode="valid") for k in range(2)], axis=1)
smooth[0], smooth[-1] = even[0], even[-1]
even = smooth
return PathSelection(selection, even, tall)
def warp(selection, grid):
# type: (Selection, Sequence) -> Selection
"""Bend the new letters by hand: a grid of moves (rows x columns of (dx, dy) in pixels)
spread evenly over the text, the first row along its top and the last along its bottom.
Between the grid points the moves blend smoothly."""
moves = np.asarray(grid, np.float64)
if moves.ndim != 3 or moves.shape[0] < 2 or moves.shape[1] < 2 or moves.shape[2] != 2:
return selection
if not np.abs(moves).any():
return selection
out = copy.copy(selection)
out.warp = moves
return out
def _passes(gray, side):
"""Thin marks that stand out from what is around them, looked for four ways: light on
dark and dark on light, at two stroke widths. Yields (kernel, light, mask)."""
base = int(max(9, 0.03 * side)) | 1
for kernel in (base, base * 2 + 1):
shape = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel, kernel))
wide = np.ones((kernel * 4 + 1, kernel * 4 + 1), np.uint8)
for light, op in ((True, cv2.MORPH_TOPHAT), (False, cv2.MORPH_BLACKHAT)):
response = cv2.morphologyEx(gray, op, shape)
# A mark counts when it is strong next to the strongest thing near it.
level = np.maximum(28.0, 0.45 * cv2.dilate(response, wide).astype(np.float32))
yield kernel, light, response > level
def _colors(rgb, labels, count):
"""Mean color of every labelled mark, n x 3."""
flat = labels.ravel()
sizes = np.maximum(np.bincount(flat, minlength=count), 1).astype(np.float64)
return np.stack([np.bincount(flat, weights=rgb[..., c].ravel(), minlength=count) / sizes for c in range(3)],
axis=1)
def _line_of(boxes, colors, usable, seed):
"""The letters standing in one line with the seed letter: marks of its height and its
color, side by side. boxes: n x 4 (x, y, w, h); colors: n x 3."""
used = ~usable
used[seed] = True
group = [seed]
queue = [seed]
right = boxes[:, 0] + boxes[:, 2]
lower = boxes[:, 1] + boxes[:, 3]
while queue:
j = queue.pop()
tall = float(np.median(boxes[group, 3]))
x, y, w, h = boxes[j]
gap = np.maximum(boxes[:, 0], x) - np.minimum(right, x + w)
overlap = (np.minimum(lower, y + h) - np.maximum(boxes[:, 1], y)) / np.minimum(boxes[:, 3], h)
alike = np.abs(colors - np.median(colors[group], axis=0)).max(axis=1) <= 45
fits = (~used & alike & (gap <= 0.9 * tall) & (overlap >= 0.4) & (boxes[:, 3] >= 0.4 * tall)
& (boxes[:, 3] <= 2.2 * tall) & (boxes[:, 2] <= 6 * tall))
for i in np.nonzero(fits)[0]:
used[i] = True
group.append(int(i))
queue.append(int(i))
return group
def _contrast(gray, letters, boxes):
"""How much the letters differ from what lies around the whole line.
This is what tells letters from the gaps between them: the gaps between light letters
are dark marks too, and just as regular, but they have the color of the surroundings.
"""
tall = float(np.median(boxes[:, 3]))
x0, y0 = boxes[:, 0].min(), boxes[:, 1].min()
x1, y1 = (boxes[:, 0] + boxes[:, 2]).max(), (boxes[:, 1] + boxes[:, 3]).max()
# A narrow band right around the line: text often sits on a plate or a patch of its
# own, and what lies beyond that is not what the letters were written on.
inner = 0.08 * tall
outer = inner + max(3.0, 0.25 * tall)
height, width = gray.shape
oy0, oy1 = int(max(0, y0 - outer)), int(min(height, y1 + outer))
ox0, ox1 = int(max(0, x0 - outer)), int(min(width, x1 + outer))
ring = np.ones((oy1 - oy0, ox1 - ox0), bool)
iy0, iy1 = int(max(0, y0 - inner)) - oy0, int(min(height, y1 + inner)) - oy0
ix0, ix1 = int(max(0, x0 - inner)) - ox0, int(min(width, x1 + inner)) - ox0
ring[iy0:iy1, ix0:ix1] = False
around = gray[oy0:oy1, ox0:ox1][ring]
if not around.size:
return 0.0
return abs(float(np.median(gray[letters])) - float(np.median(around)))
def _fit(along, values, degree, tall):
coeffs = np.polyfit(along, values, degree)
off = np.abs(values - np.polyval(coeffs, along))
keep = off <= max(1.5, 0.2 * tall)
if keep.sum() < degree + 2:
# Too few letters agree to leave the rest out: the fit stays the one of all of them,
# and all of them count. (With none agreeing, there would be nothing to measure by.)
return coeffs, np.ones(len(values), bool)
if not keep.all():
coeffs = np.polyfit(along[keep], values[keep], degree)
return coeffs, keep
def _edges(centers, tops, bottoms, width):
"""Upper and lower edge of a line of letters as polynomials of the place in the line."""
flat = (np.array([tops.min()]), np.array([bottoms.max()]))
count = len(centers)
if count < 3:
return flat
tall = float(np.median(bottoms - tops))
degree = 2 if count >= 5 else 1
while True:
top, kept_top = _fit(centers, tops, degree, tall)
bottom, kept_bottom = _fit(centers, bottoms, degree, tall)
if degree == 2 and max(abs(top[0]), abs(bottom[0])) * width * width / 4.0 < 0.06 * tall:
degree = 1 # no bend worth following
continue
break
# Move the edges out until every letter that agreed with them lies inside.
top = top.copy()
bottom = bottom.copy()
top[-1] -= max(0.0, float((np.polyval(top, centers) - tops)[kept_top].max()))
bottom[-1] += max(0.0, float((bottoms - np.polyval(bottom, centers))[kept_bottom].max()))
steps = np.linspace(0.0, width, 16)
if (np.polyval(bottom, steps) - np.polyval(top, steps)).min() < 0.4 * tall:
return flat
return top, bottom
def _selection(rgb, mask, light, color=None):
"""A Selection from the pixels of its letters."""
ys, xs = np.nonzero(mask)
y0, x0 = int(ys.min()), int(xs.min())
crop = mask[y0:ys.max() + 1, x0:xs.max() + 1]
count, labels = cv2.connectedComponents(crop.astype(np.uint8), connectivity=8)
points = np.stack([xs, ys], axis=1).astype(np.float64)
which = labels[ys - y0, xs - x0]
# The way the text runs. A line of text is long and low, so the tightest box around it
# lies along the line; a short word gives no such hint and is taken as level.
along = np.array([1.0, 0.0])
(_cx, _cy), (rect_w, rect_h), _angle = rect = cv2.minAreaRect(points.astype(np.float32))
if max(rect_w, rect_h) >= 1.8 * max(min(rect_w, rect_h), 1.0):
box = cv2.boxPoints(rect).astype(np.float64)
first, second = box[1] - box[0], box[2] - box[1]
along = first if np.linalg.norm(first) >= np.linalg.norm(second) else second
along /= max(np.linalg.norm(along), 1e-6)
if along[0] < 0:
along = -along
down = np.array([-along[1], along[0]])
a = points @ along
d = points @ down
start = float(a.min())
width = float(a.max() + 1 - start)
order = np.argsort(which, kind="stable")
_, firsts = np.unique(which[order], return_index=True)
a_sorted, d_sorted = a[order], d[order]
sizes = np.diff(np.append(firsts, len(order)))
big = sizes >= 4
centers = (np.add.reduceat(a_sorted, firsts) / sizes - start)[big]
tops = np.minimum.reduceat(d_sorted, firsts)[big]
bottoms = (np.maximum.reduceat(d_sorted, firsts) + 1)[big]
if len(centers):
top, bottom = _edges(centers, tops, bottoms, width)
else:
top, bottom = np.array([d.min()]), np.array([d.max() + 1])
corners = [(start, d.min()), (start + width, d.min()), (start + width, d.max() + 1), (start, d.max() + 1)]
quad = np.array([along * p + down * q for p, q in corners], np.float64)
if color is None:
# The heart of the strokes: their edges are mixed with the background.
ink = rgb[ys, xs]
gray = ink @ np.array([0.299, 0.587, 0.114])
strong = gray >= np.percentile(gray, 60) if light else gray <= np.percentile(gray, 40)
color = tuple(int(v) for v in np.median(ink[strong], axis=0))
return Selection(mask, quad, color, along, down, start, top, bottom)
def locate(rgb, x, y, reach=0.3, add_to=None):
# type: (np.ndarray, int, int, float, Optional[Selection]) -> Optional[Selection]
"""Find the line of text at the clicked point. None when nothing text-like is there.
reach is the share of the image's shorter side searched to each side of the click.
add_to joins what is found to an earlier selection (a missed letter, a second word).
"""
height, width = rgb.shape[:2]
span = int(max(64, reach * min(height, width)))
while True:
x0, y0 = max(0, x - span), max(0, y - span)
x1, y1 = min(width, x + span + 1), min(height, y + span + 1)
best, too_long = _locate_in(rgb, x, y, (x0, y0, x1, y1))
if best is None:
if too_long and span < max(height, width):
span *= 2 # the line fills the window from side to side: it needs a larger one
continue
return add_to
# A line that comes close to the edge of the searched window may go on beyond it,
# and its last letter may be cut there: look again in a larger window.
ys, xs = np.nonzero(best[1])
room = 1.5 * min(xs.max() - xs.min() + 1, ys.max() - ys.min() + 1)
cut = ((x0 > 0 and xs.min() < room) or (y0 > 0 and ys.min() < room)
or (x1 < width and xs.max() > x1 - x0 - 1 - room) or (y1 < height and ys.max() > y1 - y0 - 1 - room))
if not cut or span >= max(height, width):
break
span *= 2
full = np.zeros((height, width), bool)
full[y0:y1, x0:x1] = best[1]
if add_to is not None:
# The user said this belongs to the line: no test of its looks.
return _selection(rgb, full | add_to.mask, best[2], add_to.color)
selection = _selection(rgb, full, best[2])
return selection if _looks_like_text(selection, min(height, width)) else None
def _looks_like_text(selection, side):
"""Whether a selection made from a click looks like a line of text at all.
A click on a face, a fold or a patch of grass also finds marks that stand out. A line of
text differs from those in ways that are easy to measure: it is several marks rather
than one, of about one height; they fill a fair share of their box; the box is wider
than tall and not huge next to the picture.
"""
count, _labels, stats, _ = cv2.connectedComponentsWithStats(selection.mask.astype(np.uint8), connectivity=8)
areas = stats[1:, cv2.CC_STAT_AREA]
if not len(areas):
return False
marks = areas >= max(8, 0.02 * areas.max())
heights = stats[1:, cv2.CC_STAT_HEIGHT][marks]
wide, tall = selection.width(), max(1.0, selection.height())
cover = selection.mask.sum() / max(1.0, wide * tall)
return bool(marks.sum() >= 2 and cover >= 0.12 and wide >= 1.2 * tall and tall <= 0.25 * side
and float(np.std(heights)) <= 0.33 * float(np.mean(heights)))
def _locate_in(rgb, x, y, window_box):
"""The line of text at (x, y), looked for inside the window. Returns (answer, too_long):
the answer is (contrast, mask of the window's size, light) or None; too_long says that
something at the click ran through the whole window and was passed over for that."""
x0, y0, x1, y1 = window_box
side = min(rgb.shape[:2])
window = np.ascontiguousarray(rgb[y0:y1, x0:x1])
gray = cv2.cvtColor(window, cv2.COLOR_RGB2GRAY)
cx, cy = x - x0, y - y0
best = None
too_long = False
for kernel, light, mask in _passes(gray, side):
count, labels, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
if count < 2:
continue
# The letter under the click, or the nearest one within a letter's reach: a click
# meant for a word often lands in the gap between two letters.
near = kernel
patch = labels[max(0, cy - near):cy + near + 1, max(0, cx - near):cx + near + 1]
ys, xs = np.nonzero(patch)
if not len(ys):
continue
oy, ox = min(cy, near), min(cx, near)
nearest = int(np.argmin((ys - oy) ** 2 + (xs - ox) ** 2))
seed = int(patch[ys[nearest], xs[nearest]])
boxes = stats[:, :4].astype(np.float64)
if boxes[seed, 2] > 0.8 * gray.shape[1] or boxes[seed, 3] > 0.8 * gray.shape[0]:
too_long = True
continue # not a letter: an edge that runs through the whole window
usable = stats[:, cv2.CC_STAT_AREA] >= 4
usable[0] = False
group = _line_of(boxes, _colors(window, labels, count), usable, seed)
letters = np.isin(labels, group)
mine = boxes[group]
reach = max((mine[:, 0] + mine[:, 2]).max() - mine[:, 0].min(), (mine[:, 1] + mine[:, 3]).max() - mine[:, 1].min())
if reach < 0.6 * kernel:
continue # a speck: a glint inside a letter is a mark too, but it is not the text
contrast = _contrast(gray, letters, mine)
if contrast >= 25 and (best is None or contrast > best[0] * 1.15):
best = (contrast, letters, light)
return best, too_long
def find_all(rgb, limit=12):
# type: (np.ndarray, int) -> List[Selection]
"""Every line of text the picture seems to hold, top to bottom.
Without a click to start from, a line has to look like text by itself: at least three
marks of one height and one color in a row, clearly unlike what surrounds them. Short
or faint text is missed, and now and then a row of buttons or rivets is taken for text.
"""
height, width = rgb.shape[:2]
side = min(height, width)
gray = cv2.cvtColor(np.ascontiguousarray(rgb), cv2.COLOR_RGB2GRAY)
found = []
for _kernel, light, mask in _passes(gray, side):
count, labels, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8)
boxes = stats[:, :4].astype(np.float64)
area = stats[:, cv2.CC_STAT_AREA]
usable = ((area >= 12) & (boxes[:, 3] >= 7) & (boxes[:, 3] <= 0.3 * side) & (boxes[:, 2] <= 0.5 * side))
usable[0] = False
if usable.sum() > 1500: # a very busy picture: the larger marks only
usable &= area >= np.sort(area[usable])[-1500]
taken = np.zeros(count, bool)
colors = _colors(rgb, labels, count)
for seed in np.nonzero(usable)[0][np.argsort(boxes[usable, 0])]:
if taken[seed]:
continue
group = _line_of(boxes, colors, usable & ~taken, int(seed))
taken[group] = True
if len(group) < 3:
continue
mine = boxes[group]
tall = float(np.median(mine[:, 3]))
if np.std(mine[:, 3]) > 0.35 * tall:
continue
x0, y0 = int(mine[:, 0].min()), int(mine[:, 1].min())
x1, y1 = int((mine[:, 0] + mine[:, 2]).max()), int((mine[:, 1] + mine[:, 3]).max())
if (x1 - x0) < 1.5 * (y1 - y0):
continue
letters = np.isin(labels[y0:y1, x0:x1], group)
cover = letters.mean()
if not 0.08 <= cover <= 0.75:
continue
solid = float(np.mean(area[group] / (mine[:, 2] * mine[:, 3])))
if solid > 0.85 or solid < 0.18:
continue # blocks, or bits of a thin outline: not letters
if (mine[:, 2] > 4 * tall).any():
continue # a long stroke among them: an edge of something
# Letters of one line are written with one pen: their strokes are equally thick.
depth = cv2.distanceTransform(letters.astype(np.uint8), cv2.DIST_L2, 3)
inside = labels[y0:y1, x0:x1][letters]
sums = np.bincount(inside, weights=depth[letters], minlength=count)[group]
strokes = sums / area[group]
if tall >= 16 and np.std(strokes) > 0.35 * np.mean(strokes):
continue # (in tiny text the strokes are a pixel or two: too coarse to compare)
full = np.zeros((height, width), bool)
full[y0:y1, x0:x1] = letters
contrast = _contrast(gray, full, mine)
if contrast < (45 if len(group) >= 4 else 90):
continue # three marks in a row are text only when they stand out strongly
selection = _selection(rgb, full, light)
selection.score = contrast * np.sqrt(len(group))
found.append(selection)
# The same line is found more than once, by different passes: the best of each stays.
found.sort(key=lambda item: -item.score)
kept = []
for selection in found:
center = selection.quad.mean(axis=0)
if any(other.contains(center[0], center[1]) or selection.contains(*other.quad.mean(axis=0))
for other in kept):
continue
kept.append(selection)
if len(kept) >= limit:
break
kept.sort(key=lambda item: (item.quad[:, 1].mean(), item.quad[:, 0].mean()))
return kept
def erase(rgb, selection):
# type: (np.ndarray, Selection) -> np.ndarray
"""Paint the letters over with what surrounds them."""
tall = selection.letters_height()
grow = int(max(2, round(0.12 * tall)))
letters = selection.mask
mask = cv2.dilate(letters.astype(np.uint8),
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * grow + 1, 2 * grow + 1)))
ys, xs = np.nonzero(mask)
pad = grow * 6 + 8
y0, y1 = max(0, ys.min() - pad), min(rgb.shape[0], ys.max() + pad + 1)
x0, x1 = max(0, xs.min() - pad), min(rgb.shape[1], xs.max() + pad + 1)
window = np.ascontiguousarray(rgb[y0:y1, x0:x1])
mask = mask[y0:y1, x0:x1]
# The found letters are their clear strokes. Their soft edges and the parts lying in a
# shadow stay behind as a ghost of the old text: inside the text's area, whatever is
# nearer to the letters' tone than to the surface's goes too, as long as it lies next to
# a letter. (Without that limit a light stripe of the surface itself is taken for text,
# and what is painted in its place is whatever dark thing lies beside it.)
area = np.zeros(mask.shape, np.uint8)
cv2.fillPoly(area, [np.round(selection.letters_area() - (x0, y0)).astype(np.int32)], 1)
close = int(max(3, round(0.3 * tall)))
area &= cv2.dilate(letters[y0:y1, x0:x1].astype(np.uint8),
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * close + 1, 2 * close + 1)))
gray = cv2.cvtColor(window, cv2.COLOR_RGB2GRAY).astype(np.float32)
surface = (area > 0) & (mask == 0)
if surface.sum() >= 20:
ink_tone = float(np.median(gray[letters[y0:y1, x0:x1]]))
surface_tone = float(np.median(gray[surface]))
if abs(ink_tone - surface_tone) >= 30:
middle = (ink_tone + surface_tone) / 2.0
ghost = surface & ((gray > middle) if ink_tone > surface_tone else (gray < middle))
if ghost.sum() <= 0.6 * mask.sum():
mask = mask | cv2.dilate(ghost.astype(np.uint8), np.ones((3, 3), np.uint8))
out = rgb.copy()
out[y0:y1, x0:x1] = _fill(window, mask > 0, (area > 0) & (mask == 0), tall)
return out
def _fill(window, hole, surface, tall):
"""Paint the hole with the surface the text was written on.
The hole is filled from the pixels around it, each counted by how much it looks like
that surface: a dark seam or the edge of another thing next to the text adds nothing,
where a plain fill from all sides would smear it into the hole. Near pixels are used
first, so that a gradient of the surface runs on through the hole.
"""
if surface.sum() < 20:
return cv2.inpaint(window, hole.astype(np.uint8) * 255, 3, cv2.INPAINT_TELEA)
pixels = window.astype(np.float32)
tone = np.median(pixels[surface], axis=0)
apart = np.linalg.norm(pixels - tone, axis=2)
spread = max(25.0, 2.5 * float(np.median(apart[surface])))
weight = np.where(hole, 0.0, np.exp(-(apart / spread) ** 2)).astype(np.float32)
filled = np.zeros_like(pixels)
done = np.zeros(hole.shape, bool)
for sigma in (0.15 * tall, 0.4 * tall, 1.0 * tall, 2.5 * tall):
sigma = max(1.0, sigma)
total = cv2.GaussianBlur(weight, (0, 0), sigma)
mixed = cv2.GaussianBlur(pixels * weight[..., None], (0, 0), sigma)
ready = hole & ~done & (total > 0.08)
filled[ready] = mixed[ready] / total[ready][:, None]
done |= ready
if done[hole].all():
break
filled[hole & ~done] = tone
out = pixels.copy()
out[hole] = filled[hole]
return np.clip(out, 0, 255).astype(np.uint8)
class Look(object):
"""How the new text is drawn.
font_path the font file; None for the built-in one
color (r, g, b), or None for the color of the old letters
size 1.0 gives letters as tall as the old ones
fill 0..1: how far a text shorter than the old one is spread to the old width
weight None makes the strokes as thick as the old letters' were; a number from
-1 to 1 thins or thickens the font's own strokes instead
uneven 0..1: how much each letter is tilted, shifted and resized, as hand lettering is
shading 0..1: how much of the surface's light and shadow shows on the letters
opacity 0..1
soften blur of the letters' edges, in pixels
shift_x, shift_y a nudge, in letter heights
seed picks the unevenness, and the wear of a stencil
color2 (r, g, b) for the lower part of each line, or None for one color
split 0..1: 0 parts the two colors with a sharp edge at the middle, 1 runs one into
the other over the whole height
outline width of an outline around the letters, in letter heights; 0 for none
outline_color (r, g, b)
shadow 0..1: how dark a shadow the letters cast; 0 for none
shadow_color (r, g, b)
shadow_x, shadow_y where the shadow falls, in letter heights
shadow_blur in letter heights
effect "none", "embroidery", "stencil", "neon" or "engraving"
effect_strength 0..1
relief 0..1: how much the letters follow the folds and bumps of the surface, as its
light and shadow show them
"""
def __init__(self, font_path=None, color=None, size=1.0, fill=0.6, weight=None, uneven=0.0,
shading=0.6, opacity=1.0, soften=0.7, shift_x=0.0, shift_y=0.0, seed=0,
color2=None, split=1.0, outline=0.0, outline_color=(0, 0, 0), shadow=0.0,
shadow_color=(0, 0, 0), shadow_x=0.06, shadow_y=0.08, shadow_blur=0.04,
effect="none", effect_strength=1.0, relief=0.0):
self.font_path = font_path
self.color = color
self.size = size
self.fill = fill
self.weight = weight
self.uneven = uneven
self.shading = shading
self.opacity = opacity
self.soften = soften
self.shift_x = shift_x
self.shift_y = shift_y
self.seed = seed
self.color2 = color2
self.split = split
self.outline = outline
self.outline_color = outline_color
self.shadow = shadow
self.shadow_color = shadow_color
self.shadow_x = shadow_x
self.shadow_y = shadow_y
self.shadow_blur = shadow_blur
self.effect = effect if effect in EFFECTS else "none"
self.effect_strength = effect_strength
self.relief = relief
EFFECTS = ("none", "embroidery", "stencil", "neon", "engraving")
DRAWN = 4 # the text is drawn this many times larger than it ends up: smooth edges
KEPT = 2 # and kept this many times larger until it is bent into place
ROOM = 0.5 # free rows above and below the letters, in letter heights: tails, tilted letters
def _stroke(mask):
"""Thickness of the strokes in a bool mask, in pixels."""
if not mask.any():
return 0.0
depth = cv2.distanceTransform(mask.astype(np.uint8), cv2.DIST_L2, 3)
# Across a stroke the depth runs from 0 to half its width. The deep end is what counts:
# a thin frame or underline that came along with the letters must not thin the answer.
return 2.2 * float(np.percentile(depth[mask], 90))
def _load_font(path, size):
size = max(8, int(size))
try:
return ImageFont.truetype(path, size) if path else ImageFont.load_default(size)
except (OSError, IOError, TypeError):
return ImageFont.load_default()
def _glyphs(text, font, tall, look, track):
"""The text drawn letter by letter, capitals `tall` pixels high. Returns (gray array,
x of the text's left edge, y of the baseline, width of the text)."""
try:
ascent, descent = font.getmetrics()
starts = [font.getlength(text[:i]) for i in range(len(text))]
width = font.getlength(text)
except AttributeError: # the built-in bitmap font
ascent, descent = int(tall), int(tall * 0.3)
width = float(font.getbbox(text)[2])
starts = [width * i / max(1, len(text)) for i in range(len(text))]
margin = int(tall * 0.6) + 8
width += track * max(0, len(text) - 1)
canvas = Image.new("L", (int(width) + 2 * margin, ascent + descent + 2 * margin), 0)
baseline = margin + ascent
rng = np.random.RandomState(look.seed % (2 ** 31))
for i, char in enumerate(text):
if char.isspace():
continue
x = margin + starts[i] + track * i
if look.uneven <= 0:
try:
ImageDraw.Draw(canvas).text((x, baseline), char, fill=255, font=font, anchor="ls")
except (ValueError, TypeError):
ImageDraw.Draw(canvas).text((x, baseline - ascent), char, fill=255, font=font)
continue
# One letter on a tile of its own, then tilted, resized and dropped a little.
box = int(tall * 2.2)
tile = Image.new("L", (box, box), 0)
ImageDraw.Draw(tile).text((box // 2, box // 2 + tall // 2), char, fill=255, font=font, anchor="ms")
tilt, grow, drop = rng.uniform(-1, 1, 3)
tile = tile.rotate(7.0 * look.uneven * tilt, resample=Image.BICUBIC)
side = max(4, int(round(box * (1.0 + 0.09 * look.uneven * grow))))
tile = tile.resize((side, side), Image.LANCZOS)
try:
middle = x + font.getlength(char) / 2.0
except AttributeError:
middle = x + tall * 0.3
spot = (int(round(middle - side / 2.0)),
int(round(baseline - tall / 2.0 - side / 2.0 + 0.07 * tall * look.uneven * drop)))
patch = Image.new("L", canvas.size, 0)
patch.paste(tile, spot)
canvas = ImageChops.lighter(canvas, patch)
return np.asarray(canvas), margin, baseline, width
def _text_tile(text, look, tall, wide, old_stroke):
"""The text as a gray tile: `wide` across, `tall` for the capitals plus ROOM above and
below. Letters as tall as the old ones, with strokes as thick; a text longer than the old
one is squeezed, a shorter one is spread towards the old width.
old_stroke is the thickness of the old letters' strokes as a share of their height.
"""
room = int(round(ROOM * tall))
blank = np.zeros((tall + 2 * room, wide), np.uint8)
# The font size at which a capital letter is `tall` pixels high.
probe = _load_font(look.font_path, 200)
box = probe.getbbox("H")
cap = max(1.0, float(box[3] - box[1]))
font = _load_font(look.font_path, 200.0 * tall / cap)
try:
natural = font.getlength(text)
except AttributeError:
natural = float(font.getbbox(text)[2])
gaps = max(0, len(text) - 1)
track = 0.0
if natural < wide and gaps:
wanted = natural + look.fill * (wide - natural)
track = min((wanted - natural) / gaps, 0.25 * tall)
glyphs, left, baseline, width = _glyphs(text, font, tall, look, track)
if not glyphs.any():
return blank
# Stroke thickness: that of the old letters, within what still looks like this font.
own = _stroke(glyphs > 127) / float(tall)
if look.weight is None:
change = (min(max(old_stroke, 0.6 * own), 1.8 * own) - own) if old_stroke > 0 else 0.0
else:
change = 0.1 * look.weight
radius = int(round(abs(change) * tall / 2.0))
if radius:
shape = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * radius + 1, 2 * radius + 1))
glyphs = cv2.dilate(glyphs, shape) if change > 0 else cv2.erode(glyphs, shape)
across, down = 1.0, 1.0
if width > wide:
across = max(0.6, wide / width) # narrower letters first, smaller ones after that
if width * across > wide:
down = wide / (width * across)
across *= down
elif width < wide:
across = min(1.35, (width + look.fill * (wide - width)) / width)
glyphs = cv2.resize(glyphs, (max(1, int(round(glyphs.shape[1] * across))),
max(1, int(round(glyphs.shape[0] * down)))), interpolation=cv2.INTER_AREA)
# Onto the tile: centered across, the capitals in the middle of their rows.
x = int(round(wide / 2.0 - (left + width / 2.0) * across))
y = int(round(room + tall * (1.0 - down) / 2.0 - (baseline - tall) * down))
tile = Image.fromarray(blank)
tile.paste(Image.fromarray(glyphs), (x, y))
return np.asarray(tile)
LEADING = 0.45 # the gap between lines, in capital heights
def _lines_tile(lines, look, tall, wide, old_stroke):
"""Like _text_tile, for one line or several: the lines share the height of the old text,
one under the other, each centered."""
if len(lines) == 1:
return _text_tile(lines[0], look, tall, wide, old_stroke)
count = len(lines)
line_tall = max(4, int(tall / (count + (count - 1) * LEADING)))
room = int(round(ROOM * tall))
out = np.zeros((tall + 2 * room, wide), np.uint8)
line_room = int(round(ROOM * line_tall))
used = count * line_tall + (count - 1) * LEADING * line_tall
top = room + (tall - used) / 2.0
for index, line in enumerate(lines):
part = _text_tile(line, look, line_tall, wide, old_stroke)
y = int(round(top + index * line_tall * (1 + LEADING))) - line_room
y0, y1 = max(0, y), min(out.shape[0], y + part.shape[0])
if y1 > y0:
np.maximum(out[y0:y1], part[y0 - y:y1 - y], out=out[y0:y1])
return out
def write(rgb, selection, text, look=None):
# type: (np.ndarray, Selection, str, Optional[Look]) -> np.ndarray
"""Draw `text` where the old text was: same place, size, slant, bend, color and stroke,
lit the way the surface under it is lit."""
look = look or Look()
lines = [" ".join(line.split()) for line in text.split("\n")]
lines = [line for line in lines if line]
if not lines:
return rgb
wide = max(2, int(round(selection.width())))
tall = max(2, int(round(selection.height())))
ys, xs = np.nonzero(selection.mask)
old = selection.mask[ys.min():ys.max() + 1, xs.min():xs.max() + 1] if len(ys) else selection.mask[:1, :1]
tile = _lines_tile(lines, look, tall * DRAWN, wide * DRAWN, _stroke(old) / float(tall))
tile = cv2.resize(tile, (wide * KEPT, int(round(tall * (1 + 2 * ROOM))) * KEPT), interpolation=cv2.INTER_AREA)
# For every pixel near the text: where in the flat tile it takes its value from.
size = max(0.2, float(look.size))
count = len(lines)
line_px = tall * size / (count + (count - 1) * LEADING) # a capital's height, as drawn
extra = 0.0 # how far an outline or a shadow reaches past the letters, in line heights
if look.outline > 0:
extra += look.outline
if look.shadow > 0:
extra += max(abs(look.shadow_x), abs(look.shadow_y)) + 3 * look.shadow_blur
if look.effect == "neon":
extra += 1.0
warp = getattr(selection, "warp", None)
moved = float(np.abs(warp).max()) if warp is not None else 0.0
moved += RELIEF * max(0.0, float(look.relief)) * line_px
reach = (tall * (ROOM * size + abs(look.shift_y) + abs(look.shift_x) + max(0.0, size - 1.0))
+ extra * line_px + moved + 3)
outline = selection.outline_points()
x0, y0 = np.floor(outline.min(axis=0) - reach).astype(int)
x1, y1 = np.ceil(outline.max(axis=0) + reach).astype(int) + 1
x0, y0 = max(0, x0), max(0, y0)
x1, y1 = min(rgb.shape[1], x1), min(rgb.shape[0], y1)
if x1 <= x0 or y1 <= y0:
return rgb
xs, ys = np.meshgrid(np.arange(x0, x1, dtype=np.float64) + 0.5, np.arange(y0, y1, dtype=np.float64) + 0.5)
if getattr(selection, "path", None) is not None:
a, v = _path_coords(selection.path, xs, ys)
v = v + tall / 2.0 # the path runs through the middle of the letters
else:
a = xs * selection.along[0] + ys * selection.along[1] - selection.start
d = xs * selection.down[0] + ys * selection.down[1]
inside = np.clip(a, 0.0, wide) # beyond the ends the edges go on straight, not as the fit says
upper = np.polyval(selection.top, inside)
lower = np.polyval(selection.bottom, inside)
v = (d - upper) / np.maximum(lower - upper, 1.0) * tall
if moved > 0:
a, v = _displace(a, v, warp, look.relief, rgb[y0:y1, x0:x1], wide, tall, line_px)
# Size and nudge: around the middle of the text.
a = (a - wide / 2.0 - look.shift_x * tall) / size + wide / 2.0
v = (v - tall / 2.0 - look.shift_y * tall) / size + tall / 2.0 + ROOM * tall
alpha = cv2.remap(tile, (a * KEPT - 0.5).astype(np.float32), (v * KEPT - 0.5).astype(np.float32),
cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=0)
alpha = alpha.astype(np.float32) / 255.0
if not alpha.any():
return rgb
# Where each pixel sits within its line, 0 at the top of the capitals and 1 at the baseline.
line_tall = tall / (count + (count - 1) * LEADING)
row = v - ROOM * tall
index = np.clip(np.floor(row / (line_tall * (1 + LEADING))), 0, count - 1)
within = (row - index * line_tall * (1 + LEADING)) / line_tall
under = rgb[y0:y1, x0:x1].astype(np.float32)
rng = np.random.RandomState((look.seed * 7919 + 17) % (2 ** 31))
strength = min(1.0, max(0.0, float(look.effect_strength)))
alpha = _effect_shape(alpha, look.effect, strength, line_px, within, rng)
raw = alpha
if look.soften > 0:
alpha = cv2.GaussianBlur(alpha, (0, 0), float(look.soften))
first = np.array(look.color if look.color is not None else selection.color, np.float32)
ink = np.empty_like(under)
ink[:] = first
if look.color2 is not None:
# The second color from the middle of the line down: a sharp edge, or a gradient.
width = max(0.02, float(look.split))
part = np.clip((within - 0.5) / width + 0.5, 0.0, 1.0)[..., None]
ink = ink + (np.array(look.color2, np.float32) - first) * part
light = None
if look.shading > 0:
# Paint on a surface is lit as the surface is: where the cloth under a letter is
# brighter or darker than under the text as a whole, so is the letter.
light = cv2.GaussianBlur(under @ np.array([0.299, 0.587, 0.114], np.float32), (0, 0),
max(1.0, 0.06 * tall))
covered = alpha > 0.5
level = float(np.median(light[covered])) if covered.any() else float(light.mean())
light = (light - level) * 0.8 * look.shading
if look.effect == "neon":
light = light * (1.0 - strength) # a tube gives off light, it is not lit by the wall
ink += light[..., None]
opacity = min(1.0, max(0.0, look.opacity))
out = under
shape = raw
rim = None
if look.outline > 0:
radius = max(1, int(round(look.outline * line_px)))
rim = cv2.dilate(raw, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * radius + 1, 2 * radius + 1)))
if look.soften > 0:
rim = cv2.GaussianBlur(rim, (0, 0), float(look.soften))
shape = np.maximum(shape, rim)
if look.shadow > 0:
moved = cv2.warpAffine(shape, np.float32([[1, 0, look.shadow_x * line_px], [0, 1, look.shadow_y * line_px]]),
(shape.shape[1], shape.shape[0]), flags=cv2.INTER_LINEAR, borderValue=0)
blur = look.shadow_blur * line_px
if blur > 0.3:
moved = cv2.GaussianBlur(moved, (0, 0), blur)
cast = (moved * min(1.0, look.shadow) * opacity)[..., None]
out = out * (1.0 - cast) + np.array(look.shadow_color, np.float32) * cast
if rim is not None:
edge = np.empty_like(under)
edge[:] = np.array(look.outline_color, np.float32)
if light is not None:
edge += light[..., None]
cover = (rim * opacity)[..., None]
out = out * (1.0 - cover) + edge * cover
ink, out = _effect_color(ink, out, under, alpha, raw, look.effect, strength, line_px, a, v, first)
cover = (alpha * opacity)[..., None]
out = out * (1.0 - cover) + ink * cover
result = rgb.copy()
result[y0:y1, x0:x1] = np.clip(out, 0, 255)
return result
RELIEF = 0.35 # how far the folds of a surface move the letters at relief 1, in line heights
def _path_coords(path, xs, ys):
"""For each pixel: how far along the path its nearest point lies, and how far the pixel is
from the path, positive on the right of the way the path runs. Past the ends the path
goes on straight."""
best = np.full(xs.shape, np.inf)
along = np.zeros(xs.shape)
across = np.zeros(xs.shape)
done = 0.0
last = len(path) - 2
for i in range(len(path) - 1):
(ax, ay), (bx, by) = path[i], path[i + 1]
dx, dy = bx - ax, by - ay
length = float(np.hypot(dx, dy))
if length < 1e-6:
continue
t = ((xs - ax) * dx + (ys - ay) * dy) / (length * length)
low = -np.inf if i == 0 else 0.0
high = np.inf if i == last else 1.0
t = np.clip(t, low, high)
px, py = ax + t * dx, ay + t * dy
far = (xs - px) ** 2 + (ys - py) ** 2
closer = far < best
best = np.where(closer, far, best)
along = np.where(closer, done + t * length, along)
across = np.where(closer, ((xs - px) * -dy + (ys - py) * dx) / length, across)
done += length
return along, across
def _displace(a, v, warp, relief, under, wide, tall, line_px):
"""Bend the letters out of their straight place: by a grid of moves set by hand (each
grid point an (dx, dy) in pixels, the grid spread over the text), and by the folds of the
surface, guessed from its light and shadow. Returns the new place in the tile of every
pixel."""
shift = np.zeros(a.shape + (2,), np.float32)
if warp is not None:
grid = np.asarray(warp, np.float32)
rows, cols = grid.shape[:2]
gx = np.clip(a / max(1.0, wide), 0.0, 1.0) * (cols - 1)
gy = np.clip(v / max(1.0, tall), 0.0, 1.0) * (rows - 1)
for k in range(2):
shift[..., k] = cv2.remap(np.ascontiguousarray(grid[..., k]), gx.astype(np.float32),
gy.astype(np.float32), cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
if relief > 0:
# Light falls on a fold's near side and misses the far one: where the surface is
# brighter than its surroundings it bulges towards the light, and the letters on it are
# carried along, as a displacement map carries them.
gray = cv2.cvtColor(under.astype(np.uint8), cv2.COLOR_RGB2GRAY).astype(np.float32)
fine = cv2.GaussianBlur(gray, (0, 0), max(1.0, 0.25 * line_px))
broad = cv2.GaussianBlur(gray, (0, 0), max(2.0, 2.0 * line_px))
bump = fine - broad
bump /= max(4.0, float(np.percentile(np.abs(bump), 95)))
amount = RELIEF * float(relief) * line_px
shift[..., 0] += (np.clip(bump, -1.5, 1.5) * amount * 0.5).astype(np.float32)
shift[..., 1] += (np.clip(bump, -1.5, 1.5) * amount).astype(np.float32)
# The letters land where they are moved to: a pixel takes the place of the point that
# was moved onto it.
h, w = a.shape
px, py = np.meshgrid(np.arange(w, dtype=np.float32), np.arange(h, dtype=np.float32))
forward = [np.ascontiguousarray(shift[..., k]) for k in range(2)]
for _ in range(3): # the move is smooth, so a few rounds find where each pixel came from
sx = px - shift[..., 0]
sy = py - shift[..., 1]
shift = np.stack([cv2.remap(part, sx, sy, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
for part in forward], axis=-1)
mx, my = px - shift[..., 0], py - shift[..., 1]
a = cv2.remap(a.astype(np.float32), mx, my, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
v = cv2.remap(v.astype(np.float32), mx, my, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
return a.astype(np.float64), v.astype(np.float64)
def _effect_shape(alpha, effect, strength, line_px, within, rng):
"""The letters' coverage as a material changes it: a stencil's bridges and wear."""
if effect != "stencil" or strength <= 0:
return alpha
# Bridges: a stencil cannot hold the middle of a letter, so a band across it stays bare.
gap = 0.05 * strength
alpha = alpha * np.clip(np.abs(within - 0.52) / max(gap, 1e-3) * 2.0 - 1.0, 0.0, 1.0)
# Wear: patches where the paint did not take, and a little overspray around the letters.
grain = max(1.0, 0.08 * line_px)
noise = cv2.GaussianBlur(rng.uniform(0, 1, alpha.shape).astype(np.float32), (0, 0), grain)
noise = (noise - noise.min()) / max(1e-6, float(noise.max() - noise.min()))
worn = np.clip((noise - (1.0 - 0.22 * strength)) * 6.0, 0.0, 1.0)
spray = cv2.GaussianBlur(alpha, (0, 0), max(1.0, 0.04 * line_px)) * 0.3 * strength
return np.maximum(alpha * (1.0 - worn), spray * (1.0 - worn))
def _effect_color(ink, out, under, alpha, raw, effect, strength, line_px, a, v, color):
"""The colors of the letters, and of what is under them, as a material changes them."""
if effect == "none" or strength <= 0:
return ink, out
if effect == "neon":
# A glow on the wall around the tube, and a core that burns nearly white.
glow = cv2.GaussianBlur(raw, (0, 0), max(1.0, 0.3 * line_px)) * 0.9 * strength
out = out + glow[..., None] * color * (1.0 - out / 255.0)
thin = max(1, int(round(0.05 * line_px)))
core = cv2.GaussianBlur(cv2.erode(raw, np.ones((2 * thin + 1, 2 * thin + 1), np.uint8)), (0, 0),
max(1.0, 0.03 * line_px))
ink = ink + (255.0 - ink) * (0.7 * strength * core)[..., None]
return ink, out
if effect == "engraving":
# Cut into the surface: the letters are the surface itself in shade, with the light
# catching the far wall of each cut and missing the near one.
depth = cv2.GaussianBlur(raw, (0, 0), max(1.0, 0.04 * line_px))
gx = cv2.Sobel(depth, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(depth, cv2.CV_32F, 0, 1, ksize=3)
bevel = np.clip(-(gx + gy) * line_px * 0.35, -1.0, 1.0)
floor = under * (1.0 - 0.5 * strength) + ink * 0.25 * strength
ink = ink * (1.0 - strength) + floor * strength
ink = ink + (bevel * 70.0 * strength)[..., None]
return ink, out
if effect == "embroidery":
# Satin stitches run on a slant across each letter; the thread is darker where it
# dives into the cloth at the edges, and the letters stand a little off the cloth.
period = max(2.0, 0.09 * line_px)
thread = 0.5 + 0.5 * np.sin(2 * np.pi * (a * 0.7 + v * 0.7) / (period * 1.0))
inside = cv2.distanceTransform((raw > 0.5).astype(np.uint8), cv2.DIST_L2, 3)
edge = np.clip(inside / max(1.0, 0.07 * line_px), 0.0, 1.0)
tone = (0.7 + 0.42 * thread) * (0.72 + 0.28 * edge)
ink = ink * (1.0 - strength + strength * tone[..., None])
lift = cv2.warpAffine(raw, np.float32([[1, 0, 0.02 * line_px], [0, 1, 0.03 * line_px]]),
(raw.shape[1], raw.shape[0]), flags=cv2.INTER_LINEAR, borderValue=0)
lift = cv2.GaussianBlur(lift, (0, 0), max(1.0, 0.03 * line_px)) * 0.45 * strength
out = out * (1.0 - lift[..., None])
return ink, out
return ink, out
FLAT = 64 # height of the letters when they are compared with fonts, in pixels
SAMPLE = "HAMBURGEFONSTIV"
def _flat_letters(selection):
"""The old letters as a straight line FLAT pixels high: the bend and slant of the line
taken out, so that only the shapes of the letters are left."""
wide = selection.width()
tall = selection.height()
if wide < 4 or tall < 4:
return None
room = 0.15
out_w = max(8, int(round(wide / tall * FLAT)))
out_h = int(round(FLAT * (1 + 2 * room)))
a = (np.arange(out_w, dtype=np.float64) + 0.5) * wide / out_w
v = ((np.arange(out_h, dtype=np.float64) + 0.5) / FLAT - room)
aa, vv = np.meshgrid(a, v)
upper = np.polyval(selection.top, aa)
lower = np.polyval(selection.bottom, aa)
d = upper + (lower - upper) * vv
points = selection.along[None, None, :] * (selection.start + aa)[..., None] + selection.down[None, None, :] * d[..., None]
flat = cv2.remap(selection.mask.astype(np.uint8) * 255, points[..., 0].astype(np.float32) - 0.5,
points[..., 1].astype(np.float32) - 0.5, cv2.INTER_LINEAR, borderValue=0)
return flat > 127
def letter_features(mask):
# type: (np.ndarray) -> Optional[np.ndarray]
"""What sets a typeface apart, measured on letters FLAT pixels high: stroke thickness,
how much thick and thin strokes differ, letter width, how much of its box a letter
fills, and slant. None when there are too few letters to tell."""
count, labels, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), 8)
widths, fills, slants = [], [], []
for i in range(1, count):
x, y, w, h, area = stats[i]
if h < 0.45 * FLAT or h > 1.6 * FLAT or w > 2.5 * FLAT:
continue
widths.append(w / float(FLAT))
fills.append(area / float(w * h))
part = (labels[y:y + h, x:x + w] == i).astype(np.uint8)
moments = cv2.moments(part, True)
if moments["mu02"] > 0:
slants.append(moments["mu11"] / moments["mu02"])
if len(widths) < 2:
return None
depth = cv2.distanceTransform(mask.astype(np.uint8), cv2.DIST_L2, 3)
ridge = (depth >= cv2.dilate(depth, np.ones((3, 3), np.uint8)) - 1e-3) & (depth > 1.0)
values = depth[ridge]
if len(values) < 10:
return None
stroke = 2.0 * float(np.percentile(values, 75)) / FLAT
contrast = float(np.percentile(values, 85)) / max(0.5, float(np.percentile(values, 20)))
return np.array([stroke, contrast, float(np.median(widths)), float(np.median(fills)),
float(np.median(slants)) if slants else 0.0])
_font_features = {} # type: dict
def font_features(path):
# type: (Optional[str]) -> Optional[np.ndarray]
if path in _font_features:
return _font_features[path]
probe = _load_font(path, 200)
box = probe.getbbox("H")
cap = max(1.0, float(box[3] - box[1]))
font = _load_font(path, 200.0 * FLAT / cap)
glyphs, _, _, _ = _glyphs(SAMPLE, font, FLAT, Look(), FLAT * 0.12)
features = letter_features(glyphs > 127)
_font_features[path] = features
return features
def _distance(old, new):
ratio = np.log(np.maximum(new[:3], 1e-3) / np.maximum(old[:3], 1e-3))
return float(np.sqrt(1.0 * ratio[0] ** 2 + 1.5 * ratio[1] ** 2 + 3.0 * ratio[2] ** 2
+ 6.0 * (new[3] - old[3]) ** 2 + 8.0 * (new[4] - old[4]) ** 2))
def match_fonts(selection, fonts):
# type: (Selection, dict) -> List[Tuple[str, float]]
"""The fonts ordered from the one most like the old letters, each with how far it is
from them (0 is the same). `fonts` maps names to font files. Empty when the old letters
are too few or too blurred to measure."""
flat = _flat_letters(selection)
old = letter_features(flat) if flat is not None else None
if old is None:
return []
ranked = []
for name, path in fonts.items():
features = font_features(path)
if features is not None:
ranked.append((name, _distance(old, features)))
ranked.sort(key=lambda pair: pair[1])
return ranked
def replace(rgb, selection, text, look=None):
# type: (np.ndarray, Selection, str, Optional[Look]) -> np.ndarray
if not " ".join(text.split()):
return rgb
return write(erase(rgb, selection), selection, text, look)
def blend_mask(shape, selection):
"""The area handed to the model to blend the new text in: the new text and the place of
the old letters, with a margin as wide as a share of a line of the old letters."""
mask = np.zeros(shape[:2], np.uint8)
cv2.fillPoly(mask, [np.round(selection.outline_points()).astype(np.int32)], 255)
cv2.fillPoly(mask, [np.round(selection.letters_area()).astype(np.int32)], 255)
grow = int(max(3, round(0.4 * selection.letters_height())))
mask = cv2.dilate(mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * grow + 1, 2 * grow + 1)))
return mask > 0
def outline(rgb, selection, color=(0, 255, 120), number=None):
"""The image with the selection's edge drawn on it, and its number when given."""
out = np.ascontiguousarray(rgb).copy()
thick = max(1, int(round(min(rgb.shape[:2]) / 500.0)))
cv2.polylines(out, [np.round(selection.outline_points()).astype(np.int32)], True, color, thick, cv2.LINE_AA)
if number is not None:
scale = max(0.45, min(rgb.shape[:2]) / 1100.0)
x, y = selection.quad[0]
spot = (int(max(2, x)), int(max(14 * scale * 2, y - 4)))
cv2.putText(out, str(number), spot, cv2.FONT_HERSHEY_SIMPLEX, scale, (0, 0, 0), thick * 3 + 1, cv2.LINE_AA)
cv2.putText(out, str(number), spot, cv2.FONT_HERSHEY_SIMPLEX, scale, color, thick + 1, cv2.LINE_AA)
return out
def same(first, second):
"""Whether two selections are of the same text. The host may hand back copies of the
objects it was given, so they are told apart by where they lie."""
return np.array_equal(first.quad, second.quad)
def preview(rgb, chosen, offered=()):
# type: (np.ndarray, Sequence[Selection], Sequence[Selection]) -> np.ndarray
"""The image with what was found (yellow) and what is chosen (green, numbered)."""
out = rgb
for selection in offered:
if not any(same(selection, other) for other in chosen):
out = outline(out, selection, color=(255, 210, 0))
for index, selection in enumerate(chosen):
out = outline(out, selection, number=index + 1)
return out
def parse_color(value):
# type: (str) -> Optional[Tuple[int, int, int]]
""""#rrggbb" or "rgb(r, g, b)" / "rgba(...)" as the host's color picker gives it."""
value = (value or "").strip()
if value.startswith("#") and len(value) == 7:
try:
return tuple(int(value[i:i + 2], 16) for i in (1, 3, 5))
except ValueError:
return None
if value.startswith("rgb"):
parts = value[value.find("(") + 1:value.rfind(")")].split(",") # type: List[str]
try:
return tuple(int(round(float(part))) for part in parts[:3])
except ValueError:
return None
return None
|