Skip to content

Instantly share code, notes, and snippets.

@lagoushque
Last active March 12, 2017 17:41
Show Gist options
  • Save lagoushque/ba94cbbc574b103efac38b961d68f6d1 to your computer and use it in GitHub Desktop.
Save lagoushque/ba94cbbc574b103efac38b961d68f6d1 to your computer and use it in GitHub Desktop.
import cv2
import math
# Input example: /home/b1rd/pyexample/Berneys4.jpg 45 0.5 1
def transform(image, a, c, i):
img = cv2.imread(image)
rows,cols, ch = img.shape
croppedWidth, croppedHeight = map(int, rect_max_area(cols, rows, math.radians(a)))
dst = crop_around_center(rotate_image(img, a), croppedWidth, croppedHeight)
modifiedWidth, modifiedHeight = int(dst.shape[1]*c), int(dst.shape[0]/c)
stretched = cv2.resize(dst, (modifiedWidth, modifiedHeight))
cv2.imwrite('/home/b1rd/pyexample/rotated.jpg', dst)
cv2.imwrite('/home/b1rd/pyexample/resized.jpg', stretched)
interpolated_img = cv2.resize(dst, (modifiedWidth, modifiedHeight), interpolation=i)
cv2.imwrite('/home/b1rd/pyexample/interpolated.bmp', interpolated_img)
cv2.imshow('Rotated by '+str(a)+' degrees',dst)
cv2.imshow('Stretched with coefficient = ' + str(c), stretched)
cv2.waitKey(0)
cv2.destroyAllWindows()
def crop_around_center(image, width, height):
image_size = (image.shape[1], image.shape[0])
image_center = (int(image_size[0] * 0.5), int(image_size[1] * 0.5))
if(width > image_size[0]):
width = image_size[0]
if(height > image_size[1]):
height = image_size[1]
x1 = int(image_center[0] - width * 0.5)
x2 = int(image_center[0] + width * 0.5)
y1 = int(image_center[1] - height * 0.5)
y2 = int(image_center[1] + height * 0.5)
return image[y1:y2, x1:x2]
def rotate_image(image, angle):
height, width, ch = image.shape
height_big = height * 2
width_big = width * 2
image_big = cv2.resize(image, (width_big, height_big))
image_center = (width_big/2, height_big/2)#rotation center
rot_mat = cv2.getRotationMatrix2D(image_center,angle, 0.5)
result = cv2.warpAffine(image_big, rot_mat, (width_big, height_big), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255, 255))
return result
def rect_max_area(w, h, angle):
if w <= 0 or h <= 0:
return 0,0
width_is_longer = w >= h
side_long, side_short = (w,h) if width_is_longer else (h,w)
sin_a, cos_a = abs(math.sin(angle)), abs(math.cos(angle))
if side_short <= 2.*sin_a*cos_a*side_long:
x = 0.5*side_short
wr,hr = (x/sin_a,x/cos_a) if width_is_longer else (x/cos_a,x/sin_a)
else:
cos_2a = cos_a*cos_a - sin_a*sin_a
wr,hr = (w*cos_a - h*sin_a)/cos_2a, (h*cos_a - w*sin_a)/cos_2a
return wr,hr
def main():
input = raw_input().split()
img, angle, coeff, interp = str(input[0]), int(input[1]), float(input[2]), int(input[3])
print img, angle, coeff, interp
print(transform(img, angle, coeff, interp))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment