实验7.1
#include <bits/stdc++.h> #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/video.hpp" #include "opencv2/objdetect.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/ml.hpp" #define inf 2333333333333333 #define N 100010 #define p(a) putchar(a) #define For(i,a,b) for(int i=a;i<=b;++i) //by war //2020.10.27 using namespace std; using namespace cv; int n,k; Mat image,img0,out,labels,stats,centroids; void in(int &x){ int y=1;char c=getchar();x=0; while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();} while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();} x*=y; } void o(int x){ if(x<0){p('-');x=-x;} if(x>9)o(x/10); p(x%10+'0'); } signed main(){ srand(time(0)); img0 = imread("/Users/war/Downloads/1.png",0); threshold(img0, image, 128, 255, THRESH_BINARY); n=connectedComponentsWithStats(image, labels, stats, centroids); vector<Vec3b> v(n+1); v[0]=Vec3b(rand()%256,rand()%256,rand()%256); For(i,1,n){ v[i]=Vec3b(rand()%256,rand()%256,rand()%256); if(stats.at<int>(i,CC_STAT_AREA)<10000) v[i]=v[0]; } out=Mat::zeros(image.size(),CV_8UC3); For(i,0,out.rows-1) For(j,0,out.cols-1){ k=labels.at<int>(i,j); out.at<Vec3b>(i,j)=v[k]; } imshow("out",out); waitKey(); return 0; }