close

Drawing Histogram in OpenCV-Python

home

Drawing Histogram in OpenCV-Python

opencvpython.blogspot.com

Drawing Histogram in OpenCV-Python

Hi Friends,

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

Drawing Histogram in OpenCV-Python

See the histogram for above image for RGB channels.

Drawing Histogram in OpenCV-Python

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])
cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)
hist=np.int32(np.around(hist_item))
pts = np.column_stack((bins,hist))
cv2.polylines(h,[pts],False,col)

h=np.flipud(h)

cv2.imshow('colorhist',h)
cv2.waitKey(0)

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.











Share

20 Comments on OpenCV-Python: Drawing Histogram in OpenCV-Python

  • ADS
    on June 08, 2012 | 18:55 ADSsaid :
    "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,
    Alex"
  • abidk
    on June 08, 2012 | 19:49 abidksaid :
    "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?"
  • Anonymous
    on July 04, 2012 | 06:36 Anonymoussaid :
    "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?"
  • abidk
    on July 05, 2012 | 22:52 abidksaid :
    "Seeing it for the first time. By the way, which line throws this error?"
  • deranged_physicist
    on July 05, 2012 | 23:42 deranged_physicistsaid :
    "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."
  • abidk
    on July 06, 2012 | 00:13 abidksaid :
    "Please checkout the installation guide for OpenCV-Python interface here : http://opencvpython.blogspot.com/2012/05/install-opencv-in-windows-for-python.html

    This is new cv2 interface of OpenCV ( I use 2.4.1 version) along with Numpy Support, which is similar to Matlab."
  • Michael Geerings
    on July 15, 2012 | 22:16 Michael Geeringssaid :
    "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/Python.app/Contents/MacOS/Python
    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: com.apple.main-thread
    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 cv2.so 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

    ...

    Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/cv2.so
    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 (5.106.198.4.20)
    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..!!!"
  • abidk
    on July 15, 2012 | 23:00 abidksaid :
    "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 !!"
  • mike
    on August 05, 2012 | 18:43 mikesaid :
    "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)."
  • abidk
    on August 05, 2012 | 21:48 abidksaid :
    "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."
  • abidk
    on August 05, 2012 | 21:50 abidksaid :
    "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."
  • Taro
    on September 07, 2012 | 10:27 Tarosaid :
    "I got the same error. Did you manage to find out what's wrong?"
  • Anonymous
    on September 10, 2012 | 18:35 Anonymoussaid :
    "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:

    cv2.polylines(h,[pts],False,col)
    "
  • Anonymous
    on September 10, 2012 | 19:33 Anonymoussaid :
    "the size of the image is not 300*256"
  • Marco Antônio
    on September 24, 2012 | 09:09 Marco Antôniosaid :
    "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 test.py and then the program ends, it's not showing that histogram window. Why is that?

    Thanks!
    Marco"
  • Anonymous
    on October 29, 2012 | 01:10 Anonymoussaid :
    "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)
    "
  • Anonymous
    on November 11, 2012 | 23:17 Anonymoussaid :
    "Hi,

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

    Lana"
  • Matthäus Brandl
    on February 07, 2013 | 15:03 Matthäus Brandlsaid :
    "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"
  • abidk
    on February 07, 2013 | 21:02 abidksaid :
    "Thank you Matthaus !!!

    I didn't notice it. "
  • Anonymous
    on April 16, 2013 | 05:56 Anonymoussaid :
    "Thanks Lana that was the fix for me as:
    cv2.namedWindow('colorhist', cv2.CV_WINDOW_AUTOSIZE)"

Report "Drawing Histogram in OpenCV-Python"

Are you sure you want to report this post for ?

Cancel
×