utils.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. import re
  2. import cv2
  3. import numpy as np
  4. from PIL import Image
  5. REGEX_NODE = re.compile(r'(-?[A-Za-z]+)(-?\d+)')
  6. def random_normal_distribution_int(a, b, n=3):
  7. """Generate a normal distribution int within the interval. Use the average value of several random numbers to
  8. simulate normal distribution.
  9. Args:
  10. a (int): The minimum of the interval.
  11. b (int): The maximum of the interval.
  12. n (int): The amount of numbers in simulation. Default to 3.
  13. Returns:
  14. int
  15. """
  16. if a < b:
  17. output = np.mean(np.random.randint(a, b, size=n))
  18. return int(output.round())
  19. else:
  20. return b
  21. def random_rectangle_point(area, n=3):
  22. """Choose a random point in an area.
  23. Args:
  24. area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  25. n (int): The amount of numbers in simulation. Default to 3.
  26. Returns:
  27. tuple(int): (x, y)
  28. """
  29. x = random_normal_distribution_int(area[0], area[2], n=n)
  30. y = random_normal_distribution_int(area[1], area[3], n=n)
  31. return x, y
  32. def random_rectangle_vector(vector, box, random_range=(0, 0, 0, 0), padding=15):
  33. """Place a vector in a box randomly.
  34. Args:
  35. vector: (x, y)
  36. box: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  37. random_range (tuple): Add a random_range to vector. (x_min, y_min, x_max, y_max).
  38. padding (int):
  39. Returns:
  40. tuple(int), tuple(int): start_point, end_point.
  41. """
  42. vector = np.array(vector) + random_rectangle_point(random_range)
  43. vector = np.round(vector).astype(np.int)
  44. half_vector = np.round(vector / 2).astype(np.int)
  45. box = np.array(box) + np.append(np.abs(half_vector) + padding, -np.abs(half_vector) - padding)
  46. center = random_rectangle_point(box)
  47. start_point = center - half_vector
  48. end_point = start_point + vector
  49. return tuple(start_point), tuple(end_point)
  50. def random_rectangle_vector_opted(
  51. vector, box, random_range=(0, 0, 0, 0), padding=15, whitelist_area=None, blacklist_area=None):
  52. """
  53. Place a vector in a box randomly.
  54. When emulator/game stuck, it treats a swipe as a click, clicking at the end of swipe path.
  55. To prevent this, random results need to be filtered.
  56. Args:
  57. vector: (x, y)
  58. box: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  59. random_range (tuple): Add a random_range to vector. (x_min, y_min, x_max, y_max).
  60. padding (int):
  61. whitelist_area: (list[tuple[int]]):
  62. A list of area that safe to click. Swipe path will end there.
  63. blacklist_area: (list[tuple[int]]):
  64. If none of the whitelist_area satisfies current vector, blacklist_area will be used.
  65. Delete random path that ends in any blacklist_area.
  66. Returns:
  67. tuple(int), tuple(int): start_point, end_point.
  68. """
  69. vector = np.array(vector) + random_rectangle_point(random_range)
  70. vector = np.round(vector).astype(np.int)
  71. half_vector = np.round(vector / 2).astype(np.int)
  72. box_pad = np.array(box) + np.append(np.abs(half_vector) + padding, -np.abs(half_vector) - padding)
  73. box_pad = area_offset(box_pad, half_vector)
  74. segment = int(np.linalg.norm(vector) // 70) + 1
  75. def in_blacklist(end):
  76. if not blacklist_area:
  77. return False
  78. for x in range(segment + 1):
  79. point = - vector * x / segment + end
  80. for area in blacklist_area:
  81. if point_in_area(point, area, threshold=0):
  82. return True
  83. return False
  84. if whitelist_area:
  85. for area in whitelist_area:
  86. area = area_limit(area, box_pad)
  87. if all([x > 0 for x in area_size(area)]):
  88. end_point = random_rectangle_point(area)
  89. for _ in range(10):
  90. if in_blacklist(end_point):
  91. continue
  92. return point_limit(end_point - vector, box), point_limit(end_point, box)
  93. for _ in range(100):
  94. end_point = random_rectangle_point(box_pad)
  95. if in_blacklist(end_point):
  96. continue
  97. return point_limit(end_point - vector, box), point_limit(end_point, box)
  98. end_point = random_rectangle_point(box_pad)
  99. return point_limit(end_point - vector, box), point_limit(end_point, box)
  100. def random_line_segments(p1, p2, n, random_range=(0, 0, 0, 0)):
  101. """Cut a line into multiple segments.
  102. Args:
  103. p1: (x, y).
  104. p2: (x, y).
  105. n: Number of slice.
  106. random_range: Add a random_range to points.
  107. Returns:
  108. list[tuple]: [(x0, y0), (x1, y1), (x2, y2)]
  109. """
  110. return [tuple((((n - index) * p1 + index * p2) / n).astype(int) + random_rectangle_point(random_range))
  111. for index in range(0, n + 1)]
  112. def ensure_time(second, n=3, precision=3):
  113. """Ensure to be time.
  114. Args:
  115. second (int, float, tuple): time, such as 10, (10, 30), '10, 30'
  116. n (int): The amount of numbers in simulation. Default to 5.
  117. precision (int): Decimals.
  118. Returns:
  119. float:
  120. """
  121. if isinstance(second, tuple):
  122. multiply = 10 ** precision
  123. result = random_normal_distribution_int(second[0] * multiply, second[1] * multiply, n) / multiply
  124. return round(result, precision)
  125. elif isinstance(second, str):
  126. if ',' in second:
  127. lower, upper = second.replace(' ', '').split(',')
  128. lower, upper = int(lower), int(upper)
  129. return ensure_time((lower, upper), n=n, precision=precision)
  130. if '-' in second:
  131. lower, upper = second.replace(' ', '').split('-')
  132. lower, upper = int(lower), int(upper)
  133. return ensure_time((lower, upper), n=n, precision=precision)
  134. else:
  135. return int(second)
  136. else:
  137. return second
  138. def ensure_int(*args):
  139. """
  140. Convert all elements to int.
  141. Return the same structure as nested objects.
  142. Args:
  143. *args:
  144. Returns:
  145. list:
  146. """
  147. def to_int(item):
  148. try:
  149. return int(item)
  150. except TypeError:
  151. result = [to_int(i) for i in item]
  152. if len(result) == 1:
  153. result = result[0]
  154. return result
  155. return to_int(args)
  156. def area_offset(area, offset):
  157. """
  158. Move an area.
  159. Args:
  160. area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  161. offset: (x, y).
  162. Returns:
  163. tuple: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  164. """
  165. upper_left_x, upper_left_y, bottom_right_x, bottom_right_y = area
  166. x, y = offset
  167. return upper_left_x + x, upper_left_y + y, bottom_right_x + x, bottom_right_y + y
  168. def area_pad(area, pad=10):
  169. """
  170. Inner offset an area.
  171. Args:
  172. area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  173. pad (int):
  174. Returns:
  175. tuple: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  176. """
  177. upper_left_x, upper_left_y, bottom_right_x, bottom_right_y = area
  178. return upper_left_x + pad, upper_left_y + pad, bottom_right_x - pad, bottom_right_y - pad
  179. def limit_in(x, lower, upper):
  180. """
  181. Limit x within range (lower, upper)
  182. Args:
  183. x:
  184. lower:
  185. upper:
  186. Returns:
  187. int, float:
  188. """
  189. return max(min(x, upper), lower)
  190. def area_limit(area1, area2):
  191. """
  192. Limit an area in another area.
  193. Args:
  194. area1: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  195. area2: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  196. Returns:
  197. tuple: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  198. """
  199. x_lower, y_lower, x_upper, y_upper = area2
  200. return (
  201. limit_in(area1[0], x_lower, x_upper),
  202. limit_in(area1[1], y_lower, y_upper),
  203. limit_in(area1[2], x_lower, x_upper),
  204. limit_in(area1[3], y_lower, y_upper),
  205. )
  206. def area_size(area):
  207. """
  208. Area size or shape.
  209. Args:
  210. area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  211. Returns:
  212. tuple: (x, y).
  213. """
  214. return (
  215. max(area[2] - area[0], 0),
  216. max(area[3] - area[1], 0)
  217. )
  218. def point_limit(point, area):
  219. """
  220. Limit point in an area.
  221. Args:
  222. point: (x, y).
  223. area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  224. Returns:
  225. tuple: (x, y).
  226. """
  227. return (
  228. limit_in(point[0], area[0], area[2]),
  229. limit_in(point[1], area[1], area[3])
  230. )
  231. def point_in_area(point, area, threshold=5):
  232. """
  233. Args:
  234. point: (x, y).
  235. area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  236. threshold: int
  237. Returns:
  238. bool:
  239. """
  240. return area[0] - threshold < point[0] < area[2] + threshold and area[1] - threshold < point[1] < area[3] + threshold
  241. def area_in_area(area1, area2, threshold=5):
  242. """
  243. Args:
  244. area1: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  245. area2: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  246. threshold: int
  247. Returns:
  248. bool:
  249. """
  250. return area2[0] - threshold <= area1[0] \
  251. and area2[1] - threshold <= area1[1] \
  252. and area1[2] <= area2[2] + threshold \
  253. and area1[3] <= area2[3] + threshold
  254. def area_cross_area(area1, area2, threshold=5):
  255. """
  256. Args:
  257. area1: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  258. area2: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
  259. threshold: int
  260. Returns:
  261. bool:
  262. """
  263. # https://www.yiiven.cn/rect-is-intersection.html
  264. xa1, ya1, xa2, ya2 = area1
  265. xb1, yb1, xb2, yb2 = area2
  266. return abs(xb2 + xb1 - xa2 - xa1) <= xa2 - xa1 + xb2 - xb1 + threshold * 2 \
  267. and abs(yb2 + yb1 - ya2 - ya1) <= ya2 - ya1 + yb2 - yb1 + threshold * 2
  268. def float2str(n, decimal=3):
  269. """
  270. Args:
  271. n (float):
  272. decimal (int):
  273. Returns:
  274. str:
  275. """
  276. return str(round(n, decimal)).ljust(decimal + 2, "0")
  277. def point2str(x, y, length=4):
  278. """
  279. Args:
  280. x (int, float):
  281. y (int, float):
  282. length (int): Align length.
  283. Returns:
  284. str: String with numbers right aligned, such as '( 100, 80)'.
  285. """
  286. return '(%s, %s)' % (str(int(x)).rjust(length), str(int(y)).rjust(length))
  287. def col2name(col):
  288. """
  289. Convert a zero indexed column cell reference to a string.
  290. Args:
  291. col: The cell column. Int.
  292. Returns:
  293. Column style string.
  294. Examples:
  295. 0 -> A, 3 -> D, 35 -> AJ, -1 -> -A
  296. """
  297. col_neg = col < 0
  298. if col_neg:
  299. col_num = -col
  300. else:
  301. col_num = col + 1 # Change to 1-index.
  302. col_str = ''
  303. while col_num:
  304. # Set remainder from 1 .. 26
  305. remainder = col_num % 26
  306. if remainder == 0:
  307. remainder = 26
  308. # Convert the remainder to a character.
  309. col_letter = chr(remainder + 64)
  310. # Accumulate the column letters, right to left.
  311. col_str = col_letter + col_str
  312. # Get the next order of magnitude.
  313. col_num = int((col_num - 1) / 26)
  314. if col_neg:
  315. return '-' + col_str
  316. else:
  317. return col_str
  318. def name2col(col_str):
  319. """
  320. Convert a cell reference in A1 notation to a zero indexed row and column.
  321. Args:
  322. col_str: A1 style string.
  323. Returns:
  324. row, col: Zero indexed cell row and column indices.
  325. """
  326. # Convert base26 column string to number.
  327. expn = 0
  328. col = 0
  329. col_neg = col_str.startswith('-')
  330. col_str = col_str.strip('-').upper()
  331. for char in reversed(col_str):
  332. col += (ord(char) - 64) * (26 ** expn)
  333. expn += 1
  334. if col_neg:
  335. return -col
  336. else:
  337. return col - 1 # Convert 1-index to zero-index
  338. def node2location(node):
  339. """
  340. See location2node()
  341. Args:
  342. node (str): Example: 'E3'
  343. Returns:
  344. tuple[int]: Example: (4, 2)
  345. """
  346. res = REGEX_NODE.search(node)
  347. if res:
  348. x, y = res.group(1), res.group(2)
  349. y = int(y)
  350. if y > 0:
  351. y -= 1
  352. return name2col(x), y
  353. else:
  354. # Whatever
  355. return ord(node[0]) % 32 - 1, int(node[1:]) - 1
  356. def location2node(location):
  357. """
  358. Convert location tuple to an Excel-like cell.
  359. Accept negative values also.
  360. -2 -1 0 1 2 3
  361. -2 -B-2 -A-2 A-2 B-2 C-2 D-2
  362. -1 -B-1 -A-1 A-1 B-1 C-1 D-1
  363. 0 -B1 -A1 A1 B1 C1 D1
  364. 1 -B2 -A2 A2 B2 C2 D2
  365. 2 -B3 -A3 A3 B3 C3 D3
  366. 3 -B4 -A4 A4 B4 C4 D4
  367. # To generate the table above
  368. index = range(-2, 4)
  369. row = ' ' + ' '.join([str(i).rjust(4) for i in index])
  370. print(row)
  371. for y in index:
  372. row = str(y).rjust(2) + ' ' + ' '.join([location2node((x, y)).rjust(4) for x in index])
  373. print(row)
  374. def check(node):
  375. return point2str(*node2location(location2node(node)), length=2)
  376. row = ' ' + ' '.join([str(i).rjust(8) for i in index])
  377. print(row)
  378. for y in index:
  379. row = str(y).rjust(2) + ' ' + ' '.join([check((x, y)).rjust(4) for x in index])
  380. print(row)
  381. Args:
  382. location (tuple[int]):
  383. Returns:
  384. str:
  385. """
  386. x, y = location
  387. if y >= 0:
  388. y += 1
  389. return col2name(x) + str(y)
  390. def load_image(file, area=None):
  391. """
  392. Load an image like pillow and drop alpha channel.
  393. Args:
  394. file (str):
  395. area (tuple):
  396. Returns:
  397. np.ndarray:
  398. """
  399. image = Image.open(file)
  400. if area is not None:
  401. image = image.crop(area)
  402. image = np.array(image)
  403. channel = image.shape[2] if len(image.shape) > 2 else 1
  404. if channel > 3:
  405. image = image[:, :, :3].copy()
  406. return image
  407. def save_image(image, file):
  408. """
  409. Save an image like pillow.
  410. Args:
  411. image (np.ndarray):
  412. file (str):
  413. """
  414. # image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
  415. # cv2.imwrite(file, image)
  416. Image.fromarray(image).save(file)
  417. def crop(image, area, copy=True):
  418. """
  419. Crop image like pillow, when using opencv / numpy.
  420. Provides a black background if cropping outside of image.
  421. Args:
  422. image (np.ndarray):
  423. area:
  424. copy (bool):
  425. Returns:
  426. np.ndarray:
  427. """
  428. x1, y1, x2, y2 = map(int, map(round, area))
  429. h, w = image.shape[:2]
  430. border = np.maximum((0 - y1, y2 - h, 0 - x1, x2 - w), 0)
  431. x1, y1, x2, y2 = np.maximum((x1, y1, x2, y2), 0)
  432. image = image[y1:y2, x1:x2]
  433. if sum(border) > 0:
  434. image = cv2.copyMakeBorder(image, *border, borderType=cv2.BORDER_CONSTANT, value=(0, 0, 0))
  435. if copy:
  436. image = image.copy()
  437. return image
  438. def resize(image, size):
  439. """
  440. Resize image like pillow image.resize(), but implement in opencv.
  441. Pillow uses PIL.Image.NEAREST by default.
  442. Args:
  443. image (np.ndarray):
  444. size: (x, y)
  445. Returns:
  446. np.ndarray:
  447. """
  448. return cv2.resize(image, size, interpolation=cv2.INTER_NEAREST)
  449. def image_channel(image):
  450. """
  451. Args:
  452. image (np.ndarray):
  453. Returns:
  454. int: 0 for grayscale, 3 for RGB.
  455. """
  456. return image.shape[2] if len(image.shape) == 3 else 0
  457. def image_size(image):
  458. """
  459. Args:
  460. image (np.ndarray):
  461. Returns:
  462. int, int: width, height
  463. """
  464. shape = image.shape
  465. return shape[1], shape[0]
  466. def rgb2gray(image):
  467. """
  468. Args:
  469. image (np.ndarray): Shape (height, width, channel)
  470. Returns:
  471. np.ndarray: Shape (height, width)
  472. """
  473. r, g, b = cv2.split(image)
  474. return cv2.add(
  475. cv2.multiply(cv2.max(cv2.max(r, g), b), 0.5),
  476. cv2.multiply(cv2.min(cv2.min(r, g), b), 0.5)
  477. )
  478. def rgb2hsv(image):
  479. """
  480. Convert RGB color space to HSV color space.
  481. HSV is Hue Saturation Value.
  482. Args:
  483. image (np.ndarray): Shape (height, width, channel)
  484. Returns:
  485. np.ndarray: Hue (0~360), Saturation (0~100), Value (0~100).
  486. """
  487. image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV).astype(np.float)
  488. image *= (360 / 180, 100 / 255, 100 / 255)
  489. return image
  490. def rgb2yuv(image):
  491. """
  492. Convert RGB to YUV color space.
  493. Args:
  494. image (np.ndarray): Shape (height, width, channel)
  495. Returns:
  496. np.ndarray: Shape (height, width)
  497. """
  498. image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)
  499. return image
  500. def rgb2luma(image):
  501. """
  502. Convert RGB to the Y channel (Luminance) in YUV color space.
  503. Args:
  504. image (np.ndarray): Shape (height, width, channel)
  505. Returns:
  506. np.ndarray: Shape (height, width)
  507. """
  508. image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)
  509. luma, _, _ = cv2.split(image)
  510. return luma
  511. def get_color(image, area):
  512. """Calculate the average color of a particular area of the image.
  513. Args:
  514. image (np.ndarray): Screenshot.
  515. area (tuple): (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y)
  516. Returns:
  517. tuple: (r, g, b)
  518. """
  519. temp = crop(image, area, copy=False)
  520. color = cv2.mean(temp)
  521. return color[:3]
  522. def get_bbox(image, threshold=0):
  523. """
  524. A numpy implementation of the getbbox() in pillow.
  525. Args:
  526. image (np.ndarray): Screenshot.
  527. threshold (int): Color <= threshold will be considered black
  528. Returns:
  529. tuple: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y)
  530. """
  531. if image_channel(image) == 3:
  532. image = np.max(image, axis=2)
  533. x = np.where(np.max(image, axis=0) > threshold)[0]
  534. y = np.where(np.max(image, axis=1) > threshold)[0]
  535. return x[0], y[0], x[-1] + 1, y[-1] + 1
  536. def color_similarity(color1, color2):
  537. """
  538. Args:
  539. color1 (tuple): (r, g, b)
  540. color2 (tuple): (r, g, b)
  541. Returns:
  542. int:
  543. """
  544. diff = np.array(color1).astype(int) - np.array(color2).astype(int)
  545. diff = np.max(np.maximum(diff, 0)) - np.min(np.minimum(diff, 0))
  546. return diff
  547. def color_similar(color1, color2, threshold=10):
  548. """Consider two colors are similar, if tolerance lesser or equal threshold.
  549. Tolerance = Max(Positive(difference_rgb)) + Max(- Negative(difference_rgb))
  550. The same as the tolerance in Photoshop.
  551. Args:
  552. color1 (tuple): (r, g, b)
  553. color2 (tuple): (r, g, b)
  554. threshold (int): Default to 10.
  555. Returns:
  556. bool: True if two colors are similar.
  557. """
  558. # print(color1, color2)
  559. diff = np.array(color1).astype(int) - np.array(color2).astype(int)
  560. diff = np.max(np.maximum(diff, 0)) - np.min(np.minimum(diff, 0))
  561. return diff <= threshold
  562. def color_similar_1d(image, color, threshold=10):
  563. """
  564. Args:
  565. image (np.ndarray): 1D array.
  566. color: (r, g, b)
  567. threshold(int): Default to 10.
  568. Returns:
  569. np.ndarray: bool
  570. """
  571. diff = image.astype(int) - color
  572. diff = np.max(np.maximum(diff, 0), axis=1) - np.min(np.minimum(diff, 0), axis=1)
  573. return diff <= threshold
  574. def color_similarity_2d(image, color):
  575. """
  576. Args:
  577. image: 2D array.
  578. color: (r, g, b)
  579. Returns:
  580. np.ndarray: uint8
  581. """
  582. r, g, b = cv2.split(cv2.subtract(image, (*color, 0)))
  583. positive = cv2.max(cv2.max(r, g), b)
  584. r, g, b = cv2.split(cv2.subtract((*color, 0), image))
  585. negative = cv2.max(cv2.max(r, g), b)
  586. return cv2.subtract(255, cv2.add(positive, negative))
  587. def extract_letters(image, letter=(255, 255, 255), threshold=128):
  588. """Set letter color to black, set background color to white.
  589. Args:
  590. image: Shape (height, width, channel)
  591. letter (tuple): Letter RGB.
  592. threshold (int):
  593. Returns:
  594. np.ndarray: Shape (height, width)
  595. """
  596. r, g, b = cv2.split(cv2.subtract(image, (*letter, 0)))
  597. positive = cv2.max(cv2.max(r, g), b)
  598. r, g, b = cv2.split(cv2.subtract((*letter, 0), image))
  599. negative = cv2.max(cv2.max(r, g), b)
  600. return cv2.multiply(cv2.add(positive, negative), 255.0 / threshold)
  601. def extract_white_letters(image, threshold=128):
  602. """Set letter color to black, set background color to white.
  603. This function will discourage color pixels (Non-gray pixels)
  604. Args:
  605. image: Shape (height, width, channel)
  606. threshold (int):
  607. Returns:
  608. np.ndarray: Shape (height, width)
  609. """
  610. r, g, b = cv2.split(cv2.subtract((255, 255, 255, 0), image))
  611. minimum = cv2.min(cv2.min(r, g), b)
  612. maximum = cv2.max(cv2.max(r, g), b)
  613. return cv2.multiply(cv2.add(maximum, cv2.subtract(maximum, minimum)), 255.0 / threshold)
  614. def color_mapping(image, max_multiply=2):
  615. """
  616. Mapping color to 0-255.
  617. Minimum color to 0, maximum color to 255, multiply colors by 2 at max.
  618. Args:
  619. image (np.ndarray):
  620. max_multiply (int, float):
  621. Returns:
  622. np.ndarray:
  623. """
  624. image = image.astype(float)
  625. low, high = np.min(image), np.max(image)
  626. multiply = min(255 / (high - low), max_multiply)
  627. add = (255 - multiply * (low + high)) / 2
  628. image = cv2.add(cv2.multiply(image, multiply), add)
  629. image[image > 255] = 255
  630. image[image < 0] = 0
  631. return image.astype(np.uint8)
  632. def image_left_strip(image, threshold, length):
  633. """
  634. In `DAILY:200/200` strip `DAILY:` and leave `200/200`
  635. Args:
  636. image (np.ndarray): (height, width)
  637. threshold (int):
  638. 0-255
  639. The first column with brightness lower than this
  640. will be considered as left edge.
  641. length (int):
  642. Strip this length of image after the left edge
  643. Returns:
  644. np.ndarray:
  645. """
  646. brightness = np.mean(image, axis=0)
  647. match = np.where(brightness < threshold)[0]
  648. if len(match):
  649. left = match[0] + length
  650. total = image.shape[1]
  651. if left < total:
  652. image = image[:, left:]
  653. return image
  654. def red_overlay_transparency(color1, color2, red=247):
  655. """Calculate the transparency of red overlay.
  656. Args:
  657. color1: origin color.
  658. color2: changed color.
  659. red(int): red color 0-255. Default to 247.
  660. Returns:
  661. float: 0-1
  662. """
  663. return (color2[0] - color1[0]) / (red - color1[0])
  664. def color_bar_percentage(image, area, prev_color, reverse=False, starter=0, threshold=30):
  665. """
  666. Args:
  667. image:
  668. area:
  669. prev_color:
  670. reverse: True if bar goes from right to left.
  671. starter:
  672. threshold:
  673. Returns:
  674. float: 0 to 1.
  675. """
  676. image = crop(image, area)
  677. image = image[:, ::-1, :] if reverse else image
  678. length = image.shape[1]
  679. prev_index = starter
  680. for _ in range(1280):
  681. bar = color_similarity_2d(image, color=prev_color)
  682. index = np.where(np.any(bar > 255 - threshold, axis=0))[0]
  683. if not index.size:
  684. return prev_index / length
  685. else:
  686. index = index[-1]
  687. if index <= prev_index:
  688. return index / length
  689. prev_index = index
  690. prev_row = bar[:, prev_index] > 255 - threshold
  691. if not prev_row.size:
  692. return prev_index / length
  693. prev_color = np.mean(image[:, prev_index], axis=0)
  694. return 0.