OpenCV C++,为什么不使用零功能会出现黑屏

OpenCV C++, how come I get a black screen without using the zero function?

本文关键字:功能 C++ 为什么不 OpenCV      更新时间:2023-10-16
#include <opencv2/core/core.hpp>
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main( int argc, char** argv ){
    //sets up image you want
    Mat img = imread("shape.jpg",CV_LOAD_IMAGE_GRAYSCALE);
    //checks to see if image was read
    if(img.empty()){
        cout<<"Image not found"<<endl;
        return -1;
    }
    //identifies the edges on the picture
    Canny(img, img, 200, 200,3 );
    //creates a vector of all the points that are contoured
    vector<vector<Point>> contours;
    //needed for function
    vector<Vec4i> hierarchy;
    //finds all the contours in the image and places it into contour vector array
    findContours( img, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
    Mat drawing = Mat::zeros( img.size(), CV_8UC3 );
    //loop allows you to re-draw out all the contours based on the points in the vector
    for( int i = 0; i< contours.size(); i++ )
    {
        drawContours( drawing, contours, i, Scalar(0,255,0), 2, 8, hierarchy, 0, Point());
    }
    //shows the images
    imshow("Pic",drawing);
    waitKey(0);
    destroyWindow("Pic");

}

我怎么需要这条线?

Mat drawing = Mat::zeros( img.size(), CV_8UC3 );

就像如果我注释掉那行,然后在它下面的其余代码中将变量"drawing"更改为"img",为什么当我运行它时会出现黑屏?而不仅仅是精明转换的图像,使照片的其余部分除了轮廓线变黑?我假设从我读到的内容中,零函数将图片中矩阵的值更改为 0 使其变为黑色,这将导致 for 循环在仅显示轮廓线的黑色图片上绘制。

根据findContours()的文档:

图像 – 源,8 位单通道图像。非零像素被视为 1。零像素保持 0,因此图像被视为二进制...该函数在提取轮廓时修改图像。

特别是,它将图像的类型修改为 8UC1。最后,该函数drawContours()将轮廓打印为黑色,因为它使用 Scalars(0,255,0) .如果你使用Scalar(255,0,0),这个问题就不会被注意到。

只需修改对drawContours()的调用:

drawContours( img, contours, i, Scalar(255), 2, 8, hierarchy, 0, Point());

PS:章鱼的功能可以用来打印图像的类型。