cv::Mat ManualTracker::generateMarkersForFrame(int fnum, cv::Size fsize) { std::map<int, std::vector<double> > cells; cv::Mat markers(fsize, CV_32S, cv::Scalar::all(0)); try { cells = (sp->getAllCells()).at(fnum); } catch (const std::out_of_range& oor) { std::cerr << "Out of Range error: " << oor.what() << '\n'; return markers; } std::vector< std::vector<cv::Point2f> > contours(1); for (std::map<int, std::vector<double> >::iterator it=cells.begin(); it!=cells.end(); ++it) { std::vector<double> curCell = it->second; cv::Point2f center(curCell[3], curCell[4]); cv::Size2f size(curCell[6], curCell[5]); cv::RotatedRect box(center, size, curCell[8]); cv::Point2f vertices[4]; box.points(vertices); cv::Point2i intVertices[4]; for (int i=0; i<4; i++) { intVertices[i].x = vertices[i].x; intVertices[i].y = vertices[i].y; } cv::fillConvexPoly(markers, intVertices, 4, curCell[0]); } return markers; }
/*******************************************************************************************************************//** * \brief Determine prime numbers up to an upper bound. * * Uses the 'Sieve of Eratosthenes' algorithm. * See http://en.wikipedia.org/w/index.php?title=Sieve_of_Eratosthenes&oldid=527676398. * * \param n The maximum prime number. * * \return All prime numbers <= n in ascending order. **********************************************************************************************************************/ std::vector<uint_t> getPrimes( const uint_t n ) { if( n < 2 ) return std::vector<uint_t>(); std::vector<bool> markers( n+1, false ); std::vector<uint_t> primes; size_t p = 2; while( p <= n / 2 ) { primes.push_back(p); for( size_t i = p + p; i <= n; i += p ) markers[i] = true; for( p = p + 1; p <= n / 2 && markers[p]; ++p ) ; // empty body } for( uint_t i = n / 2 + 1; i <= n; ++i ) if( !markers[i] ) primes.push_back(i); return primes; }
int PME::match(const std::string & s, ///< s String to match against unsigned offset ///< offset Offset at which to start matching ) { size_t msize; pcre_fullinfo(re, 0, PCRE_INFO_CAPTURECOUNT, &msize); msize = 3*(msize+1); int *m = new int[msize]; vector<markers> marks; // if we got a new string, reset the global position counter if ( addressoflaststring != (void *) &s ) { // fprintf ( stderr, "PME RESETTING: new string\n" ); lastglobalposition = 0; } if ( m_isglobal ) { offset += lastglobalposition; } //check that the offset isn't at the last position in the string if( offset == s.length() ) return 0; nMatches = pcre_exec(re, extra, s.c_str(), s.length(), offset, 0, m, msize); for ( int i = 0, *p = m ; i < nMatches ; i++, p+=2 ) { marks.push_back(markers(p[0], p[1])); } delete[] m; // store the last set of results locally, as well as returning them m_marks = marks; laststringmatched = s; addressoflaststring = (void *) &s; if ( m_isglobal ) { if ( nMatches == PCRE_ERROR_NOMATCH ) { // fprintf ( stderr, "PME RESETTING: reset for no match\n" ); lastglobalposition = 0; // reset the position for next match (perl does this) } else if ( nMatches > 0 ) { // fprintf ( stderr, "PME RESETTING: setting to %d\n", marks[0].second ); lastglobalposition = marks[0].second; // increment by the end of the match } else { // fprintf ( stderr, "PME RESETTING: reset for no unknown\n" ); lastglobalposition = 0; } } int returnvalue = 0; if ( nMatches > 0 ) returnvalue = nMatches; return returnvalue; }
// Takes color image and set of points provided by Python, outputs relative // position and orientation void find_totes_depth(cv::Mat color, cv::Mat depth, std::vector<Target> &r_targets, std::vector<cv::Point> points, double effective_height, double depth_correction, int hfov, int vfov) { /* Separate image into depth layers and discard bottom layer */ cv::Mat levels(depth); levels.convertTo(levels, CV_8UC1); for (int i = 0; i < levels.size().width; i++) { for (int j = 0; j < levels.size().height; j++) { uchar tmp = int(levels.at<uchar>(i,j) - round((depth.size().height-j)*(depth_correction/depth.size().height))); if (tmp >= 220) { levels.at<uchar>(i,j) = 0; } else if (tmp >= 208 && tmp < 220) { levels.at<uchar>(i,j) = 1; } else if (tmp >= 180 && tmp < 208) { levels.at<uchar>(i,j) = 2; } else { levels.at<uchar>(i,j) = 3; } } } /* Designate one point in the background at level 0 as a point so that the algorithm works */ bool done = false; for (int i = 0; i < levels.size().width && !done; i++) { for (int j = 0; j < levels.size().height && !done; j++) { if (levels.at<uchar>(i,j) == 0) { points.push_back(cv::Point(i,j)); done = true; } } } /* Discard bottom level of color image */ cv::Mat processed; cv::bitwise_and(color, color, processed, levels); /* Apply watershed to color */ int height = depth.size().height; int width = depth.size().width; cv::Mat markers(height, width, CV_32F); for (int i = 0; i < points.size(); i++) { cv::Scalar color(i, i*100, i); cv::circle(markers, points[i], 1, color, 20); } cv::watershed(color, markers); for (int i = 0; i < points.size()-1 /* all but background point */; i++) { acv::Target target; target.type = "kinect tote"; // Set level (orientation) for tote. target.orientation = std::to_string(levels.at<uchar>(points[i].x,points[i].y)); // Set angle for each tote. /* TODO Build std::vector<cv::Point> containing all points within tote */ //cv::Rect min_rect = cv::minAreaRect( /* TODO Take bottom left and right points and get angle of tote from trig */ // TODO Set coords with: // int fov_to_pix_per_ft(int frame_dim, double effective_height, int hfov, int vfov); } }
bool Segmentation::watershed_segmentation(std::string image_name)//, PointCloudElement* pElement) { cv::Mat src; cv::Mat median_image; cv::Mat binary; src = cv::imread(path + "/Results/" +image_name, 1); cv::medianBlur (src, median_image, 5); cv::cvtColor(median_image, binary, CV_BGR2GRAY); cv::Scalar temp_mean; cv::Scalar temp_std; cv::Scalar temp_mode = cv_matrix_mode (binary); // on the test tile of the test point cloud is 109 cv::meanStdDev(binary, temp_mean, temp_std, cv::Mat()); double mean = temp_mean.val[0]; double std = temp_std.val[0]; double mode = temp_mode.val[0]; segmentation_msg += "Tile " + StringUtilities::toDisplayString(k_for_process_all_point_cloud) + "\n" + "MEAN \n" + StringUtilities::toDisplayString(mean) + "\n"+ "STD DEV \n"+StringUtilities::toDisplayString(std)+ "\n" + "MODE \n"+StringUtilities::toDisplayString(mode)+ "\n\n"; cv::threshold(binary, binary, mode + std::max(9.0, 1.1*(mean - mode)), 255, cv::THRESH_BINARY_INV); // Eliminate noise and smaller objects c++ cv::Mat fg; cv::erode(binary, fg, cv::Mat(), cv::Point(-1,-1), 2); // Identify image pixels without objects cv::Mat bg; cv::dilate(binary, bg, cv::Mat(), cv::Point(-1,-1), 3); cv::threshold(bg, bg, 1, 128, cv::THRESH_BINARY_INV); // Create markers image cv::Mat markers(binary.size(),CV_8U,cv::Scalar(0)); markers = fg + bg; // Create watershed segmentation object WatershedSegmenter segmenter; segmenter.setMarkers(markers); cv::Mat result = segmenter.process(median_image); ////////////////// DISABLED WARNINGS AS ERRORS /////////////////////// // these lines are needed to remove the tiles contours (watershed identifies as building countours also the tile contours, and I need to remove them otherwise there are problems with the connected component method) result.col(1).copyTo(result.col(0)); // I disabled the warning treated as errors: to re-enable, add the enable warnings property sheet (see http://opticks.org/irclogs/%23opticks/%23opticks.2014-05-27-Tue.txt) result.col(result.cols-2).copyTo(result.col(result.cols-1));//http://stackoverflow.com/questions/6670818/opencv-c-copying-a-row-column-in-a-mat-to-another result.row(1).copyTo(result.row(0)); // I disabled the warning treated as errors: to re-enable, add the enable warnings property sheet result.row(result.rows-2).copyTo(result.row(result.rows-1)); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! result_tiles_array[k_for_process_all_point_cloud] = result; // this line must be commented when using only one tile // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! result.convertTo(result, CV_8U); cv::waitKey(0); return true; }
object create_sound_source(sqf_string_const_ref type_, const vector3 &pos_, const std::vector<marker> &markers_/* = {}*/, float placement_/* = 0.0f*/) { auto_array<game_value> markers(markers_.begin(), markers_.end()); game_value args({ type_, pos_, std::move(markers), placement_, }); return object(host::functions.invoke_raw_unary(__sqf::unary__createsoundsource__array__ret__object, args)); }
void OptiTrackNatNetClient::draw(const sofa::core::visual::VisualParams* vparams) { const float trackedMarkersSize = drawTrackedMarkersSize.getValue(); if (trackedMarkersSize > 0) { //sofa::helper::vector<sofa::defaulttype::Vector3> markers = trackedMarkers.getValue(); const sofa::helper::vector<sofa::defaulttype::Vec3f>& val = trackedMarkers.getValue(); sofa::helper::vector<sofa::defaulttype::Vector3> markers(val.size()); for (unsigned int i=0; i<val.size(); ++i) markers[i] = val[i]; vparams->drawTool()->drawSpheres(markers, trackedMarkersSize, drawTrackedMarkersColor.getValue()); } const float otherMarkersSize = drawOtherMarkersSize.getValue(); if (otherMarkersSize > 0) { //sofa::helper::vector<sofa::defaulttype::Vector3> markers = otherMarkers.getValue(); const sofa::helper::vector<sofa::defaulttype::Vec3f>& val = otherMarkers.getValue(); sofa::helper::vector<sofa::defaulttype::Vector3> markers(val.size()); for (unsigned int i=0; i<val.size(); ++i) markers[i] = val[i]; vparams->drawTool()->drawSpheres(markers, otherMarkersSize, drawOtherMarkersColor.getValue()); } }
main() { // A study is the top level component that contains the model and other // computational components. Study inverseKinematicsStudy; Model model("subject_01.osim"); inverseKinematicsStudy.addComponent(model); // A data Source component wraps a TimeSeriesTables and access rows by time // Each column is given its own Output by name unless specified otherwise Source markers("subject01_trial2.trc"); // Source markers("subject01_trial2.trc", Vec2(0, 5)); // by range // Source markers("subject01_trial2.trc", {"aa, "ai", ac"}); //by name inverseKinematicsStudy.addComponent(markers); // InverseKinematicsSolver is wrapped by a component (or one itself?) // dependency on model, and marker inputs (outputs of a source) wired // upon connect InverseKinematics ik(model, markers); inverseKinematicsStudy.addComponent(ik); // Now handle IK Outputs // Extract the outputs from the model and the state via a reporter // Do not need to know type BUT cannot combine different types // Coordinates are doubles and modelMarkers are Vec3's OutputReporter coordinateReporter(); OutputReporter modelMarkerReporter(); // Output coordinates from IK for(const auto& coord: mode.getCoordinates()) coordinateReporter.addOutput(coord.getOutput("value")); inverseKinematicsStudy.addComponent(coordinateReporter); // Output model marker locations from IK for (const auto& marker : mode.getMarkers()) modelMarkerReporter.addOutputs(marker.getOutput("location")); inverseKinematicsStudy.addComponent(modelMarkerReporter); State& state = inverseKinematicsStudy.initSystem(); // March through time to solve for the state's coordinates for (double t : markers.getTimes()) { state.setTime(t); ik.track(state); inverseKinematicsStudy.realizeReport(state); } // write results to file FileAdapter fileAdapter; fileAdapter.write("s01_tr2_IK.mot", coordinateReporter.getReport()); fileAdapter.write("s01_tr2_markers.trc", modelMarkerReporter.getReport()); }
int main() { //»ñÈ¡²¢ÏÔʾÔͼÏñ cv::Mat image = cv::imread("D:\\OpenCV demos\\images\\group.jpg"); if(!image.data) return 0; cv::namedWindow("Original Image"); cv::imshow("Original Image",image); //ÏÔʾ¶þ½øÖÆͼ cv::Mat binary; binary = cv::imread("D:\\OpenCV demos\\images\\binary.bmp",0); //¸¯Ê´½µÔë cv::Mat fg; cv::erode(binary,fg,cv::Mat(),cv::Point(-1,-1),6); cv::namedWindow("Foreground Image"); cv::imshow("Foreground Image",fg); //¼ì²â±³¾° cv::Mat bg; cv::dilate(binary,bg,cv::Mat(),cv::Point(-1,-1),6); cv::threshold(bg,bg,1,128,cv::THRESH_BINARY_INV); cv::namedWindow("Background Image"); cv::imshow("Background Image",bg); //Make and Show markers image cv::Mat markers(binary.size(),CV_8U,cv::Scalar(0)); markers = fg + bg; cv::namedWindow("markers"); cv::imshow("markers",markers); //segmentation using watershed WatershedSegementer segmenter; segmenter.setMarkers(markers); segmenter.process(image); cv::namedWindow("Segmentation"); cv::imshow("Segmentation",segmenter.getSegementation()); cv::namedWindow("Watersheds"); cv::imshow("Watersheds",segmenter.getWatersheds()); cv::waitKey(); return 0; }
void LineSpec::setSpec(QString arg) { if (spec() == arg) return; int lastInd = arg.length() - 1; if (markers().contains(arg.mid(lastInd, 1))) { setMarker(arg.mid(lastInd, 1)); lastInd--; } if (colorMap.contains(arg.mid(lastInd, 1))) { setColor(colorMap[arg.mid(lastInd, 1)]); lastInd--; } QString style = arg.left(lastInd + 1); if (!style.isEmpty()) setStyle(style); emit specChanged(arg); }
void ImageSegmentor::createMarkers(cv::Mat& targetBlobs, int maxHeight, int maxWidth) { std::vector< vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; std::vector<int> contourList; cv::Mat contourSourceImage; cv::Mat finalStorage(targetBlobs.size(), CV_8U, cv::Scalar::all(BLACK)); cv::Mat tempStorage(targetBlobs.size(), CV_8U, cv::Scalar::all(BLACK)); cv::Mat markers(targetBlobs.size(), CV_32S, cv::Scalar::all(0)); targetBlobs.copyTo(contourSourceImage); cv::findContours(contourSourceImage, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); cv::Mat laplace = ImageProcessor::laplacian(originalImage, 27); for( unsigned int i = 0; i< contours.size(); i++ ) { if(hierarchy[i][3] != -1) continue; //it's a hole! this->breakLargeContours(tempStorage, laplace, contours, hierarchy, i, maxHeight, maxWidth); cv::bitwise_or(finalStorage, tempStorage, finalStorage); } cv::findContours(finalStorage, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); int nc = 0; for( unsigned int i = 0; i< contours.size(); i++ ) { if(hierarchy[i][3] != -1) continue; //it's a hole! contourList.push_back(i); nc++; cv::drawContours(markers, contours, i, cv::Scalar::all(nc+1), -1, 8, hierarchy, INT_MAX); } markersCont mc; mc.markers = markers; mc.contours = contours; mc.hierarchy = hierarchy; mc.contourList = contourList; markersPic = markers; }
void ImageSegmentor::createMarkersIterative(cv::Mat& origImage, cv::Mat &landscape, int maxHeight, int maxWidth) { std::vector< vector<cv::Point> > ctours; std::vector<cv::Vec4i> hrchy; double hDim, wDim; cv::Mat targets(origImage.size(), CV_8U, cv::Scalar::all(BLACK)); for (int th = 20; th < 250; th += 10) { //increase threshold for distance transf. cv::Mat threshResult = ImageProcessor::threshold(landscape, th, false); cv::Mat newContour; threshResult.copyTo(newContour); //find connected components in the thresholded pic cv::findContours(newContour, ctours, hrchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); int cc = ctours.size(); for (int j = 0; j < cc; j++) { cv::RotatedRect boxTemp = cv::minAreaRect(ctours[j]); CellCont::detectHeightWidth(boxTemp, &hDim, &wDim); //draw the connected components which obey the criterion if (hDim < maxHeight && wDim < maxWidth) { cv::drawContours(targets, ctours, j, cv::Scalar::all(WHITE), -1, 8, hrchy, INT_MAX); } } } cv::Mat markers(origImage.size(), CV_32S, cv::Scalar::all(0)); cv::findContours(targets, ctours, hrchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); int nc = 0; for( unsigned int i = 0; i< ctours.size(); i++ ) { if(hrchy[i][3] != -1) continue; //it's a hole! nc++; cv::drawContours(markers, ctours, i, cv::Scalar::all(nc+1), -1, 8, hrchy, INT_MAX); } markersPic = markers; }
cv::Mat PathDetect::WatershedImage(const cv::Mat& input) const { // Create markers image cv::Mat markers(input.size(),CV_8U,cv::Scalar(0)); for (int i = 0; i < input.rows; ++i) { for (int j = 0; j < input.cols; ++j) { unsigned char value = 0; double r = input.at<cv::Vec3b>(i,j)[2]; double g = input.at<cv::Vec3b>(i,j)[1]; double b = input.at<cv::Vec3b>(i,j)[0]; if (r > g && r > b) value = PATH; if (g > r && g > b) value = NOT_PATH; markers.at<unsigned char>(i,j) = value; } } // Create watershed segmentation object WatershedSegmenter segmenter; segmenter.setMarkers(markers); return segmenter.process(input); }
int main() { // Read input image cv::Mat image= cv::imread("../images/group.jpg"); if (!image.data) return 0; // Display the image cv::namedWindow("Original Image"); cv::imshow("Original Image",image); // Get the binary map cv::Mat binary; binary= cv::imread("../images/binary.bmp",0); // Display the binary image cv::namedWindow("Binary Image"); cv::imshow("Binary Image",binary); // Eliminate noise and smaller objects cv::Mat fg; cv::erode(binary,fg,cv::Mat(),cv::Point(-1,-1),6); // Display the foreground image cv::namedWindow("Foreground Image"); cv::imshow("Foreground Image",fg); // Identify image pixels without objects cv::Mat bg; cv::dilate(binary,bg,cv::Mat(),cv::Point(-1,-1),6); cv::threshold(bg,bg,1,128,cv::THRESH_BINARY_INV); // Display the background image cv::namedWindow("Background Image"); cv::imshow("Background Image",bg); // Show markers image cv::Mat markers(binary.size(),CV_8U,cv::Scalar(0)); markers= fg+bg; cv::namedWindow("Markers"); cv::imshow("Markers",markers); // Create watershed segmentation object WatershedSegmenter segmenter; // Set markers and process segmenter.setMarkers(markers); segmenter.process(image); // Display segmentation result cv::namedWindow("Segmentation"); cv::imshow("Segmentation",segmenter.getSegmentation()); // Display watersheds cv::namedWindow("Watersheds"); cv::imshow("Watersheds",segmenter.getWatersheds()); // Open another image image= cv::imread("../images/tower.jpg"); if (!image.data) return 0; // Identify background pixels cv::Mat imageMask(image.size(),CV_8U,cv::Scalar(0)); cv::rectangle(imageMask,cv::Point(5,5),cv::Point(image.cols-5,image.rows-5),cv::Scalar(255),3); // Identify foreground pixels (in the middle of the image) cv::rectangle(imageMask,cv::Point(image.cols/2-10,image.rows/2-10), cv::Point(image.cols/2+10,image.rows/2+10),cv::Scalar(1),10); // Set markers and process segmenter.setMarkers(imageMask); segmenter.process(image); // Display the image with markers cv::rectangle(image,cv::Point(5,5),cv::Point(image.cols-5,image.rows-5),cv::Scalar(255,255,255),3); cv::rectangle(image,cv::Point(image.cols/2-10,image.rows/2-10), cv::Point(image.cols/2+10,image.rows/2+10),cv::Scalar(1,1,1),10); cv::namedWindow("Image with marker"); cv::imshow("Image with marker",image); // Display watersheds cv::namedWindow("Watersheds of foreground object"); cv::imshow("Watersheds of foreground object",segmenter.getWatersheds()); // Open another image image= cv::imread("../images/tower.jpg"); // define bounding rectangle cv::Rect rectangle(50,70,image.cols-150,image.rows-180); cv::Mat result; // segmentation result (4 possible values) cv::Mat bgModel,fgModel; // the models (internally used) // GrabCut segmentation cv::grabCut(image, // input image result, // segmentation result rectangle,// rectangle containing foreground bgModel,fgModel, // models 1, // number of iterations cv::GC_INIT_WITH_RECT); // use rectangle // Get the pixels marked as likely foreground cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ); // Generate output image cv::Mat foreground(image.size(),CV_8UC3,cv::Scalar(255,255,255)); image.copyTo(foreground,result); // bg pixels not copied // draw rectangle on original image cv::rectangle(image, rectangle, cv::Scalar(255,255,255),1); cv::namedWindow("Image"); cv::imshow("Image",image); // display result cv::namedWindow("Segmented Image"); cv::imshow("Segmented Image",foreground); // Open another image image= cv::imread("../images/group.jpg"); // define bounding rectangle cv::Rect rectangle2(10,100,380,180); cv::Mat bkgModel,fgrModel; // the models (internally used) // GrabCut segmentation cv::grabCut(image, // input image result, // segmentation result rectangle2,bkgModel,fgrModel,5,cv::GC_INIT_WITH_RECT); // Get the pixels marked as likely foreground // cv::compare(result,cv::GC_PR_FGD,result,cv::CMP_EQ); result= result&1; foreground.create(image.size(),CV_8UC3); foreground.setTo(cv::Scalar(255,255,255)); image.copyTo(foreground,result); // bg pixels not copied // draw rectangle on original image cv::rectangle(image, rectangle2, cv::Scalar(255,255,255),1); cv::namedWindow("Image 2"); cv::imshow("Image 2",image); // display result cv::namedWindow("Foreground objects"); cv::imshow("Foreground objects",foreground); cv::waitKey(); return 0; }
int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { //Load media if( !loadMedia() ) { printf( "Failed to load media!\n" ); } else { //Main loop flag int selectedPlayer = 0; bool quit = false; SDL_Rect destination,source; SDL_Rect tmpR; bool setLoc = false; tmpR.w = 10; tmpR.h = 10; locationState* tmpLS; // game board Pane aPane(0,0,804,700); // players area Pane bPane(804,0,SCREEN_WIDTH - 804,700); sprites playerStars("playerStars.txt"); sprites playerDice("dice.txt"); sprites playerArtifacts("artifacts.txt"); sprites playerDilemma("dilemmas.txt"); sprites playerResources("resources.txt"); sprites playerRecruits("recruits.txt"); sprites marketTiles("FactorySprites.txt"); sprites digits("numberSprites.txt"); sprites markers("gameMarkers.txt"); sprites blockingTiles("BlockingTiles.txt"); // Default everything to one pane then fix the few that belong in another pane. for(int i = 0; i < NUMLOCALS; i++) { boardLocation[i]->setTargetPane(&aPane); } boardLocation[PLAYER_ARTIFACTS]->setTargetPane(&bPane); boardLocation[PLAYER_DILEMMA]->setTargetPane(&bPane); boardLocation[PLAYER_RESOURCES]->setTargetPane(&bPane); boardLocation[PLAYER_WORKERS]->setTargetPane(&bPane); boardLocation[PLAYER_RECRUITS]->setTargetPane(&bPane); // The majority of locations use either dice or stars, so roughly set them all to that and fix the few different ones next. for(int i = 0; i < NUMLOCALS; i++) { if(i < 15) boardLocation[i]->setSourceArray(&playerStars); else boardLocation[i]->setSourceArray(&playerDice); } boardLocation[PLAYER_ARTIFACTS]->setSourceArray(&playerArtifacts); boardLocation[PLAYER_DILEMMA]->setSourceArray(&playerDilemma); boardLocation[PLAYER_RESOURCES]->setSourceArray(&digits); boardLocation[PLAYER_WORKERS]->setSourceArray(&playerDice); boardLocation[PLAYER_RECRUITS]->setSourceArray(&playerRecruits); boardLocation[MARKET_TILES]->setSourceArray(&marketTiles); boardLocation[MARKET_STARS]->setSourceArray(&playerStars); boardLocation[E_TRACK]->setSourceArray(&markers); boardLocation[I_TRACK]->setSourceArray(&markers); boardLocation[S_TRACK]->setSourceArray(&markers); boardLocation[W_TRACK]->setSourceArray(&markers); boardLocation[BLOCKED_LOCATIONS]->setSourceArray(&blockingTiles); // set the justification for number locations once now at the start as they shouldn't need to change during the game. ((numberLocation*)(boardLocation[PLAYER_RESOURCES]))->setJustification(0,LEFT_JUSTIFY); ((numberLocation*)(boardLocation[PLAYER_RESOURCES]))->setJustification(1, LEFT_JUSTIFY); ((numberLocation*)(boardLocation[PLAYER_RESOURCES]))->setJustification(2, LEFT_JUSTIFY); ((numberLocation*)(boardLocation[PLAYER_RESOURCES]))->setJustification(3, LEFT_JUSTIFY); ((numberLocation*)(boardLocation[PLAYER_RESOURCES]))->setJustification(4,RIGHT_JUSTIFY); ((numberLocation*)(boardLocation[PLAYER_RESOURCES]))->setJustification(5,RIGHT_JUSTIFY); ((numberLocation*)(boardLocation[PLAYER_RESOURCES]))->setJustification(6,RIGHT_JUSTIFY); tmpLS = gGameState.GetLocationX(BLOCKED_LOCATIONS); if( tmpLS != NULL) { if (!tmpLS->addStateValue(3, 1, NULL)) fprintf(stderr,"Awooga1\n"); if (!tmpLS->addStateValue(4, 1, NULL)) fprintf(stderr,"Awooga2\n"); if (!tmpLS->addStateValue(5, 1, NULL)) fprintf(stderr,"Awooga2\n"); if (!tmpLS->addStateValue(6, 1, NULL)) fprintf(stderr,"Awooga2\n"); if (!tmpLS->addStateValue(7, 2, NULL)) fprintf(stderr,"Awooga2\n"); if (!tmpLS->addStateValue(8, 2, NULL)) fprintf(stderr,"Awooga2\n"); if (!tmpLS->addStateValue(9, 2, NULL)) fprintf(stderr,"Awooga2\n"); } else { fprintf(stderr,"Error getting location X\n"); } // variables to track timing incase I want to animate anything. Uint32 tBeginning = SDL_GetTicks(); Uint32 tDelta = 0; Uint32 tPrev = SDL_GetTicks(); //Event handler SDL_Event e; //While application is running while( !quit ) { /*********/ // Input // /*********/ //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { // Throw all events at my mouseEvent function and it'll decide if it's actually a mouse event or not. mouseEvent(&e); //User requests quit if( e.type == SDL_QUIT ) { quit = true; } else if( e.type == SDL_KEYDOWN ) { // Handles basic keyboard input. May want to move it to a keyboardEvent function if it needs to get fancier. // Just used in testing at the moment. switch( e.key.keysym.sym ) { case SDLK_1: selectedPlayer = 0; break; case SDLK_2: selectedPlayer = 1; break; case SDLK_3: selectedPlayer = 2; break; case SDLK_4: selectedPlayer = 3; break; case SDLK_5: selectedPlayer = 4; break; case SDLK_6: selectedPlayer = 5; break; case SDLK_x: tmpR.w++; break; case SDLK_z: if(tmpR.w - 1 > 0) tmpR.w--; break; case SDLK_y: tmpR.h++; break; case SDLK_t: if(tmpR.h - 1 > 0) tmpR.h--; break; } } } // Update all the various data structures with the information from the "input". tDelta = SDL_GetTicks() - tPrev; tPrev = SDL_GetTicks(); update(tDelta); //Clear screen SDL_SetRenderDrawColor( gRenderer, 0xBB, 0xBB, 0xBB, 0xFF ); SDL_RenderClear( gRenderer ); // Probably should change 0 and 8 to something more human readable, but they just refer to texture id's, so might be more trouble than worth it. gTM->RenderTextureToViewport(0, *aPane.getViewport()); gTM->RenderTextureToViewport(8, *bPane.getViewport()); // Draw all the locations. // Need to make sure in the enum that the locations like the player stars that appear on the markets // come after the markets so aren't drawn underneath where they can't be seen. for(int i = 0; i < NUMLOCALS; i++) { boardLocation[i]->draw(gTM); } // testing stuff if(true) { if(gRMouseState == 1 && RtargetDestinationID == -1) { RtargetDestinationID = 1; fprintf(stderr, "Right Mouse Down happened at x=%d, y=%d\n", gMousex,gMousey); int sourceID = ((Mto1gLocation*)boardLocation[GENERATOR])->SourceClickedOn(gMousex,gMousey); if(sourceID != -1 ) { ((Mto1gLocation*)boardLocation[GENERATOR])->removeValue(sourceID); } } if(gRMouseState == 0 && RtargetDestinationID > -1) { RtargetDestinationID = -1; } if(gMouseState == 1 && targetDestinationID == -1) { fprintf(stderr,"x=%d,y=%d\n",gMousex,gMousey); for( int i=0; i < NUMLOCALS; i++) { targetDestinationID = boardLocation[i]->isTargeted(gMousex,gMousey); if(targetDestinationID > -1) { targetedLocal = boardLocation[i]; targetedLocal2 = (Mto1gLocation*)boardLocation[i]; break; } else if( targetDestinationID == -2) { fprintf(stderr, "bad i = %d!\n", i); } } } if(gMouseState == 0 && targetDestinationID > -1) { if(targetedLocal->isTargeted(gMousex,gMousey) != - 1) { if (targetedLocal->getType() == MCVtoOL ) { targetedLocal2->addValue(selectedPlayer); } else { targetedLocal->setValue(targetDestinationID, selectedPlayer); } } targetedLocal = NULL; targetDestinationID = -1; // reset mouse } } else { /* Create accurate location info */ if(gMouseState == 1) // Mouse down, display sprite at location { int tmpSID = 0; sprites* tmpSprite; Pane* tmpP; tmpR.x = gMousex; tmpR.y = gMousey; setLoc = true; tmpSID = selectedPlayer; tmpSprite = &blockingTiles; if( gMousex >= (aPane.getViewport())->x && gMousex < ( (aPane.getViewport())->x + (aPane.getViewport())->w) ) { tmpP = &aPane; } else { tmpP = &bPane; tmpR.x = gMousex - bPane.getViewport()->x; tmpR.y = gMousey - bPane.getViewport()->y; } gTM->RenderTextureToViewport(4, *tmpP->getViewport(), &tmpR, tmpSprite->getSource(tmpSID)); } } if(gMouseState == 0 && setLoc == true) { setLoc = false; fprintf(stderr,"%d %d %d %d\n", tmpR.x, tmpR.y, tmpR.w, tmpR.h); } //Update screen SDL_RenderPresent( gRenderer ); } } } //Free resources and close SDL close(); return 0; }
RideFile *SrmFileReader::openRideFile(QFile &file, QStringList &errorStrings, QList<RideFile*>*) const { if (!file.open(QFile::ReadOnly)) { errorStrings << QString("can't open file %1").arg(file.fileName()); return NULL; } QDataStream in(&file); in.setByteOrder( QDataStream::LittleEndian ); RideFile *result = new RideFile; result->setDeviceType("SRM"); result->setFileFormat("SRM training files (srm)"); result->setTag("Sport", "Bike" ); char magic[4]; in.readRawData(magic, sizeof(magic)); if( strncmp(magic, "SRM", 3)){ errorStrings << QString("Unrecognized file type, missing magic." ); return NULL; } int version = magic[3] - '0'; switch( version ){ case 5: case 6: case 7: // ok break; default: errorStrings << QString("Unsupported SRM file format version: %1") .arg(version); return NULL; } quint16 dayssince1880 = readShort(in); quint16 wheelcirc = readShort(in); quint8 recint1 = readByte(in); quint8 recint2 = readByte(in); quint16 blockcnt = readShort(in); quint16 markercnt = readShort(in); readByte(in); // padding quint8 commentlen = readByte(in); if( commentlen > 70 ) commentlen = 70; char comment[71]; in.readRawData(comment, sizeof(comment) - 1); comment[commentlen] = '\0'; result->setTag("Notes", QString(comment) ); // assert propper markercnt to avoid segfaults if( in.status() != QDataStream::Ok ){ errorStrings << QString("failed to read file header" ); return NULL; } result->setRecIntSecs(((double) recint1) / recint2); unsigned recintms = (unsigned) round(result->recIntSecs() * 1000.0); result->setTag("Wheel Circumference", QString("%1").arg(wheelcirc) ); QDate date(1880, 1, 1); date = date.addDays(dayssince1880); QVector<marker> markers(markercnt + 1); for (int i = 0; i <= markercnt; ++i) { char mcomment[256]; size_t mcommentlen = version < 6 ? 3 : 255; assert( mcommentlen < sizeof(mcomment) ); in.readRawData(mcomment, mcommentlen ); mcomment[mcommentlen] = '\0'; quint8 active = readByte(in); quint16 start = readShort(in); quint16 end = readShort(in); quint16 avgwatts = readShort(in); quint16 avghr = readShort(in); quint16 avgcad = readShort(in); quint16 avgspeed = readShort(in); quint16 pwc150 = readShort(in); // data fixup: Although the data chunk index in srm files starts // with 1, some srmwin wrote files referencing index 0. if( end < 1 ) end = 1; if( start < 1 ) start = 1; // data fixup: some srmwin versions wrote markers with start > end if( end < start ){ markers[i].start = end; markers[i].end = start; } else { markers[i].start = start; markers[i].end = end; } markers[i].note = QString( mcomment); if( i == 0 ){ result->setTag("Athlete Name", QString(mcomment) ); } (void) active; (void) avgwatts; (void) avghr; (void) avgcad; (void) avgspeed; (void) pwc150; (void) wheelcirc; } // fail early to tell devs whats wrong with file if( in.status() != QDataStream::Ok ){ errorStrings << QString("failed to read marker" ); return NULL; } blockhdr *blockhdrs = new blockhdr[blockcnt+1]; for (int i = 0; i < blockcnt; ++i) { // In the .srm files generated by Rainer Clasen's srmcmd, // hsecsincemidn is a *signed* 32-bit integer. I haven't seen a // negative value in any .srm files generated by srmwin.exe, but // since the number of hundredths of a second in a day is << 2^31, // it seems safe to always treat this number as signed. qint32 hsecsincemidn = readLong(in); blockhdrs[i].chunkcnt = readShort(in); blockhdrs[i].dt = QDateTime(date); blockhdrs[i].dt = blockhdrs[i].dt.addMSecs(hsecsincemidn * 10); } // fail early to tell devs whats wrong with file if( in.status() != QDataStream::Ok ){ errorStrings << QString("failed to read block headers" ); return NULL; } quint16 zero = readShort(in); quint16 slope = readShort(in); quint16 datacnt = readShort(in); readByte(in); // padding // fail early to tell devs whats wrong with file if( in.status() != QDataStream::Ok ){ errorStrings << QString("failed to read calibration data" ); return NULL; } result->setTag("Slope", QString("%1") .arg( 140.0 / 42781 * slope, 0, 'f', 2) ); result->setTag("Zero Offset", QString("%1").arg(zero) ); // SRM5 files have no blocks - synthesize one if( blockcnt < 1 ){ blockcnt = 0; blockhdrs[0].chunkcnt = datacnt; blockhdrs[0].dt = QDateTime(date); } int blknum = 0, blkidx = 0, mrknum = 0, interval = 0; double km = 0.0, secs = 0.0; if (markercnt > 0) mrknum = 1; for (int i = 0; i < datacnt; ++i) { int cad, hr, watts; double kph, alt; double temp=-255; if (version < 7) { quint8 ps[3]; in.readRawData((char*) ps, sizeof(ps)); cad = readByte(in); hr = readByte(in); kph = (((((unsigned) ps[1]) & 0xf0) << 3) | (ps[0] & 0x7f)) * 3.0 / 26.0; watts = (ps[1] & 0x0f) | (ps[2] << 0x4); alt = 0.0; } else { assert(version == 7); watts = readShort(in); cad = readByte(in); hr = readByte(in); qint32 kph_tmp = readSignedLong(in); kph = kph_tmp < 0 ? 0 : kph_tmp * 3.6 / 1000.0; alt = readSignedLong(in); temp = 0.1 * readSignedShort(in); } if (i == 0) { result->setStartTime(blockhdrs[blknum].dt); } if (mrknum < markers.size() && i == markers[mrknum].end) { ++interval; ++mrknum; } // markers count from 1 if ((i > 0) && (mrknum < markers.size()) && (i == markers[mrknum].start - 1)) ++interval; km += result->recIntSecs() * kph / 3600.0; double nm = watts / 2.0 / PI / cad * 60.0; result->appendPoint(secs, cad, hr, km, kph, nm, watts, alt, 0.0, 0.0, 0.0, 0.0, temp, 0.0, interval); ++blkidx; if ((blkidx == blockhdrs[blknum].chunkcnt) && (blknum + 1 < blockcnt)) { QDateTime end = blockhdrs[blknum].dt.addMSecs( recintms * blockhdrs[blknum].chunkcnt); ++blknum; blkidx = 0; QDateTime start = blockhdrs[blknum].dt; qint64 endms = ((qint64) end.toTime_t()) * 1000 + end.time().msec(); qint64 startms = ((qint64) start.toTime_t()) * 1000 + start.time().msec(); double diff_secs = (startms - endms) / 1000.0; if (diff_secs < result->recIntSecs()) { errorStrings << QString("ERROR: time goes backwards by %1 s" " on trans " "to block %2" ).arg(diff_secs).arg(blknum); secs += result->recIntSecs(); // for lack of a better option } else { secs += diff_secs; } } else { secs += result->recIntSecs(); } } // assert some points were found. prevents segfault when looking at // the overall markers[0].start/.end // note: we're not checking in.status() to cope with truncated files if( result->dataPoints().size() < 1 ){ errorStrings << QString("file contains no data points"); return NULL; } double last = 0.0; for (int i = 1; i < markers.size(); ++i) { const marker &marker = markers[i]; int start = qMin(marker.start, result->dataPoints().size()) - 1; double start_secs = result->dataPoints()[start]->secs; int end = qMin(marker.end - 1, result->dataPoints().size() - 1); double end_secs = result->dataPoints()[end]->secs + result->recIntSecs(); if( last < start_secs ) result->addInterval(last, start_secs, ""); QString note = QString("%1").arg(i); if( marker.note.length() ) note += QString(" ") + marker.note; if( start_secs <= end_secs ) result->addInterval(start_secs, end_secs, note ); last = end_secs; } if (!markers.empty() && markers.last().end < result->dataPoints().size()) { double start_secs = result->dataPoints().last()->secs + result->recIntSecs(); result->addInterval(last, start_secs, ""); } file.close(); return result; }
/** Splits into at most maxfields. If maxfields is unspecified or 0, ** trailing empty matches are discarded. If maxfields is positive, ** no more than maxfields fields will be returned and trailing empty ** matches are preserved. If maxfields is empty, all fields (including ** trailing empty ones) are returned. This *should* be the same as the ** perl behaviour */ int PME::split(const std::string & s, unsigned maxfields) { /// stores the marks for the split vector<markers> oMarks; // this is a list of current trailing empty matches if maxfields is // unspecified or 0. If there is stuff in it and a non-empty match // is found, then everything in here is pushed into oMarks and then // the new match is pushed on. If the end of the string is reached // and there are empty matches in here, they are discarded. vector<markers> oCurrentTrailingEmpties; int nOffset = 0; int nMatchesFound = 0; // while we are still finding matches and maxfields is 0 or negative // (meaning we get all matches), or we haven't gotten to the number // of specified matches int nMatchStatus; while ( ( nMatchStatus = match ( s, nOffset ) ) && ( ( maxfields < 1 ) || nMatchesFound < maxfields ) ) { nMatchesFound++; // printf ( "nMatchesFound = %d\n", nMatchesFound ); // check to see if the match is empty if ( nOffset != m_marks [ 0 ].first ) { //fprintf ( stderr, "Match is not empty\n" ); // if this one isn't empty, then make sure to push anything from // oCurrentTrailingEmpties into oMarks oMarks.insert ( oMarks.end ( ), oCurrentTrailingEmpties.begin ( ), oCurrentTrailingEmpties.end ( ) ); // grab from nOffset to m_marks[0].first and again from m_marks[0].second to // the end of the string oMarks.push_back ( markers ( nOffset, m_marks [ 0 ].first ) ); } // else the match was empty and we have to do some checking // to see what to do else { //fprintf ( stderr, "match was empty\n" ); // if maxfields == 0, discard empty trailing matches if ( maxfields == 0 ) { //fprintf ( stderr, "putting empty into trailing empties list"); oCurrentTrailingEmpties.push_back ( markers ( nOffset, m_marks [ 0 ].first ) ); } // else we keep all the matches, empty or no else { //fprintf ( stderr, "Keeping empty match\n" ); // grab from nOffset to m_marks[0].first and again from m_marks[0].second to // the end of the string oMarks.push_back ( markers ( nOffset, m_marks [ 0 ].first ) ); } } // set nOffset to the beginning of the second part of the split nOffset = m_marks [ 0 ].second; fflush ( stdout ); } // end while ( match ( ... ) ) //fprintf ( stderr, "***match status = %d offset = %d\n", nMatchStatus, nOffset); // if there were no matches found, push the whole thing on if ( nMatchesFound == 0 ) { // printf ( "Putting the whole thing in..\n" ); oMarks.push_back ( markers ( 0, s.length ( ) ) ); } // if we ran out of matches, then append the rest of the string // onto the end of the last split field else if ( maxfields > 0 && nMatchesFound >= maxfields ) { // printf ( "Something else..\n" ); oMarks [ oMarks.size ( ) - 1 ].second = s.length ( ); } // else we have to add another entry for the end of the string else { // printf ( "Something REALLY else..\n" ); oMarks.push_back ( markers ( m_marks [ 0 ].second, s.length ( ) ) ); } m_marks = oMarks; //fprintf ( stderr, "match returning %d\n", m_marks.size ( ) ); nMatches = m_marks.size ( ); return m_marks.size ( ); }
int main() { //ocl::setUseOpenCL(true); VideoCapture video("/Users/sonhojun/Downloads/data/all.mp4"); if(!video.isOpened()) { cout<<"video open error"<<endl; return 0 ; } Mat pri; Mat aft; Mat binary; Mat frame1,frame2; while (1) { video.read(frame1); video.read(frame2); // Mat cropFrame1, cropFrame2; // Mat oriConv = frame1(Rect(10,340,700,200)); // //// cropFrame1 = frame1(Rect(10,340,700,200)); //// cropFrame2 = frame2(Rect(10,340,700,200)); // // Mat grayImage1,grayImage2; // Mat differenceImage; // Mat thresholdImage; // Vec<double,4> totalDiff = 0.0; // // cropFrame1 = frame1(Rect(10,340,700,200)); // cvtColor(cropFrame1, grayImage1, COLOR_BGR2GRAY); // // cropFrame2 =frame2(Rect(10,340,700,200)); // // cvtColor(cropFrame2, grayImage2, COLOR_BGR2GRAY); // absdiff(grayImage1,grayImage2,differenceImage); // // totalDiff = sum(differenceImage) / (690 * 140); // cout << "sum diff: " <<totalDiff<<endl; // // if(totalDiff[0] > 14.0) // continue; // // threshold(differenceImage, thresholdImage, SENSITIVITY_VALUE, 255, THRESH_BINARY); // // blur(thresholdImage, thresholdImage , Size(BLUR_SIZE,BLUR_SIZE)); // // threshold(thresholdImage,thresholdImage,SENSITIVITY_VALUE,255,THRESH_BINARY); // // // //if tracking enabled, search for contours in our thresholded image // // //searchForMovement(thresholdImage, oriConv); // // // //show our captured frame // imshow("moving",thresholdImage); // imshow("ori",temp); Mat cropRGB = frame2(Rect(10,340,700,200)); Mat cropG; cvtColor(cropRGB, cropG, CV_RGB2GRAY); GaussianBlur(cropG, cropG, Size(5,5), 0,0); threshold(cropG,binary,0,255,THRESH_OTSU|THRESH_BINARY); // adaptiveThreshold(cropG, binary, 255, <#int adaptiveMethod#>, THRESH_OTSU|THRESH_BINARY, 3, 0.); // bitwise_xor(thresholdImage,binary,binary); imshow("bin",binary); Mat fg; erode(binary, fg, Mat(), Point(-1, -1), 6); namedWindow("Foreground Image"); imshow("Foreground Image", fg); Mat bg; dilate(binary,bg,Mat(),Point(-1,-1),6); threshold(bg,bg,1,128,THRESH_BINARY_INV); namedWindow("Background Image"); imshow("Background Image",bg); // Mat dist; // distanceTransform(binary, dist, CV_DIST_L2, 5); // normalize(dist, dist, 0, 1., NORM_MINMAX); // imshow("dist",dist); // // threshold(dist, dist, .4, 1., CV_THRESH_BINARY); // // Dilate a bit the dist image // Mat kernel1 = Mat::ones(3, 3, CV_8UC1); // dilate(dist, dist, kernel1); // imshow("Peaks", dist); Mat markers(binary.size(),CV_8U,Scalar(0)); markers= fg+bg; namedWindow("Markers"); imshow("Markers",markers); WatershedSegmenter segmenter; segmenter.setMarkers(markers); segmenter.process(cropRGB); namedWindow("Segmentation"); imshow("Segmentation",segmenter.getSegmentation()); // segmenter.getSegmentation() // namedWindow("Watersheds"); // 워터쉐드 띄워 보기 // imshow("Watersheds",segmenter.getWatersheds()); //111 Mat kernel = Mat::ones(3,3,CV_8U); // // Mat morpho; // morphologyEx(binary,morpho,MORPH_OPEN,kernel); // // imshow("open",morpho); // // Mat sure_bg; // dilate(morpho,sure_bg,kernel); // // imshow("dilate",sure_bg); // // Mat dist; // distanceTransform(binary, dist, CV_DIST_L2, 5); // // Normalize the distance image for range = {0.0, 1.0} // // so we can visualize and threshold it // normalize(dist, dist, 0, 1., NORM_MINMAX); // imshow("Distance Transform Image", dist); // // Threshold to obtain the peaks // // This will be the markers for the foreground objects // threshold(dist, dist, .4, 1., CV_THRESH_BINARY); // // Dilate a bit the dist image // Mat kernel1 = Mat::ones(3, 3, CV_8UC1); // dilate(dist, dist, kernel1); // imshow("Peaks", dist); // // Create the CV_8U version of the distance image // // It is needed for findContours() // Mat dist_8u; // dist.convertTo(dist_8u, CV_8U); // // Find total markers // vector<vector<Point> > contours; // findContours(dist_8u, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // // Create the marker image for the watershed algorithm // Mat markers = Mat::zeros(dist.size(), CV_32SC1); // // Draw the foreground markers // for (size_t i = 0; i < contours.size(); i++) // drawContours(markers, contours, static_cast<int>(i), Scalar::all(static_cast<int>(i)+1), -1); // // Draw the background marker // circle(markers, Point(5,5), 3, CV_RGB(255,255,255), -1); // imshow("Markers", markers*10000); // // Perform the watershed algorithm // watershed(cropRGB, markers); //// Mat mark = Mat::zeros(markers.size(), CV_8UC1); //// markers.convertTo(mark, CV_8UC1); //// bitwise_not(mark, mark); //// imshow("Markers_v2", mark); // uncomment this if you want to see how the mark // // image looks like at that point // // Generate random colors // vector<Vec3b> colors; // for (size_t i = 0; i < contours.size(); i++) // { // int b = theRNG().uniform(0, 255); // int g = theRNG().uniform(0, 255); // int r = theRNG().uniform(0, 255); // colors.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r)); // } // // Create the result image // Mat dst = Mat::zeros(markers.size(), CV_8UC3); // // Fill labeled objects with random colors // for (int i = 0; i < markers.rows; i++) // { // for (int j = 0; j < markers.cols; j++) // { // int index = markers.at<int>(i,j); // if (index > 0 && index <= static_cast<int>(contours.size())) // dst.at<Vec3b>(i,j) = colors[index-1]; // else // dst.at<Vec3b>(i,j) = Vec3b(0,0,0); // } // } // // Visualize the final image // imshow("Final Result", dst); // // // 111 1 cvWaitKey(10); } return 0; }
RideFile *SrmFileReader::openRideFile(QFile &file, QStringList &errorStrings) const { if (!file.open(QFile::ReadOnly)) { errorStrings << QString("can't open file %1").arg(file.fileName()); return NULL; } QDataStream in(&file); RideFile *result = new RideFile; result->setDeviceType("SRM"); char magic[4]; in.readRawData(magic, sizeof(magic)); assert(strncmp(magic, "SRM", 3) == 0); int version = magic[3] - '0'; assert(version == 5 || version == 6 || version == 7); quint16 dayssince1880 = readShort(in); quint16 wheelcirc = readShort(in); quint8 recint1 = readByte(in); quint8 recint2 = readByte(in); quint16 blockcnt = readShort(in); quint16 markercnt = readShort(in); readByte(in); // padding quint8 commentlen = readByte(in); char comment[71]; in.readRawData(comment, sizeof(comment) - 1); comment[commentlen - 1] = '\0'; result->setRecIntSecs(((double) recint1) / recint2); unsigned recintms = (unsigned) round(result->recIntSecs() * 1000.0); QDate date(1880, 1, 1); date = date.addDays(dayssince1880); QVector<marker> markers(markercnt + 1); for (int i = 0; i <= markercnt; ++i) { char mcomment[256]; size_t mcommentlen = version < 6 ? 3 : 255; assert( mcommentlen < sizeof(mcomment) ); in.readRawData(mcomment, mcommentlen ); mcomment[mcommentlen] = '\0'; quint8 active = readByte(in); quint16 start = readShort(in); quint16 end = readShort(in); quint16 avgwatts = readShort(in); quint16 avghr = readShort(in); quint16 avgcad = readShort(in); quint16 avgspeed = readShort(in); quint16 pwc150 = readShort(in); // data fixup: Although the data chunk index in srm files starts // with 1, some srmwin wrote files referencing index 0. if( end < 1 ) end = 1; if( start < 1 ) start = 1; // data fixup: some srmwin versions wrote markers with start > end if( end < start ){ markers[i].start = end; markers[i].end = start; } else { markers[i].start = start; markers[i].end = end; } (void) active; (void) avgwatts; (void) avghr; (void) avgcad; (void) avgspeed; (void) pwc150; (void) wheelcirc; } blockhdr *blockhdrs = new blockhdr[blockcnt+1]; for (int i = 0; i < blockcnt; ++i) { // In the .srm files generated by Rainer Clasen's srmcmd, // hsecsincemidn is a *signed* 32-bit integer. I haven't seen a // negative value in any .srm files generated by srmwin.exe, but // since the number of hundredths of a second in a day is << 2^31, // it seems safe to always treat this number as signed. qint32 hsecsincemidn = readLong(in); blockhdrs[i].chunkcnt = readShort(in); blockhdrs[i].dt = QDateTime(date); blockhdrs[i].dt = blockhdrs[i].dt.addMSecs(hsecsincemidn * 10); } quint16 zero = readShort(in); quint16 slope = readShort(in); quint16 datacnt = readShort(in); readByte(in); // padding (void) zero; (void) slope; // SRM5 files have no blocks - synthesize one if( blockcnt < 1 ){ blockcnt = 0; blockhdrs[0].chunkcnt = datacnt; blockhdrs[0].dt = QDateTime(date); } int blknum = 0, blkidx = 0, mrknum = 0, interval = 0; double km = 0.0, secs = 0.0; if (markercnt > 0) mrknum = 1; for (int i = 0; i < datacnt; ++i) { int cad, hr, watts; double kph, alt; if (version < 7) { quint8 ps[3]; in.readRawData((char*) ps, sizeof(ps)); cad = readByte(in); hr = readByte(in); kph = (((((unsigned) ps[1]) & 0xf0) << 3) | (ps[0] & 0x7f)) * 3.0 / 26.0; watts = (ps[1] & 0x0f) | (ps[2] << 0x4); alt = 0.0; } else { assert(version == 7); watts = readShort(in); cad = readByte(in); hr = readByte(in); kph = readLong(in) * 3.6 / 1000.0; alt = readLong(in); double temp = 0.1 * (qint16) readShort(in); (void) temp; // unused for now } if (i == 0) { result->setStartTime(blockhdrs[blknum].dt); } if (mrknum < markers.size() && i == markers[mrknum].end) { ++interval; ++mrknum; } // markers count from 1 if ((i > 0) && (mrknum < markers.size()) && (i == markers[mrknum].start - 1)) ++interval; km += result->recIntSecs() * kph / 3600.0; double nm = watts / 2.0 / PI / cad * 60.0; result->appendPoint(secs, cad, hr, km, kph, nm, watts, alt, 0.0, 0.0, 0.0, interval); ++blkidx; if ((blkidx == blockhdrs[blknum].chunkcnt) && (blknum + 1 < blockcnt)) { QDateTime end = blockhdrs[blknum].dt.addMSecs( recintms * blockhdrs[blknum].chunkcnt); ++blknum; blkidx = 0; QDateTime start = blockhdrs[blknum].dt; qint64 endms = ((qint64) end.toTime_t()) * 1000 + end.time().msec(); qint64 startms = ((qint64) start.toTime_t()) * 1000 + start.time().msec(); double diff_secs = (startms - endms) / 1000.0; if (diff_secs < result->recIntSecs()) { errorStrings << QString("ERROR: time goes backwards by %1 s" " on trans " "to block %2" ).arg(diff_secs).arg(blknum); secs += result->recIntSecs(); // for lack of a better option } else { secs += diff_secs; } } else { secs += result->recIntSecs(); } } double last = 0.0; for (int i = 1; i < markers.size(); ++i) { const marker &marker = markers[i]; int start = marker.start - 1; double start_secs = result->dataPoints()[start]->secs; int end = qMin(marker.end - 1, result->dataPoints().size() - 1); double end_secs = result->dataPoints()[end]->secs + result->recIntSecs(); result->addInterval(last, start_secs, ""); result->addInterval(start_secs, end_secs, QString("%1").arg(i)); last = end_secs; } if (!markers.empty() && markers.last().end < result->dataPoints().size()) { double start_secs = result->dataPoints().last()->secs + result->recIntSecs(); result->addInterval(last, start_secs, ""); } file.close(); return result; }
int main() { sf::Texture texture, backgroundTexture; if (!texture.loadFromFile("resources/uv map.jpg") || !backgroundTexture.loadFromFile("resources/BlueYellowGradient.png")) { std::cerr << "Unable to load textures." << std::endl; return EXIT_FAILURE; } sf::RenderWindow window(sf::VideoMode(800, 600), "Progress Bar example"); sw::ProgressBar progressBar({ 300.f, 40.f }); // set origin and position progressBar.setOrigin(progressBar.getSize() / 2.f); progressBar.setPosition(sf::Vector2f(window.getSize() / 2u)); // customise visual representation progressBar.setShowBackgroundAndFrame(true); progressBar.setBackgroundColor(sf::Color(128, 128, 128)); progressBar.setFrameColor(sf::Color(128, 128, 255, 192)); progressBar.setFrameThickness(2.f); progressBar.setRotation(-30); // set textures progressBar.setTexture(texture); progressBar.setTextureRect({ sf::Vector2i(0, texture.getSize().y / 10), sf::Vector2i(texture.getSize().x, texture.getSize().y / 10 + 1) }); progressBar.setBackgroundTexture(backgroundTexture); progressBar.setBackgroundTextureRect({ { 0, 0 }, { 1, static_cast<int>(backgroundTexture.getSize().y) } }); // set current progression progressBar.setFromValueInRange(9u, 0u, 10u); // marker std::vector<sf::CircleShape> markers(3, sf::CircleShape(3.f)); for (auto& marker : markers) marker.setOrigin(marker.getRadius(), marker.getRadius()); markers[0].setFillColor(sf::Color::Red); markers[1].setFillColor(sf::Color::Yellow); markers[2].setFillColor(sf::Color::Green); sf::Clock clock; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if ((event.type == sf::Event::Closed) || (event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)) window.close(); } markers[0].setPosition(progressBar.getAnchorProgressTop()); markers[1].setPosition(progressBar.getAnchorProgressCenter()); markers[2].setPosition(progressBar.getAnchorProgressBottom()); float frameTime{ clock.restart().asSeconds() }; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Add)) // [+] (number pad) increase progress progressBar.setRatio(progressBar.getRatio() + frameTime * 0.3f); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Subtract)) // [-] (number pad) decrease progress progressBar.setRatio(progressBar.getRatio() - frameTime * 0.3f); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Period)) // [.]/[>] rotate left progressBar.rotate(frameTime * 30.f); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Comma)) // [,]/[<] rotate right progressBar.rotate(-frameTime * 30.f); window.clear(); window.draw(progressBar); for (auto& marker : markers) window.draw(marker); window.display(); } return EXIT_SUCCESS; }
void grab_cut_mask(const cv::Mat &frame, cv::Mat &result, cv::Rect rect=cv::Rect() ) { /** @NOTE: unused in the program Edip. **/ /** Grab and cut function which should extract the outter contours, * using cv::findContours() function and the cv::drawContours() function which output is used to * build the mask of outter contours. * **************************************************************************************************/ cv::Mat img_gray ; cv::Mat src_gray ; cv::cvtColor(frame, src_gray, cv::COLOR_BGR2GRAY); cv::cvtColor(src_gray, img_gray, cv::COLOR_GRAY2BGR); cv::Mat canny_output; int thresh = 255/2 ; cv::Canny(src_gray, canny_output, 100, 200, 3 ); int i, j, compCount = 0 ; vector<vector<cv::Point>> contours ; vector<cv::Vec4i> hierarchy ; cv::findContours(canny_output, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE); if ( contours.empty() ) { fprintf(stderr,"contours empty !!!\n") ; return ; } cv::Mat markers(frame.size(), CV_32S); markers = cv::Scalar::all(0); int idx = 0; for( ; idx >= 0; idx = hierarchy[idx][0], compCount++ ) cv::drawContours(markers, contours, idx, cv::Scalar::all(compCount+1), CV_FILLED, 8, hierarchy, INT_MAX); if ( markers.empty() ) { fprintf(stderr,"markers empty !!!\n") ; return ; } cv::Mat mask(markers.size(), CV_8UC1) ; cv::Mat wshed(markers.size(), CV_8UC3); // paint the watershed image for( i = 0; i < markers.rows; i++ ) for( j = 0; j < markers.cols; j++ ) { int index = markers.at<int>(i,j); if( index == -1 ) { wshed.at<cv::Vec3b>(i,j) = cv::Vec3b(0,0,0) ; mask.at<uchar>(i,j) = cv::GC_PR_BGD ; } else if( index <= 0 || index > compCount ) { wshed.at<cv::Vec3b>(i,j) = cv::Vec3b(255, 255, 255); mask.at<uchar>(i,j) = cv::GC_PR_BGD ; } else { wshed.at<cv::Vec3b>(i,j) = cv::Vec3b(255, 0, 0) ; mask.at<uchar>(i,j) = cv::GC_PR_FGD ; } } wshed = wshed*0.5 + img_gray * 0.5 ; cv::Mat grab_cut_res_mask = mask ; cv::Mat fg_model ; cv::Mat bg_model ; cv::grabCut(frame, grab_cut_res_mask, rect, bg_model, fg_model, 5, cv::GC_INIT_WITH_MASK | cv::GC_EVAL) ; cv::Mat res(frame.size(), CV_8UC3 ) ; cv::compare(grab_cut_res_mask, cv::GC_PR_FGD, grab_cut_res_mask, cv::CMP_EQ) ; result.copyTo(res, grab_cut_res_mask) ; result=res ; return ; }