0

画像のヒストグラムを出すプログラムを作ったのですが、以下の行に対してエラーが発生します。
これはなぜなのでしょうか?

cv2.line(img_hst, (i, rows), (i, rows-rows*(v/max_val)), (255,255,255))

エラー

only integer scalar arrays can be converted to a scalar index

プログラム

import cv2
import numpy as np

file_src="report1picture.jpg"
file_dst="hist1.jpg"

img_src=cv2.imread(file_src, 1) 
img_hst=np.zeros([100,256]).astype('uint8')
rows, cols=img_hst.shape[:2]

hdims=[256] 
hranges=[0,256] 
hist=cv2.calcHist([img_src], [0], None, hdims, hranges)

min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(hist)

for i in range(0, 255):
    v=hist[i]
    cv2.line(img_hst, (i, rows), (i, rows-rows*(v/max_val)), (255,255,255))

cv2.imshow("src", img_src)
cv2.imshow("hst", img_hst) 
cv2.imwrite(file_dst, img_hst) 

cv2.waitKey(0)
cv2.destroyAllWindows()
3
  • Windows10 64bit python 3.7.6, opencv-python 4.1.2.30, numpy 1.18.0でエラー等では止まらず画像とヒストグラムは表示されました。環境の差とかでしょうか?
    – kunif
    2019年12月25日 5:41
  • for loop 内で v=hist[i] とされていますが、hist[i] は numpy.ndarray 型のオブジェクトですので v=hist[i][0] とするのではないでしょうか。また、hist[i][0] は numpy.float 型ですので、cv.line() 関数の引数である (i, rows-rows*(v/max_val))(i, int(rows-rows*(v/max_val))) の様に int 型に cast する必要があるかと。
    – user39889
    2019年12月25日 11:17
  • 余談ですが、cv2.line() の代わりに cv2.polylines() を使うこともできます。この場合、for loop は必要ありません。cv2.polylines(img_hst, np.array([[i, rows, i, int(rows*(1-hist[i][0]/max_val))] for i in range(cols)]).reshape(1, -1, 2), False, (255, 255, 255))
    – user39889
    2019年12月25日 12:02

0

この質問に回答するには、ログインする必要があります。

のタグが付いた他の質問を参照する。