이미지 기본 handling 코드 (CNN기초 ver)

2021. 9. 17. 20:30ai/Deep Learning

728x90

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

# 만약 Pillow 모듈이 설치가 되어 있지 않다면,
# conda install Pillow

 

img = Image.open('./images/justice.jpg')


print(type(img))   # <class 'PIL.JpegImagePlugin.JpegImageFile'>

 

plt.imshow(img)
plt.show()

 

pixel = np.array(img)
# print(pixel)


print(pixel.shape)   # (426, 640, 3)

# 여기서 알수 있는건 가로가 640 세로가 426 RGB의 3개의 컬러를 가져 3channel을 가지고 있다고 표현

 

# 컬러이미지는 보통 3차원이다. 왜냐하면

# red, green , blue (일명 RGB) 3장이 곂치기 때문이다 . 2차원이 3개 

 

img.save('./images/my_image.jpg')  # 이미지 저장

 

# crop - 이미지를 내가 원하는 부분만 자른다
# crop(좌상, 우하)
crop_image = img.crop((30,100,150,300))
plt.imshow(crop_image)
plt.show()

 

img.size   # 픽셀 (640, 426) x가로 , y세로

 

resize - 픽셀 변경
resize_img = img.resize((int(img.size[0] / 8), int(img.size[1] / 8)))
plt.imshow(resize_img)
plt.show()

# rotate - 180도 회전

rotate_img = img.rotate(180)
plt.imshow(rotate_img)
plt.show()


color → 흑백

# %reset

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

color_img = Image.open('./images/fruits.jpg')

# plt.imshow(color_img)
# plt.show()
print(color_img.size)

color_pixel = np.array(color_img)
print(color_pixel.shape)   # (426, 640, 3)

gray_pixel = color_pixel.copy()

# 각 픽셀의 RGB값의 평균을 구해서 각 픽셀의 RGB값을 그 평균값으로 설정

for y in range(gray_pixel.shape[0]):    # 0 ~ 425
    for x in range(gray_pixel.shape[1]):
        gray_pixel[y,x] = int(np.mean(gray_pixel[y,x]))  # 112 
    
# plt.imshow(gray_pixel)
# plt.show()



print(gray_pixel[0,0])   # [75 75 75]

gray_channel3_img = Image.fromarray(gray_pixel)

#  Image.fromarray() = 넘파이 어레이로부터 데이터를 땡겨서 이미지를 만들어
gray_channel3_img.save('./images/fruits_gray(3channel).jpg')


3차원 → 2차원

 

print(gray_pixel[0,0])   # [75 75 75]

gray_2d_pixel = gray_pixel[:,:,0]
print(gray_2d_pixel.shape)
print(gray_2d_pixel[0,0])   # 75

plt.imshow(gray_2d_pixel, cmap='gray')
plt.show()

  cmap='gray' 없을때
cmap='gray' 있을때


gray_2d_img = Image.fromarray(gray_2d_pixel)
gray_2d_img.save('./images/fruits_gray(2d).jpg')

'ai > Deep Learning' 카테고리의 다른 글

CNN 전반적 내용 code  (0) 2021.09.29
convolutional Neral Network (CNN) 합성곱 신경망  (0) 2021.09.28
CNN 기초, 이미지 처리  (0) 2021.09.17
MNINST (Deep Learning 역사 ver) [he's intializer]  (0) 2021.09.17
Deep Learning 역사  (0) 2021.09.16