HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
장지원 페이지/
📕
2024 UGRP
/
Member Page
Member Page
/
권태완
권태완
/
2024/09/24 - GAN

2024/09/24 - GAN

Tags

1. GAN에 대한 추가적인 질문

  • 지난 09/09 GAN 사용법을 실제로 시도해보는 작업
 
😖
지난 GPT의 대답을 토대로 진행한 결과, 잘못된 GAN모델을 사용했다는 것을 알게 되었음!!!
 
GPT에게 photo 2 sketch CycleGAN모델을 물어보았다
🤖
이해했습니다! 목표는 사진을 스케치 스타일의 그림으로 변환하는 것이군요. CycleGAN의 "horse2zebra"처럼 특정 스타일로 변환하는 것이 아니라, 스케치 스타일로 변환하는 GAN을 원하시는 것이죠.
CycleGAN은 두 도메인 간의 변환을 목표로 하는데, "horse2zebra"는 말과 얼룩말 간의 변환을 학습한 모델이기 때문에 스케치 스타일과는 무관합니다. 대신, 스케치 변환을 위한 GAN 기반 모델을 사용할 수 있습니다.
스케치 스타일 변환을 위한 방법:
  1. 사전 학습된 스케치 변환 GAN 모델 사용:
      • 스케치로 변환하는 GAN 모델을 사용하면 사진을 스케치 스타일로 변환할 수 있습니다. 아래에 해당 모델들을 설명하겠습니다.
  1. CycleGAN을 사용하여 스케치 도메인 학습:
      • CycleGAN을 사용해 사진을 스케치 스타일로 변환하는 방법도 있습니다. 이를 위해서는 스케치 데이터셋을 준비해 두 도메인 간 변환을 학습하는 방식입니다.
1. 사전 학습된 스케치 변환 GAN 모델 사용
a. SketchKeras
SketchKeras는 사진을 스케치로 변환하는 GAN 모델입니다. PyTorch 또는 Keras 기반으로 제공되며, 스케치 스타일로 변환할 수 있는 GAN 모델입니다. 기본적으로 인물 사진을 스케치로 변환하는데 사용할 수 있습니다.
b. DeOldify (흑백 변환 확장)
DeOldify는 이미지 컬러링을 위한 모델이지만, 일부 확장 기능을 통해 이미지를 스케치 스타일로 변환할 수 있습니다. 이 모델을 사용하면 사진을 흑백 스케치로 변환할 수 있습니다.
 
c. Pencil Sketch GAN
이 GAN 모델은 사진을 연필 스케치로 변환합니다. 다양한 스케치 스타일을 적용할 수 있으며, PyTorch 및 TensorFlow로 구현된 모델이 있습니다.
 
2. CycleGAN을 사용한 스케치 변환
CycleGAN을 직접 사용해 사진을 스케치로 변환하려면 스케치 스타일의 이미지와 사진을 한 쌍으로 구성한 데이터셋이 필요합니다. 스케치 스타일로 변환된 데이터가 있을 경우 이를 CycleGAN으로 학습시키고, 이후 사진을 스케치로 변환할 수 있습니다.
 
필요한 과정:
  1. 스케치 데이터셋 확보: 실제 스케치 이미지로 구성된 데이터셋을 준비합니다.
  1. CycleGAN 학습: 사진과 스케치 간의 변환을 학습시키기 위해, 스케치 스타일의 이미지와 사진을 한 쌍으로 구성한 데이터셋을 CycleGAN에 학습시킵니다.
  1. 변환: 학습된 모델로 사진을 스케치로 변환합니다.
 
3. 추천 방법: Pretrained SketchKeras or Pencil Sketch GAN 사용
가장 빠르게 적용할 수 있는 방법은 SketchKeras나 Pencil Sketch GAN과 같은 사전 학습된 모델을 사용하는 것입니다. 이를 통해 바로 사진을 스케치로 변환할 수 있습니다.
 
다음 단계:
  1. SketchKeras나 Pencil Sketch GAN과 같은 사전 학습된 모델을 설치하고 실행하는 방법을 안내드릴 수 있습니다.
  1. CycleGAN을 사용한 스케치 변환 학습을 원하시면, 스케치 데이터셋을 준비하는 방법도 안내드리겠습니다.
어떤 방법을 선택하시겠습니까? 또는 더 구체적인 지침이 필요하시면 말씀해 주세요!
 
