Skip to content

Instantly share code, notes, and snippets.

@rkdgusrn1212
Last active May 23, 2019 03:58
Show Gist options
  • Save rkdgusrn1212/58aeffa80996757e356c0bcd44b3d09c to your computer and use it in GitHub Desktop.
Save rkdgusrn1212/58aeffa80996757e356c0bcd44b3d09c to your computer and use it in GitHub Desktop.
Image Geometric Transformation in Python (without PIL.Image.resize() or rotate())
from PIL import Image
import math
img_path = input("변환시킬 이미지의 경로를 입력하세요 : ")#크기를 변환할 이미지 경로 입력.
img = Image.open(img_path)
img.show("변환 전 이미지")
width, height = img.size#원본 이미지 크기
width_rate = float(input("가로방향 변환 비율 : "))
height_rate = float(input("새로방향 변환 비율 : "))
rotate_degree = float(input("반시계 회전각(도) : "))
rotate = -rotate_degree*math.pi/180 #이미지의 좌표계의 수직축이 데카르트 좌표계에 수평축 대칭이라 반대로 회전해야됨.
scaled_width = width*width_rate #스케일링된 이미지의 가로
scaled_height = height*height_rate #스케일링된 이미지의 새로
rotated_width = math.ceil(abs(scaled_width*math.cos(rotate))+abs(scaled_height*math.sin(rotate))) #회전까지 시킨 이미지의 가로
rotated_height = math.ceil(abs(scaled_width*math.sin(rotate))+abs(scaled_height*math.cos(rotate))) #회전까지 시킨 이미지의 새로
new_img = Image.new("RGB",(rotated_width, rotated_height)) #새 이미지 생성(순방향)
new_img_rev = Image.new("RGB",(rotated_width, rotated_height)) #새 이미지 생성(역방향)
#순방향으로 이미지 맵핑하기
for i in range(0, height):
new_y = i*height_rate#스케일링된 이미지의 y값 찾기(회전 없을때)
for j in range(0, width):
new_x = j*width_rate#스케일링된 이미지의 x값 찾기(회전 없을때)
#스케일링된 이미지의 중심을 기준으로 회전시키기
rotated_new_x = round((new_x-scaled_width/2.)*math.cos(rotate)-(new_y-scaled_height/2.)*math.sin(rotate) + rotated_width/2.)
rotated_new_y = round((new_x-scaled_width/2.)*math.sin(rotate)+(new_y-scaled_height/2.)*math.cos(rotate) + rotated_height/2.)
if rotated_new_x < rotated_width and rotated_new_x >= 0 and rotated_new_y < rotated_height and rotated_new_y >= 0 :
new_img.putpixel((rotated_new_x, rotated_new_y), img.getpixel((j, i)))
new_img.show()
new_img.save("geo_trans_image_w"+str(width_rate).replace(".","x")+"_h"+str(height_rate).replace(".","x")+"_r"+str(rotate_degree)+".png")
#역방향으로 이미지 맵핑하기
for i in range(0, rotated_height):
for j in range(0, rotated_width):
#좌표를 역방향 회전하고 이미지를 0,0에 붙여서 스케일링만 적용된 좌표를 구한다.
scaled_ori_x = (j-rotated_width/2.)*math.cos(-rotate)-(i-rotated_height/2.)*math.sin(-rotate) + scaled_width/2.
scaled_ori_y = (j-rotated_width/2.)*math.sin(-rotate)+(i-rotated_height/2.)*math.cos(-rotate) + scaled_height/2.
#회전을 제거한 좌표를 이용해 스케일링 되기 전 좌표 구하기
ori_x = round(scaled_ori_x/width_rate)
ori_y = round(scaled_ori_y/height_rate)
if ori_x >=0 and ori_x < width and ori_y < height and ori_y >= 0 :
new_img_rev.putpixel((j, i), img.getpixel((ori_x,ori_y)))
new_img_rev.show()
new_img_rev.save("geo_trans_image_rev_w"+str(width_rate).replace(".","x")+"_h"+str(height_rate).replace(".","x")+"_r"+str(rotate_degree)+".png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment