Friday, April 27, 2012

Drawing Histogram in OpenCV-Python

Hi Friends,

Do you want to draw a histogram for an image as below?

See the histogram for above image for RGB channels.

The code:

import cv2
import numpy as np

img = cv2.imread('zzzyj.jpg')
h = np.zeros((300,256,3))

bins = np.arange(256).reshape(256,1)
color = [ (255,0,0),(0,255,0),(0,0,255) ]
for ch, col in enumerate(color):
    hist_item = cv2.calcHist([img],[ch],None,[256],[0,256])
    pts = np.column_stack((bins,hist))



You can see the same code written using numpy functions on histogram here  : Drawing histogram in OpenCV- Python.

Don't forget to send your comments, doubts etc.

With Regards,
Abid Rahman K.


  1. I get this error when running this:

    OpenCV Error: Assertion failed (depth >= 0 && depth <= CV_32F) in unknown function, file ..\..\..\OpenCV-2.4.0\modules\core\src\opengl_interop.cpp, line 755

    Any idea what might cause that?
    Thanks a lot,

    1. I don't have any idea why such a problem arises. Are you using OpenGL along with this?

      Can you tell which line of code shows this error ? If my assumption is true, error says array should be of depth 32F or something less than that. Check if your array is CV_64F?

    2. I got the same error. Did you manage to find out what's wrong?

  2. I got this error when running your code:

    OpenCV Error: Assertion failed (src.dims <= 2 && esz <= (size_t)32) in transpose, file /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_graphics_opencv/opencv/work/OpenCV-2.4.1/modules/core/src/matrix.cpp, line 1871
    terminate called throwing an exception

    Do you know how to fix this error?

    1. Seeing it for the first time. By the way, which line throws this error?

    2. The problem is the assert "esz <= (size_t)32" in function transpose (don't know why is limited to 32bits). pts is an int64 because bin is int64 by default in 64bits platforms, so you need to force bin to be int32. Change:

      -bins = np.arange(256).reshape(256,1)
      +bins = np.arange(256,dtype=np.int32).reshape(256,1)

  3. Which version of OpenCV are you using, and did you use a custom (looks like MATLAB-based) Python wrapper?
    I installed OpenCV 2.4.2 with their built in Python wrapper, but the function imread() doesn't exist. There is a LoadImageM() however.

    1. Please checkout the installation guide for OpenCV-Python interface here :

      This is new cv2 interface of OpenCV ( I use 2.4.1 version) along with Numpy Support, which is similar to Matlab.

  4. Hi Abid,

    I have the same problems as taketo eguchi on my Mac.

    It seems that the cv2.polylines statement at the end of the for loop causes this problem.

    I'm a newby on Python / OpenCVPython / Eclipse, and yesterday I tried your tutorial programs. Most of them work fine,
    but the pointpolygontest also crashed at the same call.

    A small exerpt of the crash report showed:

    Process: Python [2821]
    Path: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/
    Identifier: Python
    Version: ??? (???)
    Code Type: X86-64 (Native)
    Parent Process: eclipse [9272]

    Date/Time: 2012-07-15 18:40:13.111 +0200
    OS Version: Mac OS X Server 10.7.4 (11E53)
    Report Version: 9


    Thread 0 Crashed:: Dispatch queue:
    0 libsystem_kernel.dylib 0x00007fff89c7482a __kill + 10
    1 libsystem_c.dylib 0x00007fff9110aa9c abort + 177
    2 libc++abi.dylib 0x00007fff8b3df7bc abort_message + 214
    3 libc++abi.dylib 0x00007fff8b3dcfdd default_terminate() + 42
    4 libstdc++.6.dylib 0x00007fff967b787b std::terminate() + 21
    5 0x00000001050cfea3 _ZL18pyopencv_polylinesP7_objectS0_S0_ + 1011
    6 org.python.python 0x0000000104d3cfeb PyEval_EvalFrameEx + 18011
    7 org.python.python 0x0000000104d402a7 PyEval_EvalCodeEx + 2103
    8 org.python.python 0x0000000104d40326 PyEval_EvalCode + 54
    9 org.python.python 0x0000000104d5eaf4 PyRun_FileExFlags + 164
    10 org.python.python 0x0000000104d5fda8 PyRun_SimpleFileExFlags + 392
    11 org.python.python 0x0000000104d7316a Py_Main + 2874
    12 org.python.python 0x0000000104c94f14 0x104c94000 + 3860


    0x1051c9000 - 0x1053c6ff7 +libopencv_core.2.4.dylib (2.4.2 - compatibility 2.4.0) /opt/local/lib/libopencv_core.2.4.dylib

    Model: MacBookPro8,3, BootROM MBP81.0047.B27, 4 processors, Intel Core i7, 2.3 GHz, 8 GB, SMC 1.70f5
    Graphics: AMD Radeon HD 6750M, AMD Radeon HD 6750M, PCIe, 1024 MB
    Graphics: Intel HD Graphics 3000, Intel HD Graphics 3000, Built-In, 512 MB
    Memory Module: BANK 0/DIMM0, 4 GB, DDR3, 1333 MHz, 0x80CE, 0x4D34373142353237334448302D4348392020
    Memory Module: BANK 1/DIMM0, 4 GB, DDR3, 1333 MHz, 0x80CE, 0x4D34373142353237334448302D4348392020
    AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0xD6), Broadcom BCM43xx 1.0 (
    Bluetooth: Version 4.0.5f11, 2 service, 18 devices, 1 incoming serial ports
    Network Service: Ethernet, Ethernet, en0
    Serial ATA Device: APPLE SSD TS512C, 500.28 GB
    Serial ATA Device: MATSHITADVD-R UJ-8A8

    Anyway, thanks for the great help in learning OpenCVPython..!!!

    1. I am not sure what this error denote since I have no experience and access to Mac. It works fine in windows. Just for a try, change line 13 of above code as follows :

      pts = np.column_stack((bins,hist)).copy()

      and run the code. Please let me know what happens !!

    2. Hi,

      me too have the same error when i ran this code in Fedora 64-bit. But no problem in Windows 32-bit. So I think problem may be with 32-64 bit editions. Not sure.

  5. Might be a stupid question but im rather new to python. I have saved the script, run the module and i get the following error :

    Traceback (most recent call last):
    File "C:/Users/Mike/Desktop/script/script", line 10, in
    hist_item = cv2.calcHist([img],[ch],None,[256],[0,255])
    error: ..\..\..\src\opencv\modules\imgproc\src\histogram.cpp:148: error: (-215) j < nimages


    I am not sure but, where am i supposed to place the image? what would be the path? (i would of thought it should be in the same folder as the py script).

    1. Normally, i keep the images where I saved my script. So you need not specify complete path, just type image file name only. Otherwise also, no problem, just specify complete path. that's all.

  6. Hi there,

    I got same error as the guy above:

    OpenCV Error: Assertion failed (src.dims <= 2 && esz <= (size_t)32) in transpose, file /home/username/Desktop/OpenCV-2.3.1/modules/core/src/matrix.cpp, line 1680
    terminate called after throwing an instance of 'cv::Exception'
    what(): /home/username/Desktop/OpenCV-2.3.1/modules/core/src/matrix.cpp:1680: error: (-215) src.dims <= 2 && esz <= (size_t)32 in function transpose

    the error seems to be in this line:


  7. the size of the image is not 300*256

  8. Hi,

    I'm testing your example using the prompt from Windows XP. I typed the script, but when I run it, nothing happens! I get no erros, but I execute and then the program ends, it's not showing that histogram window. Why is that?


  9. Hi,

    i had same errors, i just add cv2.namedWindow('colorhist', cv.CV_WINDOW_AUTOSIZE) at the beginning and it works just fine.


    1. Thanks Lana that was the fix for me as:
      cv2.namedWindow('colorhist', cv2.CV_WINDOW_AUTOSIZE)

  10. Hey Abid,

    thanks for your code, I had some syntax trouble with getting the function to work, now everything works fine. In return I'd like to point out a bug in your code:

    -hist_item = cv2.calcHist([img],[ch],None,[256],[0,255])
    +hist_item = cv2.calcHist([img],[ch],None,[256],[0,256])

    Otherwise, values == 255 won't get counted. You can check this easily by summing up the histogram and check, that the result is not equal to the amount of pixels of your image.

    Regards, Matthäus

    1. Thank you Matthaus !!!

      I didn't notice it.