본문 바로가기
Python

[Python] argument를 bind하려면 ?? (partial)

by 슈퍼닷 2020. 1. 4.
반응형

파이썬으로 이미지에 대해 다양한 구역에 대한 히스토그램을 구하기위해 이렇게 짰다.

def getHistogram(inRange, img):
    H, W, _ = img.shape
    hist = [[0] * 256, [0] * 256, [0] * 256];
    
    for y in range(H):
        for x in range(W):
            if (inRange(x,y) == False):
                continue;
            
            for i in range(3):
                pixel = img.item(y,x,i);
                hist[i][pixel] += 1;
                     
    return hist;

inRange에 해당하는 함수는 다음과 같다.

def _inRangeRect(x1, y1, x2, y2, x, y):
    if not(x >= x1 and x < x2):
        return False
    elif not(y >= y1 and y < y2):
        return False
    else:
        return True

지금은 단순히 사각형이지만 세모 사다리꼴등 다양한 내가 원하는 구역만 구하고싶어서 함수를 이렇게 전달해줬다.

그런데 이럴려면 x1,y1,x2,y2 를 bind해야만 쓸수있다. 그래서 c++ 에서 쓰던 bind처럼 파이썬에도 이런게 있나 한번 찾아보았다..

찾아보니 partial 라는 모듈로 지원하더라.

def f(a,b,c):
	print('%d, %d, %d' % (a, b, c));

from functools import partial
f_bind = partial(f, 1)
f_bind(2,3)
#1, 2, 3

python에서는 partial로 c++의 bind와 똑같은 기능을 구현할수 있다! 

bind를 처음으로 활용한듯..

반응형

댓글