상세 컨텐츠

본문 제목

[Image] Image resize & convert(python)

IT Convergence Engineering/AI 버섯 어플

by Soo_buglosschestnut 2020. 7. 30. 21:53

본문

Image resize & convert(python)


 

Image resize code


from PIL import Image
import os
import argparse

def rescale_images(directory, size):
    for img in os.listdir(directory):
        im = Image.open(directory+'\\'+img)
        im_resized = im.resize(size, Image.ANTIALIAS)
        im_resized.save(directory+'\\'+img)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Rescale images")
    parser.add_argument('-d', '--directory', type=str, required=True, help='Directory containing the images')
    parser.add_argument('-s', '--size', type=int, nargs=2, required=True, metavar=('width', 'height'), help='Image size')
    args = parser.parse_args()
    rescale_images(args.directory, args.size)

 

  • python (resize code filename).py -d (To resize directory) -s (width_size height_size)

ps. 실제 실행 시 (~~) 괄호는 생략!


Image convert code


import numpy as np
import os
from os import listdir
from os.path import isfile, join
from PIL import Image
import argparse
 
 
np.random.seed(3)
 
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img


parser = argparse.ArgumentParser(description="generate images")
parser.add_argument('-d', '--directory', type=str, required=True, help='Directory containing the images')
parser.add_argument('-s', '--savedirectory', type=str, required=True, help='Directory savingthe images')
args = parser.parse_args()

 
data_datagen = ImageDataGenerator(rescale=1./255)
 
data_datagen = ImageDataGenerator(rescale=1./255,
                                   rotation_range=30, 
                                   shear_range=5.5,  
                                   width_shift_range=0.1,
                                   height_shift_range=0.1,
                                   zoom_range=0.2,
                                   horizontal_flip=True,
                                   vertical_flip=True,
                                   fill_mode='nearest') 
 

filename_in_dir = []
filename = './' + args.directory
savefilename = './'+ args.savedirectory
counts= 0
for root, dirs, files in os.walk(filename): #하위폴더
    for  fname in files:
        full_fname = os.path.join(root, fname)
        filename_in_dir.append(full_fname)
 
for file_image in filename_in_dir:
    counts += 1
    print(file_image, counts)
    img = load_img(file_image) 
    x = img_to_array(img)
    x = x.reshape((1,) + x.shape)
 
    i = 0
 
    for batch in data_datagen.flow(x,save_to_dir=savefilename, save_prefix='', save_format='jpg'):
        i += 1
        if i > 3: # 3배 8배 ----
            break

 

  • python (convert code filename).py -d (To convert directory) -s (To save directory)

ps. 실제 실행 시 (~~) 괄호는 생략!

더보기

rotation_range = 90

 

지정된 각도 범위내에서 임의로 원본이미지를 회전시킵니다. 단위는 도이며, 정수형입니다. 예를 들어 90이라면 0도에서 90도 사이에 임의의 각도로 회전시킵니다. 

 

width_shift_range = 0.1

 

지정된 수평방향 이동 범위내에서 임의로 원본이미지를 이동시킵니다. 수치는 전체 넓이의 비율(실수)로 나타냅니다. 예를 들어 0.1이고 전체 넓이가 100이면, 10픽셀 내외로 좌우 이동시킵니다. 

 

height_shift_range = 0.1

 

지정된 수직방향 이동 범위내에서 임의로 원본이미지를 이동시킵니다. 수치는 전체 높이의 비율(실수)로 나타냅니다. 예를 들어 0.1이고 전체 높이가 100이면, 10픽셀 내외로 상하 이동시킵니다. 

 

shear_range = 0.5

 

밀림 강도 범위내에서 임의로 원본이미지를 변형시킵니다. 수치는 시계반대방향으로 밀림 강도를 라디안으로 나타냅니다. 예를 들어 0.5이라면, 0.5 라이안내외로 시계반대방향으로 변형시킵니다. 

 

zoom_range = 0.3

 

지정된 확대/축소 범위내에서 임의로 원본이미지를 확대/축소합니다. “1-수치”부터 “1+수치”사이 범위로 확대/축소를 합니다. 예를 들어 0.3이라면, 0.7배에서 1.3배 크기 변화를 시킵니다. 

 

horizontal_flip = True

 

수평방향으로 뒤집기를 합니다. 

 

vertical_flip = True

 

수직방향으로 뒤집기를 합니다.


 

출처

https://github.com/khw11044/image-resize-convert-size

 

khw11044/image-resize-convert-size

Contribute to khw11044/image-resize-convert-size development by creating an account on GitHub.

github.com

 

관련글 더보기