opencv 파이썬
조회수 341회
def calc_histo(image, hsize, ranges=[0, 256]):
hist = np.zeros((hsize, 1), np.float32)
gap = ranges[1] / hsize
for i in range(image.shape[0]):
for j in range(image.shape[1]):
idx = int(image.item(i,j) / gap)
hist[idx] += 1
return hist
위 함수를 사용해서 아래와 같은 2차원 히스토그램 분석 결과를 얻고싶은데 방법을 모르겠어요.
[[1.0234e+04 1.1613e+04 6.9510e+03 0.0000e+00]
[3.7950e+03 6.2410e+03 3.1410e+03 6.0000e+00]
[0.0000e+00 1.5290e+03 1.3261e+04 2.1480e+03]
[0.0000e+00 0.0000e+00 4.1800e+02 1.2663e+04]]
제가 작성한 코드는
import numpy as np, cv2
def calc_histo(image, hsize, ranges=[0, 256]):
hist = np.zeros((hsize, 1), np.float32)
gap = ranges[1] / hsize
for i in range(image.shape[0]):
for j in range(image.shape[1]):
idx = int(image.item(i,j) / gap)
hist[idx] += 1
return hist
image = cv2.imread("images/pixel.jpg", cv2.IMREAD_COLOR)
if image is None:
raise Exception("영상 파일 읽기 오류 발생")
ch, bins, ranges = [0, 1], [4, 4], [0, 256, 0, 256]
image2 = np.zeros((image.shape[0], 256), dtype=np.float32)
for i in bins:
hist1 = calc_histo(image2, i, ranges)
hist2 = cv2.calcHist([image], ch, None, bins, ranges)
print("저자 구현 함수: \n", hist1)
print("OpenCV 함수: \n", hist2)
cv2.imshow("image", image)
cv2.waitKey(0)
이것이고 결과는
저자 구현 함수:
[[76800.]
[ 0.]
[ 0.]
[ 0.]]
OpenCV 함수:
[[1.0234e+04 1.1613e+04 6.9510e+03 0.0000e+00]
[3.7950e+03 6.2410e+03 3.1410e+03 6.0000e+00]
[0.0000e+00 1.5290e+03 1.3261e+04 2.1480e+03]
[0.0000e+00 0.0000e+00 4.1800e+02 1.2663e+04]]
이렇게 나옵니다.
댓글 입력