algorithm.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import cv2
  2. import numpy as np
  3. import math
  4. img = cv2.imread("pencil.png")
  5. rows, cols, _ = img.shape
  6. # Principle axis of object, defined relative to image
  7. REL_AXIS = [(0.5, 0), (0.5, 1)]
  8. # Principle axis in pixels
  9. a_point1 = np.array((int(REL_AXIS[0][0] * cols), int(REL_AXIS[0][1] * rows)))
  10. a_point2 = np.array((int(REL_AXIS[1][0] * cols), int(REL_AXIS[1][1] * rows)))
  11. a_len = int(np.linalg.norm(a_point1 - a_point2))
  12. a_direction_vec = a_point2 - a_point1
  13. a_udir = a_direction_vec / a_len
  14. def count_pixels(start, udirection):
  15. it = start
  16. count = 0
  17. while it[0] < cols and it[1] < rows and it[0] >= 0 and it[1] >= 0:
  18. pt = img[int(it[1]), int(it[0])]
  19. if np.all(pt == 0):
  20. break
  21. it = (it[0] + udirection[0], it[1] + udirection[1])
  22. count = count + 1
  23. return count
  24. perp_dir = np.array([-a_udir[1], a_udir[0]])
  25. perp_lens = []
  26. for l in range(a_len):
  27. start = a_point1 + a_udir*l
  28. perp_lens += [count_pixels(start, perp_dir)]
  29. depthImage = img.copy()
  30. for y in range(rows):
  31. for x in range(cols):
  32. C = np.array((x, y))
  33. PAR = np.dot(a_udir, C)
  34. PERP = C - PAR * a_udir - a_point1
  35. depth = (perp_lens[int(PAR)] ** 2) - np.linalg.norm(PERP)**2
  36. if depth < 0:
  37. depth = 0
  38. depth = math.sqrt(depth)
  39. depthImage[y, x] = (depth * 4, depth * 4, depth * 4)
  40. def make_target(angle):
  41. targetImage = np.zeros((rows * 3, rows * 3, 3), np.uint8)
  42. cost = math.cos(angle)
  43. sint = math.sin(angle)
  44. for y in range(rows):
  45. for x in range(cols):
  46. depth = int(depthImage[y, x][0])
  47. # Do 3D transform: matrix multiply or whatever
  48. (xP, yP, zP) = (x + rows, round(cost*y - sint*depth) + rows, depth)
  49. if depth > 0:
  50. targetImage[yP + 1, xP - 1] = img[y, x]
  51. targetImage[yP + 1, xP + 0] = img[y, x]
  52. targetImage[yP + 1, xP + 1] = img[y, x]
  53. targetImage[yP + 0, xP - 1] = img[y, x]
  54. targetImage[yP + 0, xP + 0] = img[y, x]
  55. targetImage[yP + 0, xP + 1] = img[y, x]
  56. targetImage[yP - 1, xP - 1] = img[y, x]
  57. targetImage[yP - 1, xP + 0] = img[y, x]
  58. targetImage[yP - 1, xP + 1] = img[y, x]
  59. return targetImage
  60. # Create video
  61. for angle in range(90):
  62. #cv2.waitKey(1)
  63. target = make_target(angle * math.pi / 180)
  64. #cv2.imshow("Target", target)
  65. cv2.imwrite("/dev/shm/" + str(100+angle)[1:] + ".bmp", target)