calcHist 的 CV2 错误“- 无法将 'channels' 的对象转换为向量,类型不受支持”

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

我正在尝试在 anaconda 的 spyder 上使用 cv2 创建和导出直方图。代码很简单,如下所示:

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)) 

我得到的错误如下

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

您需要将 channelshistSize 包装在这样的列表中:

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

你的掩码也不兼容计算器,我会像这样使用你已经创建的掩码数组:

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