C++ Vector Subscript out of range with opencv error [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 19 days ago.
Improve this question
Any thoughts where I might be going wrong. PS: New to coding and StackOverFlow.
#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2/imgcodecs.hpp>
#include<opencv2/imgproc.hpp>
//Declare the image variables
cv::Mat img, imgGray, imgBlur, imgCanny, imgDil;
void GetContours(cv::Mat dilatedImg, cv::Mat originalImg);
int main(int argc, char** argv)
{
std::string path="E://Trial//Resources//Resources//shapes.png";
img= cv::imread(path);
//pre=processing
cv::cvtColor(img,imgGray,cv::COLOR_BGR2GRAY);
cv::GaussianBlur(imgGray, imgBlur,cv::Size(3,3),3,0);
cv::Canny(imgBlur,imgCanny,25,75);
cv::Mat kernel= cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3,3)) ;
cv::dilate(imgCanny,imgDil,kernel);
//Processing
GetContours(imgDil, img);
//Display contours
cv::imshow("Image",img);
cv::waitKey(0);
return 0;
}
void GetContours(cv::Mat dilatedImg, cv::Mat originalImg)
{
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
std::vector<std::vector<cv::Point>> conPoly(contours.size());
double area=0;
//finds the contours in the shapes
cv::findContours(dilatedImg, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for(int i=0; i<contours.size(); i++)
{
area = cv::contourArea(contours[i]);
std::cout<<area<<std::endl;
if(area>1000)
{
//Draw contours around shapes
cv::drawContours(originalImg,contours, i,cv::Scalar(255,0,255),2);
// create a bounding box around the shapes
cv::approxPolyDP(cv::Mat(contours[i]), conPoly[i], 3, true);
//draw contours using the contour points
cv::drawContours(originalImg,conPoly, i,cv::Scalar(255,255,0),2);
}
}
}
ApproxPollyDP is where I think the code is failing. I am getting an Assertion Failed error with vector out of range. I think I am doing some silly mistake but I have not been able to debug the issue.

The vector conPoly declared as shown below
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
std::vector<std::vector<cv::Point>> conPoly(contours.size());
is an empty vector because initially contours.size() is equal tp 0 because the vector contours in turn is declared as empty.
So using the subscript operator with the vector
cv::approxPolyDP(cv::Mat(contours[i]), conPoly[i], 3, true);
invokes undefined behavior.

So this works:
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
double area=0;
//finds the contours in the shapes
cv::findContours(dilatedImg, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
std::vector<std::vector<cv::Point>> conPoly(contours.size());

Related

Get color of contour

I'm using openCV + C++ to extract the contours of an image.
See these lines:
vector<vector<cv::Point>> contours;
vector<Vec4i> hierarchy;
cvtColor(image, image, CV_BGR2GRAY);
findContours( image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
for( int i = 0; i < contours.size(); i++ ) {
// do stuff with contours[i];
}
I was wondering if there is a way to extract the extract the main-color of the image.
From this image --> extract color "blue" as RGB;
Any help how to implement this in C++ would be very appreciated.
Note: This question (Finding contour color using opencv c++) was all I've found during my research but it looks like 1.the question is Off-Topic & 2.the question didn't get answered.

OpenCV C++ set background to transparent and crop

I am creating a stitching program and it works well. My next task is to crop the image so the image doesn't get too large and only contains the stitched areas. I am able to crop the image using the threshold() and findContours() functions. I then parse through the contours to determine where to crop. Another issue I wish to tackle in this function is to set the background to be transparent or alpha(255). My logic is take the base image to crop and do this step in conjunction with finding the area to crop. My code follows with portions that were taken from these two resources:
http://answers.opencv.org/question/37441/how-to-set-transparent-background-to-grabcut-output-image-in-opencv-c/
http://answers.opencv.org/question/24463/how-to-remove-black-background-from-grabcut-output-image-in-opencv-android/#24508
Mat crop(Mat image){
Mat cropped, grayed, thresh, transparent, result;
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
int largest_contour_index=0;
int largest_area=0;
Mat alpha(image.size(),CV_8UC1,Scalar(0));
cvtColor(image, grayed, CV_BGR2GRAY);
threshold( grayed, thresh, 1, 255,THRESH_BINARY);
findContours( thresh, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
vector<int> x,y;
for(int i=0; i < contours.size(); i++){
for(int j = 0; j < contours.at(i).size();j++){
double a=contourArea( contours[i],false); // Find the area of contour
if(a>largest_area){
largest_area=a;
largest_contour_index=i; //Store the index of largest contour
}
x.push_back(contours[i][j].x);
y.push_back(contours[i][j].y);
}
}
drawContours( alpha,contours, largest_contour_index, Scalar(255),CV_FILLED, 8, hierarchy );
Mat rgb[3];
split(image,rgb);
Mat rgba[4]={rgb[0],rgb[1],rgb[2],alpha};
merge(rgba,4,transparent);
imshow("Transparent",transparent);
waitKey();
destroyAllWindows();
auto xVals = std::minmax_element(x.begin(), x.end());
auto yVals = std::minmax_element(y.begin(), y.end());
Rect rect (*xVals.first,*yVals.first,(*xVals.second)-(*xVals.first),(*yVals.second)-(*yVals.first));
cropped = image(rect);
return cropped;
}
The following image is the result of this code. As you can see the crop work but the image background is not transparent
Any help is appreciated!

Get the location of a blob in OpenCV using C++

enter image description here
The image shown is the difference between two images. All I want to do is get the location of the white part. I want to do this because I want to be able to highlight the place where the difference is on the original image.
I am thinking about using clustering or blob detection or maybe just locating the brightest or whitest pixel in the image.
What method do you think would be the easiest? Is there another method I haven't though of?
Use the findContour method to find the closed contour in the image.
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( BinaryImage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
And you can draw that contours using drawContours .
And the variable contours contains the coordinates making that particular contour. You can display it by the following command
for(double i=0; i<contours.size(); i++)
{
cout << contours[i];
drawContours( OutputImage, contours, i, Scalar(0,255,0), 2, 8, hierarchy, 0, Point() );
}

Mark point of interest in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
My project's goal is to detect the lung's nodules , after filtering and classification i got a binary image like this:
my problem is i don't know how to mark these points of interest on the original image . In matlab ,i can do it easily with [hold on-off] a loop and some plot() function . But how do i do that in C++ , i don't mean to translate matlab code to C++ , i just need to mark these PoIs on the original image by any mean necessary .
Here is the result i want :
i did it in Matlab
EDIT : I already have the points's positions from my program (as you can see in the first image) all i want to do is draw them on the original image like the second one.
Try this...
from your binary image you can extract contours.
Then either draw the contours directly, or extract bounding circles that cover the whole contour.
I'll present both methods.
int main()
{
cv::Mat input = cv::imread("../inputData/markMatlab.png");
cv::Mat gray;
cv::cvtColor(input, gray, CV_BGR2GRAY);
cv::Mat binaryImage = gray>0;
cv::imshow("binary image", binaryImage);
// here you start
std::vector<std::vector<cv::Point> > contours;
cv::findContours(binaryImage, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
// either this:
cv::Mat inputBlobs = input.clone(); // create output image
for(unsigned int i=0; i<contours.size(); ++i)
{
cv::Point2f blobCenter;
float blobRadius;
cv::minEnclosingCircle(contours[i], blobCenter, blobRadius);
cv::circle(inputBlobs, blobCenter, blobRadius, cv::Scalar(0,0,255), 2);
}
// or this one:
cv::Mat inputContours = input.clone(); // create output image
for(unsigned int i=0; i<contours.size(); ++i)
{
cv::drawContours(inputContours, contours, i, cv::Scalar(0,0,255), 2);
}
cv::imshow("input", input);
cv::imshow("input blobs", inputBlobs);
cv::imshow("input contours", inputContours);
cv::imwrite("../outputData/markMatlab.png", input);
cv::imwrite("../outputData/markMatlabBlobs.png", inputBlobs);
cv::imwrite("../outputData/markMatlabContours.png", inputContours);
cv::waitKey(0);
return 0;
}
bounding circles:
drawing contours directly:
just use your original image as input for the drawing functions.
Have you tried:
Mat image;
image = imread(filename, CV_LOAD_IMAGE_COLOR);
And then using ellipse on it?
On maybe, if you do not know the coordinates, but you just have the resulting filtered image using blend

How to find points of drawcontour of a detected image?

I want to find points of a contour which is draw on object after following operation like background subtraction , findcontour ,drawcontour.
My object is moving so that my contour is also not proper . and i want to find of maximum and minimum points on contour which is draw on object.
Can anyone tell me how to find?
My object is moving car and camera view is top.
vector<vector<Point>> allContours;
vector<Vec4i> hierarchy;
Mat _temp = image.clone();
findContours(_temp, allContours, RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
allContours is contour's vector.
you can access points of each contours.
============================================================================
all points of contous will be draw by below code.
vector<vector<Point>> allContours;
vector<Vec4i> hierarchy;
Mat _temp = imageGray.clone();
Mat ptDraw = Mat::zeros(image.rows,image.cols,CV_8UC3);
findContours(_temp, allContours, RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
for(int i=0;i<allContours.size();i++)
{
drawContours(image, allContours, i, Scalar(0,0,255), 2, 8, hierarchy, 0, Point() );
for(int j=0;j<allContours.at(i).size();j++)
{
Point pt = allContours.at(i).at(j);
circle(ptDraw,pt,1,Scalar(0,0,255),CV_FILLED);
}
}