rendering.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. if x < xmin or x > xmax or y < ymin or y > ymax:
  35. return False
  36. q = np.array([x, y])
  37. pq = q - p0
  38. # Closest point on line
  39. a = np.dot(pq, dir)
  40. a = np.clip(a, 0, dist)
  41. p = p0 + a * dir
  42. dist_to_line = np.linalg.norm(q - p)
  43. return dist_to_line <= r
  44. return fn
  45. def point_in_circle(cx, cy, r):
  46. def fn(x, y):
  47. return (x-cx)*(x-cx) + (y-cy)*(y-cy) <= r * r
  48. return fn
  49. def point_in_rect(xmin, xmax, ymin, ymax):
  50. def fn(x, y):
  51. return x >= xmin and x <= xmax and y >= ymin and y <= ymax
  52. return fn
  53. def point_in_triangle(a, b, c):
  54. a = np.array(a)
  55. b = np.array(b)
  56. c = np.array(c)
  57. def fn(x, y):
  58. v0 = c - a
  59. v1 = b - a
  60. v2 = np.array((x, y)) - a
  61. # Compute dot products
  62. dot00 = np.dot(v0, v0)
  63. dot01 = np.dot(v0, v1)
  64. dot02 = np.dot(v0, v2)
  65. dot11 = np.dot(v1, v1)
  66. dot12 = np.dot(v1, v2)
  67. # Compute barycentric coordinates
  68. inv_denom = 1 / (dot00 * dot11 - dot01 * dot01)
  69. u = (dot11 * dot02 - dot01 * dot12) * inv_denom
  70. v = (dot00 * dot12 - dot01 * dot02) * inv_denom
  71. # Check if point is in triangle
  72. return (u >= 0) and (v >= 0) and (u + v) < 1
  73. return fn
  74. def highlight_img(img, color=(255, 255, 255), alpha=0.30):
  75. """
  76. Add highlighting to an image
  77. """
  78. blend_img = img + alpha * (np.array(color, dtype=np.uint8) - img)
  79. blend_img = blend_img.clip(0, 255).astype(np.uint8)
  80. img[:, :, :] = blend_img