89 lines
2.2 KiB
C++
89 lines
2.2 KiB
C++
|
#include "opencv2/opencv.hpp"
|
||
|
|
||
|
int traitement(cv::VideoCapture cap, int seuil, cv::Vec3b couleur) {
|
||
|
cv::Mat trame, gris, flou, contx, conty, cont, contbin;
|
||
|
std::vector<std::vector<cv::Point> > contours;
|
||
|
std::vector<cv::Vec4i> hierarchy;
|
||
|
int X,Y,x,y,k,nbcont,numc,index;
|
||
|
cap>>trame;
|
||
|
X=trame.rows;
|
||
|
Y=trame.cols;
|
||
|
cv::namedWindow("Image", 1);
|
||
|
cv::imshow("Image", trame);
|
||
|
cv::cvtColor(trame, gris, CV_BGR2GRAY);
|
||
|
cv::GaussianBlur(gris, flou, cv::Size(5, 5), 0, 0);
|
||
|
cv::Sobel(flou, contx, CV_64F, 1, 0);
|
||
|
cv::Sobel(flou, conty, CV_64F, 0, 1);
|
||
|
cont = abs(contx) + abs(conty);
|
||
|
contbin = (cont<seuil);
|
||
|
cv::namedWindow("Gradient", 1);
|
||
|
cv::imshow("Gradient", cont/255);
|
||
|
findContours(contbin, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);
|
||
|
cv::Mat marqueurs = cv::Mat::zeros(X, Y, CV_32S);
|
||
|
nbcont = (int)contours.size();
|
||
|
index = 1;
|
||
|
|
||
|
for(numc = 0; numc < nbcont; numc++ ) {
|
||
|
if (hierarchy[numc][3]<0) {
|
||
|
cv::drawContours( marqueurs, contours, numc, index++);
|
||
|
}
|
||
|
}
|
||
|
cv::watershed(trame, marqueurs);
|
||
|
std::vector<std::array<double,3>> couleurs;
|
||
|
std::vector<double> indexcoul;
|
||
|
couleurs.reserve(nbcont);
|
||
|
indexcoul.reserve(nbcont);
|
||
|
for(index = 0; index < nbcont; index++) {
|
||
|
for(k=0;k<3;k++) {
|
||
|
couleurs[index][k]=0.0;
|
||
|
}
|
||
|
indexcoul[index]=0.0;
|
||
|
}
|
||
|
for(x=0;x<X;x++) {
|
||
|
for(y=0;y<Y;y++) {
|
||
|
index=marqueurs.at<int>(x,y)-1;
|
||
|
if (index>=0) {
|
||
|
indexcoul[index]++;
|
||
|
for (k=0;k<3;k++) {
|
||
|
couleurs[index][k] = couleurs[index][k]+trame.at<cv::Vec3b>(x,y)[k];
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
for(index=0;index<nbcont;index++) {
|
||
|
for (k=0;k<3;k++) {
|
||
|
couleurs[index][k]/=indexcoul[index];
|
||
|
}
|
||
|
}
|
||
|
for(x=0;x<X;x++) {
|
||
|
for(y = 0; y < Y; y++) {
|
||
|
index=marqueurs.at<int>(x,y)-1;
|
||
|
if (index>=0) {
|
||
|
for (k = 0; k < 3; k++) {
|
||
|
trame.at<cv::Vec3b>(x,y)[k] = couleurs[index][k];
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
trame.at<cv::Vec3b>(x,y) = couleur;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
cv::namedWindow("LPE", 1);
|
||
|
cv::imshow("LPE", trame);
|
||
|
|
||
|
if(cv::waitKey(30) == 27) {
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
int main(int, char**) {
|
||
|
cv::VideoCapture cap(0);
|
||
|
int seuil=10;
|
||
|
cv::Vec3b couleur(128,128,128);
|
||
|
while(traitement(cap,seuil,couleur) == false);
|
||
|
}
|
||
|
|
||
|
|
||
|
|