CycleGAN에 대해서 설명해줘
CycleGAN이란? CycleGAN은 두 개의 서로 다른 도메인 간의 이미지를 쌍으로 이루어진 데이터 없이 변환할 수 있는 이미지-이미지 변환 모델입니다. 예를 들어, 사진을 그림으로 바꾸거나, 낮 사진을 밤 사진으로 변환하는 등의 작업을 할 수 있습니다. 일반적인 GAN 모델과 달리, CycleGAN은 **사이클 일관성 손실(cycle consistency loss)**이라는 개념을 사용합니다. 이 손실은 변환된 이미지를 다시 원래 이미지로 되돌리는 과정에서 일관성을 유지하도록 학습합니다. CycleGAN의 주요 구성 요소: 두 개의 생성기(Generators): 하나는 A 도메인(예: 사진)에서 B 도메인(예: 그림)으로 이미지를 변환하고, 다른 하나는 B 도메인에서 A 도메인으로 다시 변환합니다. 두 개의 판별기(Discriminators): 각각의 도메인에 대한 이미지가 실제인지 변환된 이미지인지를 판단합니다. 사이클 일관성 손실: A에서 B로 변환된 이미지를 다시 A로 되돌렸을 때, 원본 A와 유사한지를 평가하여 학습합니다. 이 과정을 통해 쌍이 없는 데이터로도 효과적인 학습이 가능합니다.
 
 
GitHubGitHubGitHub - junyanz/CycleGAN: Software that can generate photos from paintings, turn horses into zebras, perform style transfer, and more.
GitHub - junyanz/CycleGAN: Software that can generate photos from paintings,  turn horses into zebras,  perform style transfer, and more.

GitHub - junyanz/CycleGAN: Software that can generate photos from paintings, turn horses into zebras, perform style transfer, and more.

Software that can generate photos from paintings, turn horses into zebras, perform style transfer, and more. - junyanz/CycleGAN

GitHubGitHub
이 방법을 사용하기로 하였음
 

2. GAN을 사용해서 사진을 그림으로 변환하기

 
사용환경
WSL Ubuntu 22.0.4
 
conda 가상 환경 의존성 리스트
UGRP_env_list.txt
7.8KB
 
CycleGAN 사용 방법
다운로드
  1. CycleGAN git 다운로드
    1. git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix.git cd pytorch-CycleGAN-and-pix2pix
       
  1. Pytorch 및 필요한 의존성 설치
    1. conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch pip install -r requirements.txt # CycleGAN 저장소의 요구 사항 파일을 설치
       
  1. Pre-trained model 다운로드
    1. bash ./scripts/download_cyclegan_model.sh style_monet
       
  1. 데이터 준비
    1. notion image
      → 이 때 Zone.Identifier를 지워야 한다. 커맨드 라인에 아래와 같이 입력하자
      find /datasets/mydata/ -name "*Zone*" -delete
  1. 이미지 변환 실행
    1. python test.py --dataroot ./datasets/mydata --name style_monet_pretrained --model test --input_nc 3 --no_dropout --results_dir ./output_dir --preprocess none --num_test 20000
      🤖
      • -dataroot ./datasets/my_datasets: 변환할 이미지들이 있는 폴더 경로.
      • -name style_monet_pretrained: 사전 훈련된 style_monet 모델을 사용.
      • -model test: 테스트 모드로 실행.
      • -input_nc 3: 입력 이미지의 채널 수를 3(RGB)으로 설정.
      • -no_dropout: 드롭아웃 레이어를 사용하지 않음.
      • -results_dir ./output_dir: 변환된 이미지를 저장할 출력 폴더 경로.
      • -max_dataset_size 20000: 최대 20,000개의 이미지를 처리.
      • -preprocess none: 이미지 전처리를 하지 않고 원본 크기로 처리.
       
 

3. Result

(UGRP) rnjsxodhks@DESKTOP-DA9US47:~/code/UGRP/pytorch-CycleGAN-and-pix2pix$ python test.py --dataroot ./datasets/my_datasets --name style_monet_pretrained --model test --input_nc 3 --no_dropout --results_dir ./output_dir --max_dataset_size 20000 --preprocess none --num_test 20000 ----------------- Options --------------- aspect_ratio: 1.0 batch_size: 1 checkpoints_dir: ./checkpoints crop_size: 256 dataroot: ./datasets/mydata [default: None] dataset_mode: single direction: AtoB display_winsize: 256 epoch: latest eval: False gpu_ids: 0 init_gain: 0.02 init_type: normal input_nc: 3 isTrain: False [default: None] load_iter: 0 [default: 0] load_size: 256 max_dataset_size: 20000 [default: inf] model: test model_suffix: n_layers_D: 3 name: style_monet_pretrained [default: experiment_name] ndf: 64 netD: basic netG: resnet_9blocks ngf: 64 no_dropout: True [default: False] no_flip: False norm: instance num_test: 20000 [default: 50] num_threads: 4 output_nc: 3 phase: test preprocess: none [default: resize_and_crop] results_dir: ./output_dir [default: ./results/] serial_batches: False suffix: use_wandb: False verbose: False wandb_project_name: CycleGAN-and-pix2pix ----------------- End ------------------- dataset [SingleDataset] was created initialize network with normal model [TestModel] was created loading the model from ./checkpoints/style_monet_pretrained/latest_net_G.pth /home/rnjsxodhks/code/UGRP/pytorch-CycleGAN-and-pix2pix/models/base_model.py:192: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature. state_dict = torch.load(load_path, map_location=str(self.device)) ---------- Networks initialized ------------- [Network G] Total number of parameters : 11.378 M ----------------------------------------------- creating web directory ./output_dir/style_monet_pretrained/test_latest
 
