Search code examples
c++opencvimage-thresholding

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


I've tried Real Time Video using Otsu thresholding. But i got this problem

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

And, here is the coding I used

#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;
}

Solution

  • threshold function is applied on one channel images ( like gray level images )

    so that's what you are aiming to do i suppose

    cvtColor(frame, Thres, COLOR_BGR2GRAY);
    
    threshold(Thres, frame_thres, 0, 255, THRESH_OTSU);
    

    NOTE : the first and the second threshold function paramters are input image , output image so basically your thresholded image is inside frame_thres

    SIDE NOTE :

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

    is not really necessary because they are all getting reassigned

    Mat Thres, frame, frame_thres;
    

    This should be enough