조건이 충족되면 Numpy 요소 교체
조건이 충족되면 각 요소가 1 또는 0으로 변경되도록 조작해야하는 큰 numpy 배열이 있습니다 (나중에 픽셀 마스크로 사용됨). 배열에는 약 8 백만 개의 요소가 있으며 현재 방법은 축소 파이프 라인에 너무 오래 걸립니다.
for (y,x), value in numpy.ndenumerate(mask_data):
if mask_data[y,x]<3: #Good Pixel
mask_data[y,x]=1
elif mask_data[y,x]>3: #Bad Pixel
mask_data[y,x]=0
속도를 높일 수있는 numpy 함수가 있습니까?
>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
[3, 0, 1, 2],
[2, 0, 1, 1],
[4, 0, 2, 3],
[0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False, True, True, True],
[False, True, True, True],
[ True, True, True, True],
[False, True, True, False],
[ True, True, True, True]], dtype=bool)
>>>
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 0],
[1, 1, 1, 1]])
다음과 같이 단축 할 수 있습니다.
>>> c = (a < 3).astype(int)
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[0, 3, 3, 2],
[4, 1, 1, 2],
[3, 4, 2, 4],
[2, 4, 3, 0],
[1, 2, 3, 4]])
>>>
>>> a[a > 3] = -101
>>> a
array([[ 0, 3, 3, 2],
[-101, 1, 1, 2],
[ 3, -101, 2, -101],
[ 2, -101, 3, 0],
[ 1, 2, 3, -101]])
>>>
예를 들어 부울 배열로 인덱싱을 참조하십시오 .
빠른 (가장 유연한) 방법을 사용하는 것이다 np.where 두 배열 중에서 선택 마스크 (참과 거짓 값의 배열)에있어서, 이는 :
import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)
다음을 생성합니다.
a: [[1 4 0 1]
[1 3 2 4]
[1 0 2 1]
[3 1 0 0]
[1 4 0 1]]
b: [[0 1 0 0]
[0 1 0 1]
[0 0 0 0]
[1 0 0 0]
[0 1 0 0]]
다음과 같이 한 단계로 마스크 배열을 만들 수 있습니다.
mask_data = input_mask_data < 3
This creates a boolean array which can then be used as a pixel mask. Note that we haven't changed the input array (as in your code) but have created a new array to hold the mask data - I would recommend doing it this way.
>>> input_mask_data = np.random.randint(0, 5, (3, 4))
>>> input_mask_data
array([[1, 3, 4, 0],
[4, 1, 2, 2],
[1, 2, 3, 0]])
>>> mask_data = input_mask_data < 3
>>> mask_data
array([[ True, False, False, True],
[False, True, True, True],
[ True, True, False, True]], dtype=bool)
>>>
I am not sure I understood your question, but if you write:
mask_data[:3, :3] = 1
mask_data[3:, 3:] = 0
This will make all values of mask data whose x and y indexes are less than 3 to be equal to 1 and all rest to be equal to 0
참고URL : https://stackoverflow.com/questions/19766757/replacing-numpy-elements-if-condition-is-met
'Nice programing' 카테고리의 다른 글
숨겨진 입력을 갖는 Django ModelForm (0) | 2020.11.06 |
---|---|
Android Google Maps API V2 현재 위치로 확대 (0) | 2020.11.06 |
포착되지 않은 TypeError : 정의되지 않은 'linear'속성을 읽을 수 없습니다. (0) | 2020.11.06 |
Jquery 양식 필드 값 가져 오기 (0) | 2020.11.06 |
C ++ 클래스에서 정적 변수를 초기화 하시겠습니까? (0) | 2020.11.06 |