상세 컨텐츠

본문 제목

[python] 이미지 변형 (wrap) 및 회전 (rotate) 코드

Tech/AI Study

by Enjoy Something 2019. 9. 6. 10:22

본문

이미지 wrap 하는 코드

 

OpenCV를 사용하여 이미지를 불러온 뒤, 뒤틀리는 효과를 주어 약간 변형된 이미지처럼 보이게 함.

 

 

 

 

import random
import numpy
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage.interpolation import map_coordinates
import cv2
import glob
import os

#path_dir = '/home/datarepublic2/Downloads/AI/examles/fast_neural_style/crop2/data'
#file_list = os.listdir(path_dir)



def elastic_distort(image, alpha, sigma):
"""Perform elastic distortion on an image.
Here, alpha refers to the scaling factor that controls the intensity of the
deformation. The sigma variable refers to the Gaussian filter standard
deviation.
"""

random_state = numpy.random.RandomState(None)
shape = image.shape

dx = gaussian_filter(
(random_state.rand(*shape) * 2 - 1),
sigma, mode="constant"
) * alpha
dy = gaussian_filter(
(random_state.rand(*shape) * 2 - 1),
sigma, mode="constant"
) * alpha

x, y = numpy.meshgrid(numpy.arange(shape[1]), numpy.arange(shape[0]))
indices = numpy.reshape(y+dy, (-1, 1)), numpy.reshape(x+dx, (-1, 1))
return map_coordinates(image, indices, order=1).reshape(shape)

def Rotate_Bound(image, angle):
# grab the dimensions of the image and then determine the
# center
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)

# grab the rotation matrix (applying the negative of the
# angle to rotate clockwise), then grab the sine and cosine
# (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0)
cos = numpy.abs(M[0, 0])
sin = numpy.abs(M[0, 1])

# compute the new bounding dimensions of the image
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))

# adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY

# perform the actual rotation and return the image
return cv2.warpAffine(image, M, (nW, nH))




# 이미지 변형
if __name__ == '__main__':

path = glob.glob('./data/*.jpg') # read the all jpg images in folder
arr_img = []

for img in path:
n = cv2.imread(img)
arr_img.append(n)
print(img)

#img = cv2.imread(arr_img[image])
n[n >= 128] = 255
gray = cv2.cvtColor(n,cv2.COLOR_BGR2GRAY)
gray = 255 - gray
distorted_array = elastic_distort(
gray,
alpha=random.randint(30, 40),
sigma=random.randint(6, 7)
)
distorted_array = 255 - distorted_array
#print(distorted_array)
#cv2.imwrite('a.jpg', distorted_array)
cv2.imwrite(img[:7]+'4'+img[8:],distorted_array)



'''
# 이미지 회전
if __name__ == '__main__':
img = cv2.imread("in.jpg")
rot_img = Rotate_Bound(img,90)
cv2.imwrite("in1.jpg", rot_img)
'''

관련글 더보기

댓글 영역