이미지 다루기

파이썬으로 이미지를 다루는 방법에 대해서 학습합니다.

이에 사용하는 파이썬 패키지는 Pillow 입니다.

Pillow 패키지 설치

$ pip3 install Pillow

or

$ pip3.6 install Pillow

우분투 Pillow 라이브러리 설치 예

sudo apt-get install libz-dev libjpeg-dev libfreetype6-dev

이미지 클래스 사용

>>> from PIL import Image

# 형식 : Image.open(file_path, mode='r')
>>> im = Image.open("sample1.jpeg")

이미지 정보

>>> print(im.format, im.size, im.mode)

JPEG (450, 600) RGB

Image Object

Image.open()

이미지 파일을 연다.

Image.open(file_path, mode='r')
  • file_path : 이미지 파일의 경로를 지정
  • mode : 'r' 이외는 사용할 수 없다.

Image.new()

이미지를 새로 생성한다.

Image.new(mode, size, color)
  • mode
    • 1 (1-bit pixels, black and white, stored with one pixel per byte)
    • L (8-bit pixels, black and white)
    • P (8-bit pixels, mapped to any other mode using a color palette)
    • RGB (3x8-bit pixels, true color)
    • RGBA (4x8-bit pixels, true color with transparency mask)
    • CMYK (4x8-bit pixels, color separation)
    • YCbCr (3x8-bit pixels, color video format)
    • Note that this refers to the JPEG, and not the ITU-R BT.2020, standard
    • LAB (3x8-bit pixels, the L*a*b color space)
    • HSV (3x8-bit pixels, Hue, Saturation, Value color space)
    • I (32-bit signed integer pixels
    • F (32-bit floating point pixels)
  • size - 튜플
  • color
from PIL import Image

img = Image.new(mode='RGB', size=(400, 400), color=0x0000FF)
img.save('./images/sample2.png', format='PNG')

Image.resize()

이미지 사이즈 변경

Image.resize(size, resample=0)
  • size - 변경 후 크기(픽셀)를 (width, height) 튜플로 지정
  • resample - 리샘플링 필터를 지정

Image.rotate()

이미지를 회전한다.

Image.rotate(angle, resample=0, expand=0)
  • angle - 시계방향으로 회전할 각도

Image.save()

이미지 저장

Image.save(file_path, format=None, **params)
  • file_path - 이미지를 저장할 파일 경로를 지정
  • format - 저장할 이미지 포맷을 지정한다. 생략하면 file_path 확장자로부터 자동으로 판별한다.
  • **params - 이미지 포맷별로 다른 옵션을 지정하는 인수

텍스트 넣기

# -*- coding:utf8 -*-

from PIL import Image, ImageDraw, ImageFont

img = Image.new(mode='RGB', size=(400, 400), color='#FFF')
draw = ImageDraw.Draw(img)

# 폰트 종류, 크기 지정
font = ImageFont.truetype('~/Library/Fonts/Monofur for Powerline.ttf', 22)

# 텍스트
draw.text((10, 10), 'Hello Python', font=font, fill='#000')

img.save('./images/draw_text.png', format='PNG')

ImageFont.truetype()

True Type 폰트 객체 생성

ImageFont.truetype(font=None, size=10, index=0, encoding='', filename=None)
  • font - 폰트 파일 지정
  • size - 폰트 크기
  • index - 지정한 폰트에 여러 개 폰트가 포함인 경우 ttc 번호 지정
  • filename - 사용하지 않음

ImageDraw.Draw.text()

ImageDraw.Draw.text(xy, text, file=None, font=None, anchor=None)
  • xy - 텍스트를 삽입할 좌표 (x, y) 튜플 지정
  • text - 삽입할 텍스트
  • fill - 텍스트의 색상 지정
  • font - 폰트 객체 지정

색상 지정 방식

  • RGB 16진수를 문자열로 지정 : fill='#FF0000'
  • RGB 10진수를 튜플로 지정 : fill=(255, 0, 0)
  • 색상 이름을 지정 : fill='red'

Image Crop

특정 영역을 자른다.

from PIL import Image

# 이미지 불러오기
img = Image.open('./images/sample1.jpeg')

box = (0, 0, 130, 600)
region = img.crop(box)

region.save('./images/cropped_image.png')

JPEG 썸네일 만들기

import os, sys
from PIL import Image

size = (128, 128)

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size)
            im.save(outfile, "JPEG")
        except IOError:
            print("cannot create thumbnail for", infile)

results matching ""

    No results matching ""