Python에서 이미지 작업

Python에서 이미지 작업

PIL은 Python 인터프리터에 이미지 편집 기능을 제공하는 Python 이미징 라이브러리입니다. Fredrik Lundh와 다른 여러 기여자가 개발했습니다. Pillow는 Alex Clark 및 기타 기여자들이 개발한 친숙한 PIL 포크이자 사용하기 쉬운 라이브러리입니다. 우리는 Pillow와 함께 일할 것입니다.

설치:

  • 리눅스: Linux 터미널에서 다음을 입력합니다.
     pip install Pillow  터미널을 통해 pip 설치:  
     sudo apt-get update   
    sudo apt-get install python-pip
  • 윈도우: 다운로드 Python 버전에 따라 적절한 Pillow 패키지를 선택하세요. 사용 중인 Python 버전에 맞게 다운로드하세요.

여기서는 동일한 이름의 클래스를 제공하고 이미지 작업에 필요한 많은 기능을 제공하는 이미지 모듈을 사용하여 작업할 것입니다. 이미지 모듈을 가져오려면 코드가 다음 줄로 시작해야 합니다.

  from PIL import Image  

이미지 작업:

  • 경로에서 특정 이미지를 엽니다. Python
       #img = Image.open(path)    # On successful execution of this statement   # an object of Image type is returned and stored in img variable)   try  :   img   =   Image  .  open  (  path  )   except   IOError  :   pass   # Use the above statement within try block as it can    # raise an IOError if file cannot be found    # or image cannot be opened.   
  • 이미지 크기 검색 : 생성된 Image 클래스의 인스턴스에는 유용한 속성 중 하나인 크기라는 많은 속성이 있습니다. Python
       from   PIL   import   Image   filename   =   'image.webp'   with   Image  .  open  (  filename  )   as   image  :   width     height   =   image  .  size   #Image.size gives a 2-tuple and the width height can be obtained   
    다른 속성으로는 Image.width Image.height Image.format Image.info 등이 있습니다.
  • 이미지의 변경 사항을 저장합니다. 이미지 파일에 대한 변경 사항을 저장하려면 경로와 이미지 형식을 제공해야 합니다. Python
       img  .  save  (  path     format  )   # format is optional if no format is specified    #it is determined from the filename extension   
  • 이미지 회전: 이미지 회전에는 이미지를 회전시키려면 매개변수로 각도가 필요합니다. Python
       from   PIL   import   Image   def   main  ():   try  :   #Relative Path   img   =   Image  .  open  (  'picture.webp'  )   #Angle given   img   =   img  .  rotate  (  180  )   #Saved in the same relative location   img  .  save  (  'rotated_picture.webp'  )   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   
    파이썬에서 이미지 회전하기 참고: true로 설정되면 출력 이미지를 확장하여 전체 회전된 이미지를 담을 수 있을 만큼 크게 만드는 회전 메서드의 인수 중 하나로 사용할 수 있는 선택적 확장 플래그가 있습니다. 위의 코드 조각에서 볼 수 있듯이 내 이미지가 내 Python 코드 파일과 동일한 디렉터리에 있는 상대 경로를 사용했습니다. 절대 경로도 사용할 수 있습니다.
  • 이미지 자르기: Image.crop(box)는 4튜플(왼쪽 위 오른쪽 아래) 픽셀 좌표를 사용하고 사용된 이미지에서 직사각형 영역을 반환합니다. Python
       from   PIL   import   Image   def   main  ():   try  :   #Relative Path   img   =   Image  .  open  (  'picture.webp'  )   width     height   =   img  .  size   area   =   (  0     0     width  /  2     height  /  2  )   img   =   img  .  crop  (  area  )   #Saved in the same relative location   img  .  save  (  'cropped_picture.webp'  )   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   
    파이썬에서 이미지 자르기
  • 이미지 크기 조정: Image.resize(size) - 여기서 크기는 2-튜플 너비와 높이로 제공됩니다. Python
       from   PIL   import   Image   def   main  ():   try  :   #Relative Path   img   =   Image  .  open  (  'picture.webp'  )   width     height   =   img  .  size   img   =   img  .  resize  ((  width  /  2     height  /  2  ))   #Saved in the same relative location   img  .  save  (  'resized_picture.webp'  )   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   
    파이썬에서 이미지 크기 조정
  • 다른 이미지에 이미지 붙여넣기: 두 번째 인수는 2-튜플(왼쪽 위 모서리 지정) 또는 4-튜플(왼쪽 위 오른쪽 아래)일 수 있습니다. 이 경우 붙여넣은 이미지의 크기는 이 상자 영역의 크기와 일치해야 하거나 None(0 0)과 동일해야 합니다. Python
       from   PIL   import   Image   def   main  ():   try  :   #Relative Path   #Image on which we want to paste   img   =   Image  .  open  (  'picture.webp'  )   #Relative Path   #Image which we want to paste   img2   =   Image  .  open  (  'picture2.webp'  )   img  .  paste  (  img2     (  50     50  ))   #Saved in the same relative location   img  .  save  (  'pasted_picture.webp'  )   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   ##An additional argument for an optional image mask image is also available.   
    Python에서 다른 이미지에 이미지 붙여넣기
  • 이미지의 히스토그램 얻기: 그러면 이미지의 각 픽셀에 대해 하나씩 계산되는 픽셀 목록으로 이미지의 히스토그램이 반환됩니다. (이미지의 히스토그램은 디지털 이미지의 색조 분포를 그래픽으로 표현한 것입니다. 여기에는 이미지에 포함된 모든 밝기 값이 포함됩니다. 각 밝기 값에 대한 픽셀 수를 표시합니다. 노출 설정을 수행하는 데 도움이 됩니다.) from PIL import Image Python
       def   main  ():   try  :   #Relative Path   img   =   Image  .  open  (  'picture.webp'  )   #Getting histogram of image   print   img  .  histogram  ()   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   
    Python 복사본에서 이미지의 히스토그램 가져오기


  • 이미지 전치: 이 기능은 이미지의 거울 이미지를 제공합니다. Python
        from   PIL   import   Image   def   main  ():   try  :   #Relative Path   img   =   Image  .  open  (  'picture.webp'  )   #transposing image    transposed_img   =   img  .  transpose  (  Image  .  FLIP_LEFT_RIGHT  )   #Save transposed image   transposed_img  .  save  (  'transposed.webp'  )   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   
    파이썬으로 이미지 바꾸기
  • 이미지를 개별 밴드로 분할합니다. RGB 모드에서 이미지를 분할하면 각각 원본 개별 밴드의 복사본을 포함하는 세 개의 새로운 이미지가 생성됩니다. Python
       from   PIL   import   Image   def   main  ():   try  :   #Relative Path   img   =   Image  .  open  (  'picture.webp'  )   #splitting the image   print   img  .  split  ()   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   
    파이썬으로 이미지 분할하기
  • 토비트맵: 이미지를 X11 비트맵(일반 텍스트 이진 이미지 형식)으로 변환합니다. 이는 모드 1 이미지, 즉 1비트 픽셀 흑백 이미지에만 사용할 수 있는 X11 비트맵이 포함된 문자열을 반환합니다. PIL 가져오기 이미지에서 Python
       def   main  ():   try  :   #Relative Path   img   =   Image  .  open  (  'picture.webp'  )   print   img  .  mode   #converting image to bitmap   print   img  .  tobitmap  ()   print   type  (  img  .  tobitmap  ())   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   
    파이썬에서 이미지를 비트맵으로 변환하기 Python에서 이미지를 bitmao로 변환
  • 이 메소드는 열린 이미지의 썸네일을 생성합니다. 현재 열려 있는 이미지 객체 자체를 내부 수정하는 새 이미지 객체를 반환하지 않습니다. 원본 이미지 개체를 변경하지 않으려면 복사본을 만든 다음 이 방법을 적용하세요. 이 방법은 또한 전달된 크기에 따라 이미지의 종횡비를 유지하는 것이 적절한지 평가합니다. PIL 가져오기 이미지에서 Python
       def   main  ():   try  :   #Relative Path   img   =   Image  .  open  (  'picture.webp'  )   #In-place modification   img  .  thumbnail  ((  200     200  ))   img  .  save  (  'thumb.webp'  )   except   IOError  :   pass   if   __name__   ==   '__main__'  :   main  ()   
    Python에서 이미지의 썸네일 만들기
퀴즈 만들기