변환 후 real 이미지 삭제
위와 같은 과정을 완료하고 나면 output_dir/style_monet_pretrained/ 디렉토리 안에 fake(변환 후) 이미지와 real(변환 전) 이미지가 동시에 존재한다. 우리가 필요한 것은 fake 이미지 이므로 real 이미지를 삭제해준다
find ./output_dir/style_monet_pretrained/ -name "*_real*" -delete
 
변경 후
notion image
notion image
 
변경 전
notion image
notion image
 

4 . 9/24일 현재 amusement완료, anger 진행 중

코멘트
당장 전부 변환하고 싶었으나, 오류가 발생하였음.
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 25.59 GiB. GPU 0 has a total capacity of 15.99 GiB of which 1.79 GiB is free. Of the allocated memory 12.25 GiB is allocated by PyTorch, and 250.10 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
→ 이 오류에 대해서 총 다섯 가지의 해결 방법이 있다는 것을 확인했음…

1. 메모리 캐시 강제 해제

import torch torch.cuda.empty_cache() # 캐시된 메모리 강제 해제
  • 해당 코드를 test.py의 중간 중간에 넣어서 메모리 누수를 줄임

2. 이미지 크기 줄이기

python test.py --dataroot ./datasets/my_datasets --name style_monet_pretrained --model test --input_nc 3 --no_dropout --results_dir ./output_dir --max_dataset_size 5000 --preprocess resize --load_size 512 --crop_size 512 --num_test 5000
  • 이미지의 크기를 줄여서 사용하는 메모리 양을 줄임

3. GPU 메모리 초기화

nvidia-smi로 메모리를 확인하고 GPU를 많이 사용하고 있는 프로세스가 있는 경우 강제 종료하여 메모리를 확보
nvidia-smi
notion image
만약 Memory-Usage 부분에서 과다하게 많이 사용하는 경우
ps aux | grep python
notion image
이 과정에서 과도하게 많은 GPU 메모리를 차지하는 프로세서를 강제 종료한다
kill -9 65816 <- 이게 PID
 

4. Mixed Precision Training (FP16) 사용

Pytorch의 AMP(Automatic Mixed Precision)을 사용하면 half-precision(FP-16) 연산으로 GPU 메모리 사용량을 절감 가능하다. 모델이 메모리를 덜 사용하게 만들기 위해 Pytorch의 torch.cuda.amp 모듈을 활용 가능하다. 다음과 같이 autocast를 사용해서 모델을 실행 가능하다.
from torch.cuda.amp import autocast # 모델 실행 시 mixed precision 사용 with autocast(): model.test()
 

5. GPU 대신 CPU 실행

만약 GPU 메모리 문제를 해결하기 어렵다면, CPU로 모델을 실행하는 것도 한 방법이다. 속도는 느려지지만 메모리 부족 문제는 해결 가능하다.
python test.py --dataroot ./datasets/mydata --name style_monet_pretrained --model test --input_nc 3 --no_dropout --results_dir ./output_dir --max_dataset_size 5000 --preprocess none --num_test 5000 --gpu_ids -1
 
그러나…
이 다섯 개를 전부 실행해보아도 제대로 해결되지 않았다.
당장 하려면 이미지 resize와 관련된 명령어를 건드리는 방법 뿐이다.
그러나 이 경우 실제 학습에 있어서 많은 디테일을 포기해야하는 경우가 생길 수 있으므로 함부로 사용하지 않겠다.
 
오류가 뜨는 이유를 찾았다
😖
오류가 뜨는 이유를 찾았다!
특정 픽셀(크기)를 넘어서면 너무 많은 양의 메모리가 할당되어야 하기 때문에 생기는 오류였다.
 
해결 방법
→ 확인을 해보니 약 3MB(3000KB)를 넘어서는 이미지에 대해서 이러한 오류가 발생하였음. 그래서 이 이미지들은 아쉽지만 삭제하고 GAN을 작동하는 방향으로 가기로 하였다!
 
import os # 삭제할 파일 경로가 있는 폴더 folder_path = './datasets/mydata' # 파일 크기 기준 (3MB = 3000KB = 3 * 1024 * 1024 bytes) max_size = 3 * 1024 * 1024 # 3MB # 파일 삭제 루프 for filename in os.listdir(folder_path): if filename.endswith(".jpg") or filename.endswith(".png"): # 이미지 파일만 처리 file_path = os.path.join(folder_path, filename) try: file_size = os.path.getsize(file_path) # 파일 크기(바이트 단위) 확인 # 파일 크기가 기준보다 크면 삭제 if file_size > max_size: print(f"Deleting {file_path}, size: {file_size / 1024} KB") os.remove(file_path) except Exception as e: print(f"Error processing {file_path}: {e}")
notion image