๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

AI/Computer Vision

[Computer Vision] PIL(Python Image Library)

728x90
๋ฐ˜์‘ํ˜•
๐Ÿ‘€ ๋ณธ ์˜ˆ์ œ๋Š” Window10์˜ VSCode, Python3.11.0๋กœ ์ž‘์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 

 

Python Image Library, ์ค„์—ฌ์„œ PIL์€ ํŒŒ์ด์ฌ์—์„œ ์ด๋ฏธ์ง€๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ๋˜๋Š” ๊ฐ•๋ ฅํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ด๋‹ค.

์ด๋ฏธ์ง€ ํŒŒ์ผ์„ ์—ด๊ณ , ์ˆ˜์ •ํ•˜๊ณ , ์ €์žฅํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜์—ฌ ๋‹ค์–‘ํ•œ ์ด๋ฏธ์ง€ ์ž‘์—…์„ ์‰ฝ๊ฒŒ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.

PIL์€ ์ด๋ฏธ์ง€ ํ•„ํ„ฐ๋ง, ๋ณ€ํ™˜, ์ƒ‰์ƒ ์กฐ์ •, ์ด๋ฏธ์ง€ ํฌ๋งท ๋ณ€ํ™˜ ๋“ฑ ์—ฌ๋Ÿฌ ๊ฐ€์ง€ ๊ธฐ๋Šฅ์„ ์ง€์›ํ•œ๋‹ค.

pip install pillow

 

๊ธฐ๋ณธ์ ์ธ ์ด๋ฏธ์ง€๋ฅผ ์—ด๊ณ  ๋ณด๊ณ  ์ €์žฅํ•˜๋Š” ๋ฒ•

from PIL import Image

image = Image.open("test.jpg")
image.show()
image.save("save_test.jpg")

 

 

์ด๋ฏธ์ง€ ์กฐ์ ˆํ•˜๊ธฐ

from PIL import Image

image = Image.open("human.png")
# ์ด๋ฏธ์ง€ ํฌ๊ธฐ ์กฐ์ •(๋ณด๊ฐ„๋ฒ• -> Image.Resampling.<๋ณด๊ฐ„๋ฒ•>)
re_img = image.resize(size=list(map(lambda x:int(x//2),list(image.size))),resample=Image.Resampling.LANCZOS)
re_img.show()
# ์ด๋ฏธ์ง€ ํšŒ์ „
rot_img = re_img.rotate(90)
rot_img.show()

 

ํ•„ํ„ฐ๋ง๋„ ์žˆ๋‹ค.

from PIL import Image
from PIL import ImageFilter
image = Image.open("human.png")
blur = image.filter(ImageFilter.BLUR)
gaussian = image.filter(ImageFilter.GaussianBlur)

blur.show()
gaussian.show()

Blur(์ขŒ), Gaussian(์šฐ)

 

from PIL import Image

# ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€
new = Image.new(mode="RGB",size=(1024,1024),color=(0,0,0))

# ๋ถ™์—ฌ ๋„ฃ์„ ์ด๋ฏธ์ง€
image = Image.open("test2.png")

# ๋ถ™์—ฌ ๋„ฃ์„ ์œ„์น˜(x,y)
position = (0,0)

new.paste(image,position)
new.show()

# ์ž๋ฅผ ์˜์—ญ ์ง€์ •(left, upper, right, lower)
crop_area = (100,100,400,400)
cropped_image = image.crop(crop_area)
cropped_image.show()

paste(์ขŒ), crop(์šฐ)

 

 

์ด๋ฏธ์ง€ ์ƒ‰์ƒ์˜์—ญ์— ๋Œ€ํ•œ๊ฒƒ๋„ ๊ฐ„๋‹จํ•˜๊ฒŒ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.

from PIL import Image

image = Image.open("test2.png")
print(image.mode) # RGB
print(image.convert("L").mode) # L(Grayscale)
print(image.convert("RGBA").mode) # RGBA(ํˆฌ๋ช…๋„ ์ฑ„๋„์ด ์ถ”๊ฐ€๋จ, ์ปฌ๋Ÿฌ๊ฐ’์ด ๋ชจ๋‘ 0์ธ ๊ฒฝ์šฐ ํˆฌ๋ช…)
print(image.convert("CMYK").mode) # CMYK(Cyan, Magenta, Yellow, Key(Black))
print(image.convert("1").mode) # 1-Bit Pixels (ํ‘๋ฐฑ ์ด๋ฏธ์ง€๋ฅผ ๋น„ํŠธ ๋‹จ์œ„๋กœ ํ‘œํ˜„)

 

728x90
๋ฐ˜์‘ํ˜•