OpenCV异常记录
异常描述
运行cv2.cvtColor函数时出现了:
error
OpenCV(4.4.0) c:\users\appveyor\appdata\local\temp\1\pip-req-build-h4wtvo23\opencv\modules\imgproc\src\color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function ‘__cdecl cv::impl::anonymous-namespace'::CvtHelper<struct cv::impl::
anonymous namespace’::Set<3,4,-1>,struct cv::impl::A0xe4950f71::Set<1,-1,-1>,struct cv::impl::A0xe4950f71::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class cv::_OutputArray &,int)’
Invalid number of channels in input image:
‘VScn::contains(scn)’
where
‘scn’ is 1”
解决方法
这个错误是因为输入的图像img是灰度图像,而cv2.cvtColor函数要求输入的图像img必须是彩色图像(即包含3个通道的BGR图像),因此在转换时出现了错误。可以通过判断img是否是灰度图像来避免这种错误,例如:
// An highlighted block
if img.ndim == 2:
mg_gray = save_img
else:
img_gray = cv2.cvtColor(save_img, cv2.COLOR_BGR2GRAY)