Error: Assertion failed (src.type() == CV_8UC1) in threshold

Error: Assertion failed (src.type() == CV_8UC1) in threshold

我尝试过使用 Otsu 阈值处理实时视频。但是我遇到了这个问题

OpenCV Error: Assertion failed (src.type() == CV_8UC1) in threshold, file /home/usr/opencv-3.2.0/modules/imgproc/src/thresh.cpp, line 1356 terminate called after throwing an instance of 'cv::Exception' what(): /home/usr/opencv-3.2.0/modules/imgproc/src/thresh.cpp:1356: error: (-215) src.type() == CV_8UC1 in function threshold

而且,这是我使用的编码

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include <opencv2/core/mat.hpp>
#include <iostream>
using namespace cv;

const String window_capture_name = "Video Capture";
const String window_capture_thres = "Video Threshold";

int main(int argc, char* argv[]){
VideoCapture cap(0);

namedWindow(window_capture_name);
namedWindow(window_capture_thres);

Mat Thres(1280, 720, CV_8UC4), frame(1280, 720, CV_8UC4), frame_thres(1280, 720, CV_8UC4);

while (true) {

    cap >> frame;

    Thres = threshold(frame, frame_thres, 0, 255, THRESH_OTSU);

    if(frame.empty())
    {
        break;
    }

    imshow(window_capture_name, Thres);
    imshow(window_capture_thres, frame);

    char key = (char) waitKey(30);
    if (key == 'q' || key == 27)
    {
        break;
    }
}
return 0;
}

阈值函数应用于单通道图像(如灰度图像)

所以我想这就是你的目标

cvtColor(frame, Thres, COLOR_BGR2GRAY);

threshold(Thres, frame_thres, 0, 255, THRESH_OTSU);

注意: 第一个和第二个阈值函数参数是输入图像,输出图像所以基本上你的阈值图像在 frame_thres

旁注:

Mat Thres(1280, 720, CV_8UC4), frame(1280, 720, CV_8UC4), frame_thres(1280, 720, CV_8UC4);

并不是真的有必要,因为它们都被重新分配了

Mat Thres, frame, frame_thres;

这应该够了