void run(int) { RNG& rng = theRNG(); for( int i = 0; i < 10; i++ ) { int m = rng.uniform(2, 11); int n = rng.uniform(2, 11); int depth = rng.uniform(0, 2) + CV_32F; Mat src8u(m, n, depth), src(m, n, depth), dst(m, n, CV_MAKETYPE(depth, 2)); Mat z = Mat::zeros(m, n, depth), dstz; randu(src8u, Scalar::all(0), Scalar::all(10)); src8u.convertTo(src, src.type()); dst = Scalar::all(123); Mat mv[] = {src, z}, srcz; merge(mv, 2, srcz); dft(srcz, dstz); dft(src, dst, DFT_COMPLEX_OUTPUT); if (cvtest::norm(dst, dstz, NORM_INF) > 1e-3) { cout << "actual:\n" << dst << endl << endl; cout << "reference:\n" << dstz << endl << endl; CV_Error(CV_StsError, ""); } } }
void drawKeypoints( const Mat& image, const vector<KeyPoint>& keypoints, Mat& outImage, const Scalar& _color, int flags ) { if( !(flags & DrawMatchesFlags::DRAW_OVER_OUTIMG) ) { if( image.type() == CV_8UC3 ) { image.copyTo( outImage ); } else if( image.type() == CV_8UC1 ) { cvtColor( image, outImage, CV_GRAY2BGR ); } else { CV_Error( CV_StsBadArg, "Incorrect type of input image.\n" ); } } RNG& rng=theRNG(); bool isRandColor = _color == Scalar::all(-1); CV_Assert( !outImage.empty() ); vector<KeyPoint>::const_iterator it = keypoints.begin(), end = keypoints.end(); for( ; it != end; ++it ) { Scalar color = isRandColor ? Scalar(rng(256), rng(256), rng(256)) : _color; _drawKeypoint( outImage, *it, color, flags ); } }
void drawKeypoints( InputArray image, const std::vector<KeyPoint>& keypoints, InputOutputArray outImage, const Scalar& _color, DrawMatchesFlags flags ) { CV_INSTRUMENT_REGION(); if( !(flags & DrawMatchesFlags::DRAW_OVER_OUTIMG) ) { if (image.type() == CV_8UC3 || image.type() == CV_8UC4) { image.copyTo(outImage); } else if( image.type() == CV_8UC1 ) { cvtColor( image, outImage, COLOR_GRAY2BGR ); } else { CV_Error( Error::StsBadArg, "Incorrect type of input image: " + typeToString(image.type()) ); } } RNG& rng=theRNG(); bool isRandColor = _color == Scalar::all(-1); CV_Assert( !outImage.empty() ); std::vector<KeyPoint>::const_iterator it = keypoints.begin(), end = keypoints.end(); for( ; it != end; ++it ) { Scalar color = isRandColor ? Scalar( rng(256), rng(256), rng(256), 255 ) : _color; _drawKeypoint( outImage, *it, color, flags ); } }
void drawCorrespondence(Mat &img, Point2f projected, Point2f keypoint) { RNG& rng=theRNG(); Scalar color(rng(256), rng(256), rng(256)); circle(img, keypoint, 5, color, 1); circle(img, projected, 5, color, -1); line(img, keypoint, projected, color); float distance = powf(projected.x-keypoint.x, 2) + powf(projected.y-keypoint.y, 2); }
TEST(Core_DFT, complex_output2) { for( int i = 0; i < 100; i++ ) { int type = theRNG().uniform(0, 2) ? CV_64F : CV_32F; int m = theRNG().uniform(1, 10); int n = theRNG().uniform(1, 10); Mat x(m, n, type), out; randu(x, -1., 1.); dft(x, out, DFT_ROWS | DFT_COMPLEX_OUTPUT); double nrm = cvtest::norm(out, NORM_INF); double thresh = n*m*2; if( nrm > thresh ) { cout << "x: " << x << endl; cout << "out: " << out << endl; ASSERT_LT(nrm, thresh); } } }
TEST(ML_ANN, ActivationFunction) { String folder = string(cvtest::TS::ptr()->get_data_path()); String original_path = folder + "waveform.data"; String dataname = folder + "waveform"; Ptr<TrainData> tdata = TrainData::loadFromCSV(original_path, 0); ASSERT_FALSE(tdata.empty()) << "Could not find test data file : " << original_path; RNG& rng = theRNG(); rng.state = 1027401484159173092; tdata->setTrainTestSplit(500); vector<int> activationType; activationType.push_back(ml::ANN_MLP::IDENTITY); activationType.push_back(ml::ANN_MLP::SIGMOID_SYM); activationType.push_back(ml::ANN_MLP::GAUSSIAN); activationType.push_back(ml::ANN_MLP::RELU); activationType.push_back(ml::ANN_MLP::LEAKYRELU); vector<String> activationName; activationName.push_back("_identity"); activationName.push_back("_sigmoid_sym"); activationName.push_back("_gaussian"); activationName.push_back("_relu"); activationName.push_back("_leakyrelu"); for (size_t i = 0; i < activationType.size(); i++) { Ptr<ml::ANN_MLP> x = ml::ANN_MLP::create(); Mat_<int> layerSizes(1, 4); layerSizes(0, 0) = tdata->getNVars(); layerSizes(0, 1) = 100; layerSizes(0, 2) = 100; layerSizes(0, 3) = tdata->getResponses().cols; x->setLayerSizes(layerSizes); x->setActivationFunction(activationType[i]); x->setTrainMethod(ml::ANN_MLP::RPROP, 0.01, 0.1); x->setTermCriteria(TermCriteria(TermCriteria::COUNT, 300, 0.01)); x->train(tdata, ml::ANN_MLP::NO_OUTPUT_SCALE); ASSERT_TRUE(x->isTrained()) << "Could not train networks with " << activationName[i]; #ifdef GENERATE_TESTDATA x->save(dataname + activationName[i] + ".yml"); #else Ptr<ml::ANN_MLP> y = Algorithm::load<ANN_MLP>(dataname + activationName[i] + ".yml"); ASSERT_TRUE(y != NULL) << "Could not load " << dataname + activationName[i] + ".yml"; Mat testSamples = tdata->getTestSamples(); Mat rx, ry, dst; x->predict(testSamples, rx); y->predict(testSamples, ry); double n = cvtest::norm(rx, ry, NORM_INF); EXPECT_LT(n,FLT_EPSILON) << "Predict are not equal for " << dataname + activationName[i] + ".yml and " << activationName[i]; #endif } }
void drawKeypoints( const Mat& image, const vector<KeyPoint>& keypoints, Mat& outImg, const Scalar& _color, int flags ) { if( !(flags & DrawMatchesFlags::DRAW_OVER_OUTIMG) ) cvtColor( image, outImg, CV_GRAY2BGR ); RNG& rng=theRNG(); bool isRandColor = _color == Scalar::all(-1); for( vector<KeyPoint>::const_iterator i = keypoints.begin(), ie = keypoints.end(); i != ie; ++i ) { Scalar color = isRandColor ? Scalar(rng(256), rng(256), rng(256)) : _color; _drawKeypoint( outImg, *i, color, flags ); } }
const Mat & setup(int N) const { static Mat proj; // else it can't be const ;( if (proj.rows==N && proj.cols==K) return proj; proj = Mat(N, K, CV_32F); theRNG().state = 37183927; randn(proj, Scalar(0.5), Scalar(0.5)); //randu(proj, Scalar(0), Scalar(1)); for (int i=0; i<K; i++) { normalize(proj.col(i), proj.col(i)); } return proj; }
static inline void _drawMatch( InputOutputArray outImg, InputOutputArray outImg1, InputOutputArray outImg2 , const KeyPoint& kp1, const KeyPoint& kp2, const Scalar& matchColor, DrawMatchesFlags flags ) { RNG& rng = theRNG(); bool isRandMatchColor = matchColor == Scalar::all(-1); Scalar color = isRandMatchColor ? Scalar( rng(256), rng(256), rng(256), 255 ) : matchColor; _drawKeypoint( outImg1, kp1, color, flags ); _drawKeypoint( outImg2, kp2, color, flags ); Point2f pt1 = kp1.pt, pt2 = kp2.pt, dpt2 = Point2f( std::min(pt2.x+outImg1.size().width, float(outImg.size().width-1)), pt2.y ); line( outImg, Point(cvRound(pt1.x*draw_multiplier), cvRound(pt1.y*draw_multiplier)), Point(cvRound(dpt2.x*draw_multiplier), cvRound(dpt2.y*draw_multiplier)), color, 1, LINE_AA, draw_shift_bits ); }
static inline void _drawMatch( Mat& outImg, Mat& outImg1, Mat& outImg2 , const KeyPoint& kp1, const KeyPoint& kp2, const Scalar& matchColor, int flags ) { RNG& rng = theRNG(); bool isRandMatchColor = matchColor == Scalar::all(-1); Scalar color = isRandMatchColor ? Scalar( rng(256), rng(256), rng(256) ) : matchColor; _drawKeypoint( outImg1, kp1, color, flags ); _drawKeypoint( outImg2, kp2, color, flags ); Point2f pt1 = kp1.pt, pt2 = kp2.pt, dpt2 = Point2f( std::min(pt2.x+outImg1.cols, float(outImg.cols-1)), pt2.y ); line( outImg, Point(cvRound(pt1.x*draw_multiplier), cvRound(pt1.y*draw_multiplier)), Point(cvRound(dpt2.x*draw_multiplier), cvRound(dpt2.y*draw_multiplier)), color, 1, CV_AA, draw_shift_bits ); }
void ImageSefmentByMeanshift(cv::Mat& src,cv::Mat& dst){ //#ifndef SPATIAL_RAD // #define SPATIAL_RAD 10 //#endif //#ifndef COLOR_RAD // #define COLOR_RAD 10 //#endif //#ifndef MAX_PRY_LEVEL // #define MAX_PRY_LEVEL 3 //#endif int spatialRad = 10; int colorRad = 10; int maxPryLevel = 1; //调用meanshift图像金字塔进行分割 pyrMeanShiftFiltering(src,dst,spatialRad,colorRad,maxPryLevel); RNG rng=theRNG(); Mat mask(dst.rows+2,dst.cols+2,CV_8UC1,Scalar::all(0)); for(int i=0;i<dst.rows;i++) //opencv图像等矩阵也是基于0索引的 for(int j=0;j<dst.cols;j++) if(mask.at<uchar>(i+1,j+1)==0) { Scalar newcolor(rng(256),rng(256),rng(256)); floodFill(dst,mask,Point(j,i),newcolor,0,Scalar::all(1),Scalar::all(1)); // floodFill(dst,mask,Point(i,j),newcolor,0,colorDiff,colorDiff); } imshow("src",src); imshow("dst",dst);waitKey(0); /*createTrackbar("spatialRad","dst",&spatialRad,80,meanshift_seg); createTrackbar("colorRad","dst",&colorRad,60,meanshift_seg); createTrackbar("maxPryLevel","dst",&maxPryLevel,5,meanshift_seg); imshow("src",src_S); imshow("dst",dst_S); waitKey();*/ }
void LaneDetection::AlgoFilterLanes_back(ntuple_list line_out){ unsigned int dim = line_out->dim; int n_size = line_out->size; vector< vector<int> > pairs;//each element is a vector of index of segment(s) pairs.resize(n_size); for (int i = 0; i < n_size; i++) { const Point2d p1(line_out->values[i * dim + 0], line_out->values[i * dim + 1]); const Point2d p2(line_out->values[i * dim + 2], line_out->values[i * dim + 3]); double longeur_p12 = dist_p2p(p1, p2); Segment2d s(p1, p2); //if (line_out->values[i * dim + 0] > 662 && line_out->values[i * dim + 0] < 664) //{ // int c = 0; //} //else // continue; Point2d milieu_p12 = (p1 + p2) / 2; for (int j = 0; j < n_size; j++) { if (j == i) continue; Point2d seg1(line_out->values[j * dim + 0], line_out->values[j * dim + 1]); Point2d seg2(line_out->values[j * dim + 2], line_out->values[j * dim + 3]); Segment2d seg(seg1, seg2); //simple check if (!s.isNeighbor(seg)) continue; //not same side //if ((cross(p1, seg1, seg2) > -0.0 ? 1 : -1) * (cross(p2, seg1, seg2) > -0.0 ? 1 : -1) < 0) //{ // continue; //} //slope difference double slope_dif = abs(atan(slope_seg(p1, p2)) - atan(slope_seg(seg1, seg2))); if (slope_dif > 10 * CV_PI / 180) { continue; } double longeur_seg = dist_p2p(seg1, seg2); Point2d t_p1, t_p2, t_seg1, t_seg2; if (longeur_p12 > longeur_seg * 3) { if (foot_p2segment(seg1, p1, p2, t_p1) && foot_p2segment(seg2, p1, p2, t_p2)) { t_seg1 = seg1; t_seg2 = seg2; } else { t_p1 = p1; t_p2 = p2; t_seg1 = seg1; t_seg2 = seg2; } } else if (longeur_seg > longeur_p12 * 3) { if (foot_p2segment(p1, seg1, seg2, t_seg1) && foot_p2segment(p2, seg1, seg2, t_seg2)) { t_p1 = p1; t_p2 = p2; } else { t_p1 = p1; t_p2 = p2; t_seg1 = seg1; t_seg2 = seg2; } } else { t_p1 = p1; t_p2 = p2; t_seg1 = seg1; t_seg2 = seg2; } Point2d p_start = (t_p1 + t_p2) / 2; Point2d p_end = (t_seg1 + t_seg2) / 2; //distance double thresh = 20; if (p_start.y < 2 * processImage.rows / 3 && p_end.y < 2 * processImage.rows / 3) thresh = 10; if (dist_p2segment(t_p1, t_seg1, t_seg2) > thresh && dist_p2segment(t_p2, t_seg1, t_seg2) > thresh) { continue; } //color condition int mean_color[3] = { 0, 0, 0 }; int num[3] = { 0, 0, 0 }; Point2d translation[3]; translation[0] = Point2d(0, 0); translation[1] = p_start - p_end; translation[2] = -translation[1]; for (int _trans = 0; _trans < 3; _trans++) { Rect box = getBoundingBox(t_p1 + translation[_trans], t_p2 + translation[_trans], t_seg1 + translation[_trans], t_seg2 + translation[_trans]); Point2d milieu = (p_start + p_end) / 2 + translation[_trans]; //check direction of cross. int direc = (cross(milieu, t_seg1 + translation[_trans], t_seg2 + translation[_trans]) > -EPS_HERE ? 1 : -1) * (cross(milieu, t_p1 + translation[_trans], t_p2 + translation[_trans]) > -EPS_HERE ? 1 : -1); for (int _y = box.y; _y < box.y + box.height; _y++) { if (_y >= processImage.rows || _y < 0) continue; uchar* ptr_row_processImage = ipmImage.ptr<uchar>(_y); for (int _x = box.x; _x < box.x + box.width; _x++) { if (_x >= processImage.cols || _x < 0) continue; Point2d p(_x, _y); if (direc != (cross(p, t_seg1 + translation[_trans], t_seg2 + translation[_trans]) > -EPS_HERE ? 1 : -1) * (cross(p, t_p1 + translation[_trans], t_p2 + translation[_trans]) > -EPS_HERE ? 1 : -1)) { continue; } mean_color[_trans] += ptr_row_processImage[_x]; num[_trans]++; } } mean_color[_trans] = (double)mean_color[_trans] / num[_trans]; } bool color_matched = (mean_color[0] > mean_color[1] + 30) && (mean_color[0] > mean_color[2] + 30); if (!color_matched) { //line(processImage, p1, p2, Scalar(255, 0, 0)); continue; } Rect box = getBoundingBox(t_p1, t_p2, t_seg1, t_seg2); Point2d milieu = (p_start + p_end) / 2; int _trans = 0; //check direction of cross. int direc = (cross(milieu, t_seg1 + translation[_trans], t_seg2 + translation[_trans]) > -EPS_HERE ? 1 : -1) * (cross(milieu, t_p1 + translation[_trans], t_p2 + translation[_trans]) > -EPS_HERE ? 1 : -1); for (int _y = box.y; _y < box.y + box.height; _y++) { if (_y >= processImage.rows || _y < 0) continue; Vec3b* ptr_row_processImage = processImage.ptr<Vec3b>(_y); for (int _x = box.x; _x < box.x + box.width; _x++) { if (_x >= processImage.cols || _x < 0) continue; Point2d p(_x, _y); if (direc != (cross(p, t_seg1 + translation[_trans], t_seg2 + translation[_trans]) > -EPS_HERE ? 1 : -1) * (cross(p, t_p1 + translation[_trans], t_p2 + translation[_trans]) > -EPS_HERE ? 1 : -1)) { continue; } ptr_row_processImage[_x] = Vec3b(255, 0, 255); } } //TODO: ADD MORE CONDITIONS to check if they are a pair. //line(processImage, p1, p2, Scalar(0, 255, 0)); //break; //add candidate pair to vector. } } ofstream fout("pairs.txt"); for (int i = 0; i < n_size; i++) { const Point2d p1(line_out->values[i * dim + 0], line_out->values[i * dim + 1]); const Point2d p2(line_out->values[i * dim + 2], line_out->values[i * dim + 3]); fout << i << "{" << p1 << "; " << p2 << "}" << " pairs: "; int b = (unsigned)theRNG() & 255; int g = (unsigned)theRNG() & 255; int r = (unsigned)theRNG() & 255; if (pairs[i].size() <= 1) continue; for (int j = 0; j < pairs[i].size(); j++) { Point2d seg1(line_out->values[pairs[i][j] * dim + 0], line_out->values[pairs[i][j] * dim + 1]); Point2d seg2(line_out->values[pairs[i][j] * dim + 2], line_out->values[pairs[i][j] * dim + 3]); fout << "[" << seg1 << "; " << seg2 << " ],"; } //line(processImage, p1, p2, Scalar(b, g, r)); //line(processImage, seg1, seg2, Scalar(b, g, r)); fout << "--------" << endl; } }
int minarea( int /*argc*/, char** /*argv*/ ) { help(); Mat img(500, 500, CV_8UC3); RNG& rng = theRNG(); for(;;) { int i, count = rng.uniform(1, 101); vector<Point> points; // Generate a random set of points for( i = 0; i < count; i++ ) { Point pt; pt.x = rng.uniform(img.cols/4, img.cols*3/4); pt.y = rng.uniform(img.rows/4, img.rows*3/4); points.push_back(pt); } // Find the minimum area enclosing bounding box RotatedRect box = minAreaRect(Mat(points)); // Find the minimum area enclosing triangle vector<Point2f> triangle; minEnclosingTriangle(points, triangle); // Find the minimum area enclosing circle Point2f center, vtx[4]; float radius = 0; minEnclosingCircle(Mat(points), center, radius); box.points(vtx); img = Scalar::all(0); // Draw the points for( i = 0; i < count; i++ ) circle( img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA ); // Draw the bounding box for( i = 0; i < 4; i++ ) line(img, vtx[i], vtx[(i+1)%4], Scalar(0, 255, 0), 1, LINE_AA); // Draw the triangle for( i = 0; i < 3; i++ ) line(img, triangle[i], triangle[(i+1)%3], Scalar(255, 255, 0), 1, LINE_AA); // Draw the circle circle(img, center, cvRound(radius), Scalar(0, 255, 255), 1, LINE_AA); imshow( "Rectangle, triangle & circle", img ); char key = (char)waitKey(); if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC' break; } return 0; }
double cv::kmeans( InputArray _data, int K, InputOutputArray _bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray _centers ) { const int SPP_TRIALS = 3; Mat data0 = _data.getMat(); bool isrow = data0.rows == 1; int N = isrow ? data0.cols : data0.rows; int dims = (isrow ? 1 : data0.cols)*data0.channels(); int type = data0.depth(); attempts = std::max(attempts, 1); CV_Assert( data0.dims <= 2 && type == CV_32F && K > 0 ); CV_Assert( N >= K ); Mat data(N, dims, CV_32F, data0.ptr(), isrow ? dims * sizeof(float) : static_cast<size_t>(data0.step)); _bestLabels.create(N, 1, CV_32S, -1, true); Mat _labels, best_labels = _bestLabels.getMat(); if( flags & CV_KMEANS_USE_INITIAL_LABELS ) { CV_Assert( (best_labels.cols == 1 || best_labels.rows == 1) && best_labels.cols*best_labels.rows == N && best_labels.type() == CV_32S && best_labels.isContinuous()); best_labels.copyTo(_labels); } else { if( !((best_labels.cols == 1 || best_labels.rows == 1) && best_labels.cols*best_labels.rows == N && best_labels.type() == CV_32S && best_labels.isContinuous())) best_labels.create(N, 1, CV_32S); _labels.create(best_labels.size(), best_labels.type()); } int* labels = _labels.ptr<int>(); Mat centers(K, dims, type), old_centers(K, dims, type), temp(1, dims, type); std::vector<int> counters(K); std::vector<Vec2f> _box(dims); Vec2f* box = &_box[0]; double best_compactness = DBL_MAX, compactness = 0; RNG& rng = theRNG(); int a, iter, i, j, k; if( criteria.type & TermCriteria::EPS ) criteria.epsilon = std::max(criteria.epsilon, 0.); else criteria.epsilon = FLT_EPSILON; criteria.epsilon *= criteria.epsilon; if( criteria.type & TermCriteria::COUNT ) criteria.maxCount = std::min(std::max(criteria.maxCount, 2), 100); else criteria.maxCount = 100; if( K == 1 ) { attempts = 1; criteria.maxCount = 2; } const float* sample = data.ptr<float>(0); for( j = 0; j < dims; j++ ) box[j] = Vec2f(sample[j], sample[j]); for( i = 1; i < N; i++ ) { sample = data.ptr<float>(i); for( j = 0; j < dims; j++ ) { float v = sample[j]; box[j][0] = std::min(box[j][0], v); box[j][1] = std::max(box[j][1], v); } } for( a = 0; a < attempts; a++ ) { double max_center_shift = DBL_MAX; for( iter = 0;; ) { swap(centers, old_centers); if( iter == 0 && (a > 0 || !(flags & KMEANS_USE_INITIAL_LABELS)) ) { if( flags & KMEANS_PP_CENTERS ) generateCentersPP(data, centers, K, rng, SPP_TRIALS); else { for( k = 0; k < K; k++ ) generateRandomCenter(_box, centers.ptr<float>(k), rng); } } else { if( iter == 0 && a == 0 && (flags & KMEANS_USE_INITIAL_LABELS) ) { for( i = 0; i < N; i++ ) CV_Assert( (unsigned)labels[i] < (unsigned)K ); } // compute centers centers = Scalar(0); for( k = 0; k < K; k++ ) counters[k] = 0; for( i = 0; i < N; i++ ) { sample = data.ptr<float>(i); k = labels[i]; float* center = centers.ptr<float>(k); j=0; #if CV_ENABLE_UNROLLED for(; j <= dims - 4; j += 4 ) { float t0 = center[j] + sample[j]; float t1 = center[j+1] + sample[j+1]; center[j] = t0; center[j+1] = t1; t0 = center[j+2] + sample[j+2]; t1 = center[j+3] + sample[j+3]; center[j+2] = t0; center[j+3] = t1; } #endif for( ; j < dims; j++ ) center[j] += sample[j]; counters[k]++; } if( iter > 0 ) max_center_shift = 0; for( k = 0; k < K; k++ ) { if( counters[k] != 0 ) continue; // if some cluster appeared to be empty then: // 1. find the biggest cluster // 2. find the farthest from the center point in the biggest cluster // 3. exclude the farthest point from the biggest cluster and form a new 1-point cluster. int max_k = 0; for( int k1 = 1; k1 < K; k1++ ) { if( counters[max_k] < counters[k1] ) max_k = k1; } double max_dist = 0; int farthest_i = -1; float* new_center = centers.ptr<float>(k); float* old_center = centers.ptr<float>(max_k); float* _old_center = temp.ptr<float>(); // normalized float scale = 1.f/counters[max_k]; for( j = 0; j < dims; j++ ) _old_center[j] = old_center[j]*scale; for( i = 0; i < N; i++ ) { if( labels[i] != max_k ) continue; sample = data.ptr<float>(i); double dist = normL2Sqr(sample, _old_center, dims); if( max_dist <= dist ) { max_dist = dist; farthest_i = i; } } counters[max_k]--; counters[k]++; labels[farthest_i] = k; sample = data.ptr<float>(farthest_i); for( j = 0; j < dims; j++ ) { old_center[j] -= sample[j]; new_center[j] += sample[j]; } } for( k = 0; k < K; k++ ) { float* center = centers.ptr<float>(k); CV_Assert( counters[k] != 0 ); float scale = 1.f/counters[k]; for( j = 0; j < dims; j++ ) center[j] *= scale; if( iter > 0 ) { double dist = 0; const float* old_center = old_centers.ptr<float>(k); for( j = 0; j < dims; j++ ) { double t = center[j] - old_center[j]; dist += t*t; } max_center_shift = std::max(max_center_shift, dist); } } } if( ++iter == MAX(criteria.maxCount, 2) || max_center_shift <= criteria.epsilon ) break; // assign labels Mat dists(1, N, CV_64F); double* dist = dists.ptr<double>(0); parallel_for_(Range(0, N), KMeansDistanceComputer(dist, labels, data, centers)); compactness = 0; for( i = 0; i < N; i++ ) { compactness += dist[i]; } } if( compactness < best_compactness ) { best_compactness = compactness; if( _centers.needed() ) centers.copyTo(_centers); _labels.copyTo(best_labels); } } return best_compactness; }
percepunit::percepunit(Mat *src) { Mat orig, meanshift, mask, flood, reconstruction, Matrice; vector<percepunit> percepunits; // dynamic vector to store instances of percepunit. image = *src; /// Copy the original image for in-place processing. image.copyTo(orig); image.copyTo(Matrice); // morphology (supports in place operation) Mat element = getStructuringElement(MORPH_ELLIPSE, Size(5,5), Point(2, 2) ); morphologyEx(image, image, MORPH_CLOSE, element); morphologyEx(image, image, MORPH_OPEN, element); // Mean shift filtering pyrMeanShiftFiltering(image, meanshift, 10, 35, 3); RNG rng = theRNG(); // place to store ffill masks mask = Mat( meanshift.rows+2, meanshift.cols+2, CV_8UC1, Scalar::all(0) ); // Make black single-channel image. meanshift.copyTo(flood); // copy image int area; Rect *boundingRect = new Rect(); // Stored bounding box for each flooded area. // Loop through all the pixels and flood fill. for( int y = 0; y < meanshift.rows; y++ ) { for( int x = 0; x < meanshift.cols; x++ ) { if( mask.at<uchar>(y+1, x+1) == 0 ) // mask is offset from original image. { Scalar newVal( rng(256), rng(256), rng(256) ); area = floodFill( flood, mask, Point(x,y), newVal, boundingRect, Scalar::all(1), Scalar::all(1), 8|255<<8); //Extract a subimage for each flood, if the flood is large enough. if (boundingRect->width >35 && boundingRect->height >35) { Mat ROI = orig(*boundingRect); // Make a cropped reference (not copy) of the image // crop translated mask to register with original image. boundingRect->y++; boundingRect->height++; boundingRect->x++; boundingRect->width++; Mat alpha = mask(*boundingRect); // Append an instance to the vector. percepunits.push_back(percepunit(ROI, alpha, boundingRect->x-1, boundingRect->y-1, boundingRect->width-1, boundingRect->height-1)); } } } } // New Image for reconstruction reconstruction = Mat(mask.rows,mask.cols,CV_8UC3, Scalar(0,0,0)); // red background /// Loop through instances and print for(int i = 0; i <percepunits.size(); i++) { // Copy percept into reconstruction. copyPercept(percepunits[i], reconstruction); } for (int row = 0 ; row < Matrice.rows ; row++ ) { for (int col = 0 ; col < Matrice.cols ; col++ ) { Matrice.at<uchar>(row,col) = reconstruction.at<uchar>(row,col); } } *src = Matrice; /// Destructor free memory orig.release(); meanshift.release(); mask.release(); flood.release(); reconstruction.release(); Matrice.release(); }
void Learner::learn(const Mat &img, const Mat &imgB, const Mat &img32F, const TYPE_BBOX &ret) { TYPE_TRAIN_DATA_SET &nnTrainDataset = detector->trainDataSetNN; nnTrainDataset.clear(); TYPE_TRAIN_DATA_SET &rfTrainDataset = detector->trainDataSetRF; rfTrainDataset.clear(); auto &scanBBs = detector->scanBBs; detector->sortByOverlap(ret, true); int count = 0; // P-expert - NN nnTrainDataset.push_back(make_pair(img32F(scanBBs[0]), CLASS_POS)); // P-expert - RF int tlx = img.cols, tly = img.rows, brx = 0, bry = 0; for(int i = 0; i < LEARNER_N_GOOD_BB && scanBBs[i].overlap >= GOODBB_OL; i++) { tlx = min(tlx, scanBBs[i].tl().x); tly = min(tly, scanBBs[i].tl().y); brx = max(brx, scanBBs[i].br().x); bry = max(bry, scanBBs[i].br().y); } Point tl(tlx, tly), br(brx, bry); Rect bbHull(tl, br); int cx, cy; cx = round((double)(tlx + brx) / 2); cy = round((double)(tly + bry) / 2); for(int j = 0; j < LEARNER_N_WARPED; j++) { Mat warped; if(j != 0) { patchGenerator(imgB, Point(cx, cy), warped, bbHull.size(), theRNG()); // for optimum in RF::getcode() Mat tmp(imgB.size() ,CV_8U, Scalar::all(0)); warped.copyTo(tmp(Rect(0, 0, bbHull.size().width, bbHull.size().height))); warped = tmp; } else { warped = imgB(bbHull); } for(int i = 0; i < LEARNER_N_GOOD_BB && scanBBs[i].overlap >= GOODBB_OL; i++) { Rect rect(scanBBs[i].tl() - tl, scanBBs[i].br() - tl); TYPE_TRAIN_DATA trainData(make_pair(warped(rect), CLASS_POS)); rfTrainDataset.push_back(trainData); count++; } } // N-expert - NN int nCountNN = 0; for(int i = 0; i < detector->scanBBs.size(); i++) { TYPE_DETECTOR_SCANBB &sbb = detector->scanBBs[i]; if(sbb.status != DETECTOR_REJECT_VAR) { if(sbb.overlap < BADBB_OL) { nCountNN++; TYPE_TRAIN_DATA trainData(make_pair(img32F(sbb), CLASS_NEG)); nnTrainDataset.push_back(trainData); } } if(nCountNN == LEARNER_N_NN_NEG) break; } // N-expert - RF int nCountRF = 0; for(int i = 0; i < detector->scanBBs.size(); i++) { TYPE_DETECTOR_SCANBB &sbb = detector->scanBBs[i]; if(sbb.status != DETECTOR_REJECT_VAR) { if(sbb.overlap < BADBB_OL && sbb.posterior >= 0.1) { nCountRF++; TYPE_TRAIN_DATA trainData(make_pair(imgB(sbb), CLASS_NEG)); rfTrainDataset.push_back(trainData); } } } stringstream info; info << "Generated 1 positive example for NN, and " << count << " positive example for RF."; outputInfo("Learner", info.str()); stringstream info2; info2 << "Generated " << nCountNN << " NN negative sample(s), and " << nCountRF << " RF negative example(s)."; outputInfo("Learner", info2.str()); detector->update(); stringstream info3; info3 << "Updated detector."; outputInfo("Learner", info3.str()); detector->nNClassifier.showModel(); }
MeanShiftChopper::MeanShiftChopper(){ rng = theRNG(); spatialRad = 80; colorRad = 60; maxPyrLevel = 5; }
inline Vec3d get_random_vec(double from = -10.0, double to = 10.0) { RNG& rng = theRNG(); return Vec3d(rng.uniform(from, to), rng.uniform(from, to), rng.uniform(from, to)); }
TEST_P(ML_ANN_METHOD, Test) { int methodType = get<0>(GetParam()); string methodName = get<1>(GetParam()); int N = get<2>(GetParam()); String folder = string(cvtest::TS::ptr()->get_data_path()); String original_path = folder + "waveform.data"; String dataname = folder + "waveform" + '_' + methodName; Ptr<TrainData> tdata2 = TrainData::loadFromCSV(original_path, 0); Mat samples = tdata2->getSamples()(Range(0, N), Range::all()); Mat responses(N, 3, CV_32FC1, Scalar(0)); for (int i = 0; i < N; i++) responses.at<float>(i, static_cast<int>(tdata2->getResponses().at<float>(i, 0))) = 1; Ptr<TrainData> tdata = TrainData::create(samples, ml::ROW_SAMPLE, responses); ASSERT_FALSE(tdata.empty()) << "Could not find test data file : " << original_path; RNG& rng = theRNG(); rng.state = 0; tdata->setTrainTestSplitRatio(0.8); Mat testSamples = tdata->getTestSamples(); #ifdef GENERATE_TESTDATA { Ptr<ml::ANN_MLP> xx = ml::ANN_MLP_ANNEAL::create(); Mat_<int> layerSizesXX(1, 4); layerSizesXX(0, 0) = tdata->getNVars(); layerSizesXX(0, 1) = 30; layerSizesXX(0, 2) = 30; layerSizesXX(0, 3) = tdata->getResponses().cols; xx->setLayerSizes(layerSizesXX); xx->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM); xx->setTrainMethod(ml::ANN_MLP::RPROP); xx->setTermCriteria(TermCriteria(TermCriteria::COUNT, 1, 0.01)); xx->train(tdata, ml::ANN_MLP::NO_OUTPUT_SCALE + ml::ANN_MLP::NO_INPUT_SCALE); FileStorage fs; fs.open(dataname + "_init_weight.yml.gz", FileStorage::WRITE + FileStorage::BASE64); xx->write(fs); fs.release(); } #endif { FileStorage fs; fs.open(dataname + "_init_weight.yml.gz", FileStorage::READ); Ptr<ml::ANN_MLP> x = ml::ANN_MLP_ANNEAL::create(); x->read(fs.root()); x->setTrainMethod(methodType); if (methodType == ml::ANN_MLP::ANNEAL) { x->setAnnealEnergyRNG(RNG(CV_BIG_INT(0xffffffff))); x->setAnnealInitialT(12); x->setAnnealFinalT(0.15); x->setAnnealCoolingRatio(0.96); x->setAnnealItePerStep(11); } x->setTermCriteria(TermCriteria(TermCriteria::COUNT, 100, 0.01)); x->train(tdata, ml::ANN_MLP::NO_OUTPUT_SCALE + ml::ANN_MLP::NO_INPUT_SCALE + ml::ANN_MLP::UPDATE_WEIGHTS); ASSERT_TRUE(x->isTrained()) << "Could not train networks with " << methodName; string filename = dataname + ".yml.gz"; Mat r_gold; #ifdef GENERATE_TESTDATA x->save(filename); x->predict(testSamples, r_gold); { FileStorage fs_response(dataname + "_response.yml.gz", FileStorage::WRITE + FileStorage::BASE64); fs_response << "response" << r_gold; } #else { FileStorage fs_response(dataname + "_response.yml.gz", FileStorage::READ); fs_response["response"] >> r_gold; } #endif ASSERT_FALSE(r_gold.empty()); Ptr<ml::ANN_MLP> y = Algorithm::load<ANN_MLP>(filename); ASSERT_TRUE(y != NULL) << "Could not load " << filename; Mat rx, ry; for (int j = 0; j < 4; j++) { rx = x->getWeights(j); ry = y->getWeights(j); double n = cvtest::norm(rx, ry, NORM_INF); EXPECT_LT(n, FLT_EPSILON) << "Weights are not equal for layer: " << j; } x->predict(testSamples, rx); y->predict(testSamples, ry); double n = cvtest::norm(ry, rx, NORM_INF); EXPECT_LT(n, FLT_EPSILON) << "Predict are not equal to result of the saved model"; n = cvtest::norm(r_gold, rx, NORM_INF); EXPECT_LT(n, FLT_EPSILON) << "Predict are not equal to 'gold' response"; } }