fork download
  1. import numpy as np
  2.  
  3. def rotate_coords(x, y, theta, ox, oy):
  4. """Rotate arrays of coordinates x and y by theta radians about the
  5. point (ox, oy).
  6.  
  7. """
  8. s, c = np.sin(theta), np.cos(theta)
  9. x, y = np.asarray(x) - ox, np.asarray(y) - oy
  10. return x * c - y * s + ox, x * s + y * c + oy
  11.  
  12. def rotate_image(src, theta, ox, oy, fill=255):
  13. """Rotate the image src by theta radians about (ox, oy).
  14. Pixels in the result that don't correspond to pixels in src are
  15. replaced by the value fill.
  16.  
  17. """
  18. # Images have origin at the top left, so negate the angle.
  19. theta = -theta
  20.  
  21. # Dimensions of source image. Note that scipy.misc.imread loads
  22. # images in row-major order, so src.shape gives (height, width).
  23. sh, sw = src.shape
  24.  
  25. # Rotated positions of the corners of the source image.
  26. cx, cy = rotate_coords([0, sw, sw, 0], [0, 0, sh, sh], theta, ox, oy)
  27.  
  28. # Determine dimensions of destination image.
  29. dw, dh = (int(np.ceil(c.max() - c.min())) for c in (cx, cy))
  30.  
  31. # Coordinates of pixels in destination image.
  32. dx, dy = np.meshgrid(np.arange(dw), np.arange(dh))
  33.  
  34. # Corresponding coordinates in source image. Since we are
  35. # transforming dest-to-src here, the rotation is negated.
  36. sx, sy = rotate_coords(dx + cx.min(), dy + cy.min(), -theta, ox, oy)
  37.  
  38. # Select nearest neighbour.
  39. sx, sy = sx.round().astype(int), sy.round().astype(int)
  40.  
  41. # Mask for valid coordinates.
  42. mask = (0 <= sx) & (sx < sw) & (0 <= sy) & (sy < sh)
  43.  
  44. # Create destination image.
  45. dest = np.empty(shape=(dh, dw), dtype=src.dtype)
  46.  
  47. # Copy valid coordinates from source image.
  48. dest[dy[mask], dx[mask]] = src[sy[mask], sx[mask]]
  49.  
  50. # Fill invalid coordinates.
  51. dest[dy[~mask], dx[~mask]] = fill
  52.  
  53. return dest
Success #stdin #stdout 0.2s 26120KB
stdin
Standard input is empty
stdout
Standard output is empty