rendering.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import math
  2. import numpy as np
  3. # TODO: anti-aliased version, fill_coords_aa?
  4. def fill_coords(img, fn, color):
  5. """
  6. Fill pixels of an image with coordinates matching a filter function
  7. """
  8. for y in range(img.shape[0]):
  9. for x in range(img.shape[1]):
  10. yf = (y + 0.5) / img.shape[0]
  11. xf = (x + 0.5) / img.shape[1]
  12. if fn(xf, yf):
  13. img[y, x] = color
  14. return img
  15. def rotate_fn(fin, cx, cy, theta):
  16. def fout(x, y):
  17. x = x - cx
  18. y = y - cy
  19. x2 = cx + x * math.cos(-theta) - y * math.sin(-theta)
  20. y2 = cy + y * math.cos(-theta) + x * math.sin(-theta)
  21. return fin(x2, y2)
  22. return fout
  23. def point_in_line(x0, y0, x1, y1, r):
  24. p0 = np.array([x0, y0])
  25. p1 = np.array([x1, y1])
  26. dir = p1 - p0
  27. dist = np.linalg.norm(dir)
  28. dir = dir / dist
  29. xmin = min(x0, x1) - r
  30. xmax = max(x0, x1) + r
  31. ymin = min(y0, y1) - r
  32. ymax = max(y0, y1) + r
  33. def fn(x, y):
  34. # Fast, early escape test
  35. if x < xmin or x > xmax or y < ymin or y > ymax:
  36. return False
  37. q = np.array([x, y])
  38. pq = q - p0
  39. # Closest point on line
  40. a = np.dot(pq, dir)
  41. a = np.clip(a, 0, dist)
  42. p = p0 + a * dir
  43. dist_to_line = np.linalg.norm(q - p)
  44. return dist_to_line <= r
  45. return fn
  46. def point_in_circle(cx, cy, r):
  47. def fn(x, y):
  48. return (x-cx)*(x-cx) + (y-cy)*(y-cy) <= r * r
  49. return fn
  50. def point_in_rect(xmin, xmax, ymin, ymax):
  51. def fn(x, y):
  52. return x >= xmin and x <= xmax and y >= ymin and y <= ymax
  53. return fn
  54. def point_in_triangle(a, b, c):
  55. a = np.array(a)
  56. b = np.array(b)
  57. c = np.array(c)
  58. def fn(x, y):
  59. v0 = c - a
  60. v1 = b - a
  61. v2 = np.array((x, y)) - a
  62. # Compute dot products
  63. dot00 = np.dot(v0, v0)
  64. dot01 = np.dot(v0, v1)
  65. dot02 = np.dot(v0, v2)
  66. dot11 = np.dot(v1, v1)
  67. dot12 = np.dot(v1, v2)
  68. # Compute barycentric coordinates
  69. inv_denom = 1 / (dot00 * dot11 - dot01 * dot01)
  70. u = (dot11 * dot02 - dot01 * dot12) * inv_denom
  71. v = (dot00 * dot12 - dot01 * dot02) * inv_denom
  72. # Check if point is in triangle
  73. return (u >= 0) and (v >= 0) and (u + v) < 1
  74. return fn
  75. def highlight_img(img, color=(255, 255, 255), alpha=0.30):
  76. """
  77. Add highlighting to an image
  78. """
  79. blend_img = img + alpha * (np.array(color, dtype=np.uint8) - img)
  80. blend_img = blend_img.clip(0, 255).astype(np.uint8)
  81. img[:, :, :] = blend_img