Reputation: 527
#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");
}
How come I need the line?
Mat drawing = Mat::zeros( img.size(), CV_8UC3 );
Like if I comment out that line then change the variable "drawing" to "img" in the rest of the code below it, how come I get a black screen showing up when I run it? Rather than just the canny converted image which makes the rest of the photo besides for the contour lines black? I'm assuming from what I read that the zero function changes the values of the matrix in the picture to 0 making it black, which would then cause the for loop to draw over the black picture showing only the contouring lines.
Upvotes: 1
Views: 374
Reputation: 9817
According to the documentation of findContours()
:
image – Source, an 8-bit single-channel image. Non-zero pixels are treated as 1’s. Zero pixels remain 0’s, so the image is treated as binary ... The function modifies the image while extracting the contours.
In particular, it modifies the type of the image to 8UC1. Finally, the function drawContours()
prints the contour in black, since it uses Scalars(0,255,0)
. Had you used Scalar(255,0,0)
, the issue would have remained unnoticed.
Simply modify the call to drawContours()
:
drawContours( img, contours, i, Scalar(255), 2, 8, hierarchy, 0, Point());
PS: the function of Octopus there can be used to print the type of the image.
Upvotes: 1