NumPy 배열 나누기: 영상 자르기 - split

2021. 9. 11. 22:15·Programming/DIP
728x90
728x90

1. numpy.vsplit

numpy.vsplit(array, indices_or_sections) : Split an array into multiple sub-arrays vertically (row-wise)

  • axis 0 (행)로 array를 잘라 나눔.
  • array가 image라면 수직(vertical)으로 잘려짐.
  • inideice_or_sections
    • 정수: 동일한 크기의 부분으로 나누기 (배열 크기가 나누어떨어져야 제대로 동작)
    • 리스트: 지정된 인덱스에서 나누기 (유연한 크기 조절 가능)
    • index는 0부터 시작하며, 해당 인덱스 이전에서 분할됨.

Simple example

import numpy as np
a = np.arange(12).reshape(-1,3)
np.vsplit(a, (1,3)) 
  • 이 경우,
    • idx 0인 행으로 구성된 1x3인 ndarray,
    • idx 1,2 행들이 묶인 2x3인 ndarray, 그리고 i
    • dx 3인 행으로 구성된 1x3인 ndarray로 나누어짐
  • np.vsplit(a, (1,3))의 반환값은 list임.
[array([[0, 1, 2]]),
 array([[3, 4, 5],
        [6, 7, 8]]),
 array([[ 9, 10, 11]])]

Image example

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('../../images/lena.png')
subimgs = np.vsplit(img,4) #하나의 숫자로 주어질 경우 몇 등분인지를 나타냄.

for c in subimgs:
    print(c.shape)
    plt.imshow(c[...,::-1])
    plt.show()

 

결과는 다음과 같음.

  • 512개의 pixel을 4등분하여, 128x512x3의 ndarray 4개로 나누어짐.

ref: NumPy API

 

numpy.vsplit — NumPy v2.3 Manual

>>> import numpy as np >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]) >>> np.vsplit(x, 2) [array([[0., 1., 2., 3.], [4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.], [12.,

numpy.org

 


2. numpy.hsplit

numpy.hsplit(array, indices_or_sections) : Split an array into multiple sub-arrays horizontally (column-wise)

  • axis 1(열)로 array를 잘라 나눔.
  • array가 image라면 수평으로 잘려진다.
  • inideice_or_sections
    • 정수: 동일한 크기의 부분으로 나누기 (배열 크기가 나누어떨어져야 제대로 동작)
    • 리스트: 지정된 인덱스에서 나누기 (유연한 크기 조절 가능)
    • index는 0부터 시작하며, 해당 인덱스 이전에서 분할됨.

Simple example

import numpy as np
a = np.arange(12).reshape(-1,3)
np.hsplit(a, (2,)) 
  • 이 경우, idx 0,1인 열(column)들로 구성된 4x2인 ndarray, idx 3인 열로 구성된 4x1인 ndarray로 나누어짐
  • np.hsplit(a, (2,))의 반환값은 list임.
[array([[ 0,  1],
        [ 3,  4],
        [ 6,  7],
        [ 9, 10]]),
 array([[ 2],
        [ 5],
        [ 8],
        [11]])]

Image example

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('../../images/lena.png')
subimgs = np.vsplit(img,4) #하나의 숫자로 주어질 경우 몇 등분인지를 나타냄.

for c in subimgs:
    print(c.shape)
    plt.imshow(c[...,::-1])
    plt.show()

결과는 다음과 같음.

  • 512개의 pixel을 2등분하여, 512x256x3의 ndarray 2개로 나누어짐.

ref: NumPy API

 

numpy.hsplit — NumPy v2.3 Manual

>>> import numpy as np >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]) >>> np.hsplit(x, 2) [array([[ 0., 1.], [ 4., 5.], [ 8., 9.], [12., 13.]]), array([[ 2., 3.], [ 6., 7

numpy.org


3. numpy.dsplit

numpy.dsplit(array, indices_or_sections) : Split an array into multiple sub-arrays along the 3rd axis (depth).

    • axis 2 (행)로 array를 잘라 나눔.
    • array가 image라면 channel 별로 잘려짐.
    • inideice_or_sections
      • 정수: 동일한 크기의 부분으로 나누기 (배열 크기가 나누어떨어져야 제대로 동작)
      • 리스트: 지정된 인덱스에서 나누기 (유연한 크기 조절 가능)
      • index는 0부터 시작하며, 해당 인덱스 이전에서 분할됨.
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('../../images/lena.png')
subimgs = np.dsplit(img,3) #하나의 숫자로 주어질 경우 몇 등분인지를 나타냄.

for c in subimgs:
    print(c.shape)
    plt.imshow(c[...,::-1])
    plt.show()

4. numpy.split

numpy.split(array, indices_or_sections, axis=0) : Split an array into multiple sub-arrays as views into arrays.

        • 앞서 살펴본 numpy.vsplit, numpy.hsplit 들의 일반형
        • 나눌 축을 axis라는 파라메터로 지정가능함.

다음과 같이 color image에서 각 채널별 영상으로 나누는데 사용가능함.

Example

mport cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('../../images/lena.png')
subimgs = np.split(img,3,axis=2) 
for idx,c in enumerate(subimgs):
    print(c.shape)
    plt.title(f'channel: {idx}')
    plt.imshow(c[...,::-1],cmap='gray')
    plt.show()

 

결과는 다음과 같음

    •  

ref: NumPy API

 

numpy.split — NumPy v2.3 Manual

If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised. If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the arra

numpy.org


같이 보면 좋은 자료들

https://ds31x.tistory.com/344

 

[Summary] NumPy(Numerical Python)

파이썬 생태계에서 과학적 계산의 기본이 되는 라이브러리 NumPy 소개 : NumPy는 파이썬에서 과학 계산과 수치 연산을 효율적으로 처리하기 위한 라이브러리 n-dimensional array(다차원 배열)인 ndarray

ds31x.tistory.com

 

 

  •  
728x90

'Programming > DIP' 카테고리의 다른 글

PIL과 opencv에서의 image 변환.  (1) 2021.11.22
Conda backup for DIP 2021  (0) 2021.09.18
NumPy : sum, mean, std, and so on  (0) 2021.09.17
NumPy 검색  (0) 2021.09.11
NumPy 배열 병합 : 영상 붙이기  (0) 2021.09.11
'Programming/DIP' 카테고리의 다른 글
  • Conda backup for DIP 2021
  • NumPy : sum, mean, std, and so on
  • NumPy 검색
  • NumPy 배열 병합 : 영상 붙이기
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (785)
      • Private Life (15)
      • Programming (55)
        • DIP (116)
        • ML (34)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (368)
        • Signals and Systems (115)
        • Math (176)
        • Linear Algebra (33)
        • Physics (43)
        • 인성세미나 (1)
      • 정리필요. (61)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (7)
        • PET Study 2009 (1)
        • 방사선 장해방호 (5)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    linear algebra
    Vector
    cv2
    Optimization
    인허가제도
    Term
    random
    function
    signal_and_system
    SIGNAL
    signals_and_systems
    fourier transform
    Probability
    math
    SS
    Python
    numpy
    ML
    opencv
    Programming
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
NumPy 배열 나누기: 영상 자르기 - split
상단으로

티스토리툴바