Search code examples
pythonopencvhistogram

CV2 error with calcHist "- Can't convert object to vector for 'channels', unsupported type"


I'm trying to create and export a histogram using cv2 on anaconda's spyder. The code is simple and looks like this:

import cv2
import matplotlib as plt
import numpy as np

#import image
image_positive = cv2.imread("C:/Users/matth/Pictures/S__4202500.jpg", cv2.COLOR_BGR2GRAY)

#mask creation
mask = np.zeros(image_positive.shape[:2], dtype="uint8")
cv2.circle(mask, (1070,4743), 737, 1, cv2.FILLED)
masked = cv2.bitwise_and(image_positive, image_positive, mask=mask)

#histogram creation
histogram_positive = cv2.calcHist(image_positive, 0, mask, 256, [0,256])

#histogram export to txt
with open('C:/Users/matth/Documents/Reliance/10um/histo.txt', 'w') as file:
   file.write(list(histogram_positive)) 

The error I am getting is as follows

error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'calcHist' Overload resolution failed:

  • Can't convert object to vector for 'channels', unsupported type
  • Can't convert object to vector for 'channels', unsupported type

Solution

  • You need to wrap channels and histSize in a list like this:

    histogram_positive = cv2.calcHist(image_positive, [0], mask, [256], [0,256])
    

    Your mask is also not compatible with the calc, I would just use the masked array that you already created like this:

    histogram_positive = cv2.calcHist(masked, [0], None, [256], [0,256])