numpy 배열에서 특정 값 갯수 세기. 이미지에서 특정 rgb 값 갯수 세기.
조회수 2870회
numpy 형태가
이런 형태로 나와있는데 이 값들 중 [255 255 255]일 때 카운팅을 하나씩 하고싶어서요. list랑 생각보다 달라서 감이 하나도 잡히지 않습니다... shape은 (3024, 3024, 3) 형태입니다
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
1 답변
-
https://stackoverflow.com/questions/59669715/fastest-way-to-find-the-rgb-pixel-color-count-of-image
이 링크의 답변을 보시면 좋은 답이 있네요.
numpy array 를 (-1, 3) 으로 reshape 하고, unique 로 갯수를 세면 되네요.
트리플이 아닌 페어를 세는 것으로 바꾸어 예제를 만들어 보았으니 보세요.
>>> import numpy as np >>> arr = np.array([[[1,1],[2,2],[1,1]], [[2,3],[1,1],[4,4]]]) >>> arr array([[[1, 1], [2, 2], [1, 1]], [[2, 3], [1, 1], [4, 4]]]) >>> arr.shape (2, 3, 2) >>> arr1 = arr.reshape((-1, 2)) >>> arr1 array([[1, 1], [2, 2], [1, 1], [2, 3], [1, 1], [4, 4]]) >>> np.unique(arr1) array([1, 2, 3, 4]) >>> np.unique(arr1, axis=0, return_counts=True) (array([[1, 1], [2, 2], [2, 3], [4, 4]]), array([3, 1, 1, 1], dtype=int64)) >>> values, counts = np.unique(arr1, axis=0, return_counts=1) >>> values array([[1, 1], [2, 2], [2, 3], [4, 4]]) >>> counts array([3, 1, 1, 1], dtype=int64) >>> for value, count in zip(*np.unique(arr1, axis=0, return_counts=1)): print(f"{value} 이 {count} 개") [1 1] 이 3 개 [2 2] 이 1 개 [2 3] 이 1 개 [4 4] 이 1 개 >>>
댓글 입력