Python 이미지 합치기.

- 45 x 45 이미지 세장을 가로로 붙이기.

- 이미지 사이즈 지정 135 x 45


핵심 코드.

# 새로운 이미지 생성 L = 흑백, 컬러는 RGB, 튜플 형식(이미지 가로 길이, 이미지 세로 길이)

result = Image.new("L",(result_width, result_height))

# 이미지 붙이기(추가할 이미지 , 붙일 위치(가로, 세로))

result.paste(im=input_img_1, box=(0, 0))

# 가로로 붙여줄 꺼기 떄문에 가로 위치를 이미지 크기만큼 이동.

result.paste(im=inpit_oper_img, box=(45, 0))

# 가로로 붙여줄 꺼기 떄문에 가로 위치를 이미지 크기만큼 이동.

result.paste(im=input_img_2, box=(90, 0))


# 이미지 저장. (경로.확장자)

result.save(r'E:\deep_learning\handwrittenmathsymbols\data\new_img\1_2_+\1_2_+_{0}.jpg'.format(idx))



전체코드

import random

import os 

from PIL import Image


# 각 이미지 사이즈 45 x 45

# 새로만들 이미지 사이즈.  -> 가로로 세장 붙이기. 135 x 45

result_width = 135

result_height = 45


# input 파일 path 

input_path_1 = r'E:\deep_learning\handwrittenmathsymbols\data\test\1'

input_path_2 = r'E:\deep_learning\handwrittenmathsymbols\data\test\2'

oper_path = r'E:\deep_learning\handwrittenmathsymbols\data\test\+'


# path 폴더 안의 파일 리스트 가져오기.

file_list_input_1 = os.listdir(input_path_1)

file_list_input_2 = os.listdir(input_path_2)

file_list_oper = os.listdir(oper_path)


# 파일 폴더별 파일 개수 저장.

random_input_1 = len(file_list_input_1)

random_input_2 = len(file_list_input_2)

random_input_oper = len(file_list_oper)


#파일_리네임_변수

idx = 0


# 랜덤으로 파일 100개 생성.

for i in range(100):

    idx += 1


    # 1 ~ 파일 개수 사이의 랜덤 넘버 생성. 

    random_num_input_1 =  random.randrange(0,random_input_1)

    random_num_input_2 =  random.randrange(0,random_input_2)

    random_num_input_oper =  random.randrange(0,random_input_oper)


    # 각 파일의 이미지 불러오기.

    input_img_1 = Image.open(r'E:\deep_learning\handwrittenmathsymbols\data\test\1\1_{0}.jpg'.format(random_num_input_1))

    inpit_oper_img = Image.open(r'E:\deep_learning\handwrittenmathsymbols\data\test\+\+_{0}.jpg'.format(random_num_input_2))

    input_img_2 = Image.open(r'E:\deep_learning\handwrittenmathsymbols\data\test\2\2_{0}.jpg'.format(random_num_input_oper))


    # 흑백이미지 생성 및 이미지 가로로 붙이기.

    result = Image.new("L",(result_width, result_height))

    result.paste(im=input_img_1, box=(0, 0))

    result.paste(im=inpit_oper_img, box=(45, 0))

    result.paste(im=input_img_2, box=(90, 0))


    # 이미지 저장.

    result.save(r'E:\deep_learning\handwrittenmathsymbols\data\new_img\1_2_+\1_2_+_{0}.jpg'.format(idx))


Python 파일 이름 변경.

os.rename('원래파일', '변경할 파일')

-> 파일 경로와 파일명 지정 후, 변경할 파일 경로 및 파일이름 확장자

ex) os.rename('path/파일명.확장자', 'path/변경할파일명.확장자')


import os


# 원본 데이터셋 폴더 접근.

input_path_1 = r'E:\deep_learning\handwrittenmathsymbols\data\extracted_images\+'

file_list_input_1 = os.listdir(input_path_1)


# 파일_네임_번호

idx = 0

# 원본 파일 순회하며 -> 파일 리네임.

for i in file_list_input_1:

    idx += 1

    os.rename(r'E:\deep_learning\handwrittenmathsymbols\data\extracted_images\+\{0}'.format(i),r'E:\deep_learning\handwrittenmathsymbols\data\test\+\+_{0}.jpg'.format(idx))



Anaconda Prompt -> pip install py_translator


from py_translator import Translator


s = Translator().translate(text='안녕하세요 나는 대학생 입니다', dest='en').text

print(s)



PCA & PCR Code


# -*- coding: utf-8 -*-


# DO NOT CHANGE

from sklearn import datasets

import numpy as np

import matplotlib.pyplot as plt

from sklearn.decomposition import PCA

from sklearn.linear_model import LinearRegression


def cal_PC(X, n_components):

    # X: input data matrix

    # n_components: the number of principal components

    # return (eigenvalues of n_components of PCs, n_feature*n_components matrix (each column is PC))

    

    # HINT: np.linalg.eigh

    XT = X.T

    for i in range(len(XT)):

        XT[i] -= XT[i].mean()

    

    

    cov = np.matmul(XT,X)                       #eigh... plot 그림 이상.

    eigenvalue_list, eigvector_list = np.linalg.eig(cov)

    eigenvalue = eigenvalue_list[:n_components]

    

    eigenvector = []

    for i in range(n_components):

        val = eigvector_list[:,i]

        eigenvector.append(val)

        

    eigenvector = np.asarray(eigenvector)

    

    return eigenvalue, eigenvector

    

    

def proj_PC(X,eigvec):

    # X: input data matrix

    # eigvec: n_feature*n_components matrix (each column is PC)

    # return n_data*n_components transformed data matrix

    data_matrix = np.matmul(X, eigvec.T)

    

    return data_matrix

    

def PCR(X, y, n_components):

    # X: input data matrix

    # y: output target vector

    # n_components: the number of principal components

    # return regression model

    regression = LinearRegression()

    eigenvalue, eigenvector = cal_PC(X, n_components)

    T = proj_PC(X,eigenvector)

    regression_model = regression.fit(T,y)

    

    return regression_model


# PCA

iris=datasets.load_iris()

X1=iris.data

y1=iris.target

n_components=2


eigval,eigvec=cal_PC(X1, n_components)

T1=proj_PC(X1, eigvec)


# TODO: Get transformed data using PCA implemented by scikit-learn

pca = PCA(n_components=2)

pca.fit(X1)

T = pca.transform(X1)


# TODO: Plot

plt.scatter(T[:,0], T[:,1], c=y1)

plt.scatter(T1[:,0], T1[:,1], c=y1)


# Regression

n_components=4

boston=datasets.load_boston()

X2=boston.data

y2=boston.target

reg_pca=PCR(X2,y2,n_components)


# TODO: Build a regression model using all features

reg = LinearRegression()

reg.fit(X2, y2)

# TODO: Compare R-square using all samples of PCR with ordinary regression model

reg_pcr = PCR(X2, y2, n_components)

eigval,eigvec=cal_PC(X2, n_components)

T2=proj_PC(X2, eigvec)


reg.score(X2, y2)

reg_pcr.score(T2, y2)



우분트 환경 파이썬 파일 GPU 실행.


# 파이썬 실행.

CUDA_VISIBLE_DEVICES=0 python tsne.py



# GPU 할당량 보기.

nvidia-smi 


+ Recent posts