1

I would like to calculate image histogram with OpenCV's calcHist function with Python.
But it doesn't work.

Code:

im = cv2.imread(imPath,0) hist = cv2.calcHist([im],[0],None,[256],[0,256])

And I get error like this:

OpenCV Error: Assertion failed (step(dims[-1] == (size_t) CV_ELEM_SIZE(flags)) 
in create, file opencv/sources/modules/core/src/matrix.cpp line:236
Dharmesh Porwal
  • 1,406
  • 2
  • 12
  • 21
ekarem
  • 148
  • 2
  • 12
  • The guy in that question http://stackoverflow.com/questions/9390592/drawing-histogram-in-opencv-python calls it like that: `cv2.calcHist([item],[0],None,[256],[0,255])`. Note that the last list is `[0,255]` not `[0,256]`. Maybe that's your error? Would make sense.. – Callahan Jan 09 '15 at 09:08
  • ^^ I don't Callahan is correct. I think it is probably that your image is not reading in properly or the wrong file type. – GPPK Jan 09 '15 at 09:13
  • 1
    @Callahan I run code again with your modification. But I got same error. – ekarem Jan 09 '15 at 09:13
  • @GPPK image file extension is "BMP". Is that a problem? – ekarem Jan 09 '15 at 09:15
  • shouldn't think so, but test it with a jpg to see? – GPPK Jan 09 '15 at 09:25
  • I tested with jpg and the result is same. – ekarem Jan 09 '15 at 09:28
  • In my experience, most of the time `imread()` does not work as expected. So you should verify that `im` is actually well defined after `imread()`. – Callahan Jan 09 '15 at 09:45
  • I print im after read it and there is no problem. May this problem is about version of OpenCV ? Because, I tried the same code at another computer that has different version of opencv. It worked. – ekarem Jan 09 '15 at 09:49

2 Answers2

1

Your code is not incorrect - here is some example code that does the same thing (taken from here):

img = cv2.imread('home.jpg',0)
hist = cv2.calcHist([img],[0],None,[256],[0,256])

Therefore I think your imPath is probably incorret. I would suggest using static file path, something similar to "C:\myImage.jpg", to start with and see if an error appears with that.

GPPK
  • 6,546
  • 4
  • 32
  • 57
1

Try this one:

import cv2
im = cv2.imread(r'd:\temp\1.bmp',0)
hist = cv2.calcHist([im],[0],None,256,[0,255])

print im
print hist
Max Tkachenko
  • 792
  • 1
  • 12
  • 30