- 11
- 이니스프리
- 조회 수 8114
파이썬 Pillow 라이브러리를 이용하면 다양한 방식으로 이미지를 편집할 수 있습니다.
이 글에서는 Pillow를 이용하여 이미지의 배경에 transparent한 속성을 주는 방법에 대해 살펴보겠습니다.
스포어에는 웹디자이너 회원님들께서도 많이 계실텐데 저의 허접한 실력이 부끄럽네요~
요새 많이 돌아다니는 짤을 활용해서 설명드릴게요 ^^
출처: https://sir.kr/cm_free/1518481
여러 방법을 생각해볼 수 있겠지만 다음과 같은 스크립트를 이용하여 위 이미지에서 배경을 날려버리겠습니다 ^^
설명을 드리면 이미지의 색상을 RGB로 분석하여 (255, 255, 255)이면
alpha 값(투명도)을 0으로 변경하여 투명하게 만들어주는 방식입니다.
참고로 jpg는 transparency를 지원하지 않기 때문에, PNG GIF WEBP SVG 등을 사용해야 합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from PIL import Image img = Image. open ( '이미지 파일명.확장자' ) img = img.convert( "RGBA" ) datas = img.getdata() newData = [] cutOff = 255 for item in datas: if item[ 0 ] > = cutOff and item[ 1 ] > = cutOff and item[ 2 ] > = cutOff: newData.append(( 255 , 255 , 255 , 0 )) # RGB의 각 요소가 모두 cutOff 이상이면 transparent하게 바꿔줍니다. else : newData.append(item) # 나머지 요소는 변경하지 않습니다. img.putdata(newData) img.save( "생성할 파일명.png" , "PNG" ) # PNG 포맷으로 저장합니다. |
그런데 실행해보면 다음과 같이 지저분하게 처리가 되는 것을 확인할 수 있습니다.
이는 우리가 모니터로 볼 때 흰색이라고 생각되는 색을
실제로 color picker로 찍어보면 (255, 255, 255)가 아닌 경우가 있기 때문입니다.
특히 이미지 파일을 압축하는 과정에서 이런 현상이 발생하는 것으로 알고 있습니다.
위 스크립트에서 cutOff의 값을 조금씩 낮춰보겠습니다.
대략 150 이하에서는 다음과 같이 비교적 깨끗한 이미지를 얻을 수 있습니다 ^^
150 이하에서는 더 작은 값을 주더라도 큰 변화를 체감할 수 없었습니다.
이러한 방법은 배경이 단색일 때에는 비교적 손쉽게 활용할 수 있으나,
여러 색상인 경우에는 다른 방법을 이용하시는 것이 좋을 것 같네요 ㅠㅠ
허접한 글을 읽어주셔서 감사합니다 ^-^
그럼 즐거운 주말 오후 되세요!
추천인 1
작성자
댓글 11



어떤 분께서 Pillow 라이브러리에 대해
"포토샵 정도 수준의 프로그램을 만들 것이 아니라면 충분히 강력하다"는 취지로 말씀하셨는데
몇 줄 안 되는 스크립트로 이미지를 다양한 방식으로 다룰 수 있어서
솔직히 저도 조금 놀랐습니다 ㄷㄷ
아무래도 파이썬이 머신러닝 방면으로 발전하고 있고, 머신러닝의 대상이 주로 이미지라서 그런지
상대적으로 파이썬이 다른 언어에 비해 이미지를 다루는 좋은 라이브러리들이 많은 것 같아요.
Pillow에 대한 동영상 강의나 교재가 있으면 더 공부를 해보고 싶은데
아쉽게도 몇몇 해외 강좌를 제외하면 강의가 많지는 않은 것 같고
시중에 Pillow만 다룬 교재가 있는 것 같지는 않네요.
(역시 Numpy나 Pandas 관련해서는 교재가 많더군요 ㄷㄷ)
그럼 마스터 님께서도 편안한 밤 되시고 다음 한 주도 화이팅입니다!




오차값에 따라 지저분하게 나오는것도 똑같고요..
흐음.. 파이썬을 다시 깔아봐야겠습니다. 의외로 간단하군요!


포토샵의 매직완드나 이 스크립트처럼 PIL을 사용하는 방법이나 결국 코딩의 원리는 비슷하지 않을까요? ^^
물론 포토샵의 완성도가 더 높고, 색상과 포지션을 선택하면 이를 분석하는 과정이 포함되겠지만요.
어느덧 날씨가 조금 선선해졌네요! 굿밤 되세요~



저도 PIL(Pillow)을 공부하면서 많은 점을 느끼게 되더군요!
정말 강력한 라이브러리인 것 같아요 ^^
조금 시행착오를 겪기도 했지만 이미지매직 등을 사용하지 않고
오로지 PIL만 이용해서 짧은 스크립트로 animated GIF를 리사이징하는 것도 가능하더군요.
그럼 남은 9월 잘 마무리하세요!




저는 감기에 걸려서 고생하고 있네요 ㅠㅠ


저는 요즘 새로운 도전을 해볼까 고민 중이네요 ㅎㅎ


제가 프로필에 적은 티벳어의 의미는 '에베레스트'라서 달달한 생활과는 거리가 좀 있는 것 같습니다 -_-;;;
주변에 등산을 좋아하시는 분들도 안나푸르나 베이스캠프(ABC)는 가도 에베레스트 쪽으로는 잘 안 가시던데요 ㄷㄷ
그나저나 새로운 도전은 좋죠!
저도 올해 준비하던 시험에 운좋게 합격해서 내년에 연수받고 이직하게 되었습니다 ^^
그럼 모니터 님께서도 즐거운 주말 되세요~!
