Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Image rotation iterator
- # Original video & blog post by jk-keller
- # https://www.youtube.com/watch?v=1UuQCDgiqVg
- # https://jk-keller.com/o__o/rotational_growth/
- # Python code by yclee126
- import cv2
- import numpy as np
- import time
- ### User Settings ###
- image_filename = 'image.png'
- angle_increment = 10 # degrees, (+): counter clockwise, (-): clockwise
- rotation_count = 100
- interpolation = cv2.INTER_CUBIC # see interpolation parameter table below
- display_frames = 1 # True(1) or False(0) -- (keys) q: quit, p: pause, s: skip
- frame_delay = 1 # milliseconds, 0: frame-by-frame, 1: fastest
- padding_color = (255, 255, 255) # BGR order
- extra_padding = 10 # pixels
- # interpolation params
- #
- # INTER_NEAREST (nearest neighbor interpolation)
- # INTER_LINEAR (bilinear interpolation)
- # INTER_CUBIC (bicubic interpolation)
- # INTER_AREA (resampling using pixel area relation)
- # INTER_LANCZOS4 (Lanczos interpolation over 8x8 neighborhood)
- ### Image processing codes ###
- img = cv2.imread(image_filename)
- h, w, *c = img.shape
- if len(c) == 0: # grayscale image
- img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
- # make canvas that can fit the diagonal line of the image + extra padding
- final_size = int((h*h + w*w)**(1/2) + extra_padding*2)
- canvas = np.zeros((final_size, final_size, 3), dtype='uint8')
- canvas[:, :] = padding_color
- # paste image in the center
- x_offset = int((final_size - w) / 2)
- y_offset = int((final_size - h) / 2)
- canvas[y_offset:y_offset+h, x_offset:x_offset+w] = img
- # calc infos
- iterations = abs(round(360 / angle_increment * rotation_count))
- print(f'Increment: {angle_increment} deg, Rotations: {rotation_count}, Iterations: {iterations}')
- print_progress = lambda i: print(f'Progress: {i/iterations*100:.2f}% (r:{int(abs(i*angle_increment) / 360)}, i:{i})', end='\r')
- # main rotation loop
- rotated = canvas
- prev_print_time = time.time()
- for i in range(iterations):
- # print progress
- if time.time() - prev_print_time > 0.1 or display_frames: # prevent print() slowing down calculation
- print_progress(i)
- prev_print_time = time.time()
- # rotate canvas
- matrix = cv2.getRotationMatrix2D((final_size/2, final_size/2), angle_increment, 1.0)
- rotated = cv2.warpAffine(
- rotated,
- matrix,
- (final_size, final_size),
- None,
- interpolation,
- cv2.BORDER_CONSTANT,
- padding_color)
- if display_frames:
- # display frame
- cv2.imshow('win', rotated)
- key = cv2.waitKey(frame_delay)
- # process pause input first
- if key == ord('p'):
- key = cv2.waitKey(0)
- # process other key inputs
- if key == ord('q'):
- exit()
- elif key == ord('s'):
- display_frames = False
- cv2.destroyAllWindows()
- # display final frame
- print_progress(iterations)
- cv2.imshow('win', rotated)
- cv2.waitKey(0)
- # save image
- cv2.imwrite('output.png', rotated)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement