rendering.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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_circle(cx, cy, r):
  24. def fn(x, y):
  25. return (x-cx)*(x-cx) + (y-cy)*(y-cy) <= r * r
  26. return fn
  27. def point_in_rect(xmin, xmax, ymin, ymax):
  28. def fn(x, y):
  29. return x >= xmin and x <= xmax and y >= ymin and y <= ymax
  30. return fn
  31. def point_in_triangle(a, b, c):
  32. a = np.array(a)
  33. b = np.array(b)
  34. c = np.array(c)
  35. def fn(x, y):
  36. v0 = c - a
  37. v1 = b - a
  38. v2 = np.array((x, y)) - a
  39. # Compute dot products
  40. dot00 = np.dot(v0, v0)
  41. dot01 = np.dot(v0, v1)
  42. dot02 = np.dot(v0, v2)
  43. dot11 = np.dot(v1, v1)
  44. dot12 = np.dot(v1, v2)
  45. # Compute barycentric coordinates
  46. inv_denom = 1 / (dot00 * dot11 - dot01 * dot01)
  47. u = (dot11 * dot02 - dot01 * dot12) * inv_denom
  48. v = (dot00 * dot12 - dot01 * dot02) * inv_denom
  49. # Check if point is in triangle
  50. return (u >= 0) and (v >= 0) and (u + v) < 1
  51. return fn
  52. def highlight_img(img, color=(255, 255, 255), alpha=0.30):
  53. """
  54. Add highlighting to an image
  55. """
  56. blend_img = img + alpha * (np.array(color, dtype=np.uint8) - img)
  57. blend_img = blend_img.clip(0, 255).astype(np.uint8)
  58. img[:, :, :] = blend_img