IT/Python

np.unravel_index() 설명 및 사용예시 정리

준나이 2022. 11. 15. 01:06

Function Signature 

numpy.unravel_index(indices, shape, order='C')

shape = (M, N) 으로 주어질 때, Matrix (M, N) 내 원소는 0 부터 M * N-1 까지 존재한다고 가정
indicies = index: int (or indicies: list of int)가 위치한 좌표를 나타냄

 

예시1 :

np.unravel_index(6, (3, 4))

 

shape: (3, 4) -> np.arange(12).reshape(3, 4) = 0~11 로 채워진 M = 3, N =4인 matrix 

  0 1 2 (return j) 3
0 0 1 2 3
(return i) 4 5 6 (index) 7
2 8 9 10 11

(1, 2)

 

 

예시2 : np.argmax() 한계 극복

import numpy as np
from PIL import Image

img = ... # 원본 이미지 e.g. 풍경 사진
template = ... # 원본과 맵핑하고 싶은 템플릿 e.g. 나무 템플릿
corr_img = ... # 원본과 이미지를 cross-correlation 하여 구한 값

# corr_img 중 에서 가장 correlation 이 높은 pixel을 argmax로 구한 후, 
# 정확한 좌표값을 corr_img.shape 해서 구할 수 있음
# np. argmax() 만 사용해서는 안 됨
high_corr_y, high_corr_x = np.unravel_index(np.argmax(corr_img, None), corr_img.shape)

# high_corr_y, high_corr_x 를 이용하여 template이 실제로 잘 맵핑 됐는지 확인 수 있음
Image.fromarray(
	img[high_corr_y:high_corr_y+template.shape[0], 
    	high_corr_x:high_corr_x+template.shape[1]]
).show()


[참고]

https://numpy.org/doc/stable/reference/generated/numpy.unravel_index.html
https://stackoverflow.com/questions/48135736/what-is-an-intuitive-explanation-of-np-unravel-index

'IT > Python' 카테고리의 다른 글

matplotlib 에서 latex 쓰기  (1) 2022.11.19
python encoding  (0) 2018.10.15