void MGuiEditText::upCharId(int direction) { MVector2 pos = getFont()->getCharacterPosition(getText(), getPosition(), getTextSize(), getCharId()); pos.x += 0.1f; pos.y += 0.1f; pos += MVector2(0, getTextSize() * direction); if(pos.y < getPosition().y) return; if(pos.y > (getPosition().y + getScale().y)) return; unsigned int id = getFont()->findPointedCharacter(getText(), getPosition(), getTextSize(), pos); setCharId(id); }
void TextWidget::recalculateText() { // perform text initialization. loadTextFont(); myText.setColor(isEnabled() ? getTextColor() : fadeColor(getTextColor(), 0.6f)); sf::FloatRect boundingBox = getTextMaxBoundingBox(); sf::Vector2f pos(boundingBox.left, boundingBox.top); myText.setMaxSize(sf::Vector2f(boundingBox.width, boundingBox.height)); sf::Vector2f textSize(getTextSize()); pos.x += (boundingBox.width - textSize.x) * getTextPreciseAlignment().x; pos.y += (boundingBox.height - textSize.y) * getTextPreciseAlignment().y; /* switch (convertAlignmentHorizontal(getTextAlignment())) { case AlignLeft: default: break; case AlignCenter: pos.x += (boundingBox.width - textSize.x) / 2.f; break; case AlignRight: pos.x += boundingBox.width - textSize.x; break; } switch (convertAlignmentVertical(getTextAlignment())) { case AlignTop: default: break; case AlignCenter: pos.y += (boundingBox.height - textSize.y) / 2.f; break; case AlignBottom: pos.y += boundingBox.height - textSize.y; break; } */ if (isTextPixelPerfect()) pos = sf::Vector2f(sf::Vector2i(pos + sf::Vector2f(0.5f, 0.5f))); if (pos != myText.getPosition()) { myText.setPosition(pos); myText.updateMinor(); } }
long Numkey::getNum(){ char size = getTextSize(); long result = 0; for(int i = 0; i<size; i++){ if(text[i] == '.') break; // Only process integer side result = result * 10 + text[i]-'0'; } return result; }
//============================================================================== void draw_string(Mat img, //image to draw on const string text) //text to draw { Size size = getTextSize(text,FONT_HERSHEY_COMPLEX,0.6f,1,NULL); putText(img,text,Point(0,size.height),FONT_HERSHEY_COMPLEX,0.6f, Scalar::all(0),1,CV_AA); putText(img,text,Point(1,size.height+1),FONT_HERSHEY_COMPLEX,0.6f, Scalar::all(255),1,CV_AA); }
Size getTextSize(HWND hwnd, HFONT font, const char* text, int width) { HDC hdc = GetDC(hwnd); if (font) font = (HFONT)SelectObject(hdc , font); Size sz = getTextSize(hdc, text, width); if (font) SelectObject(hdc , font); ReleaseDC(hwnd, hdc); return sz; }
void Numkey::clear(){ byte textSize = getTextSize(); if(textSize){ for(int i = textSize-1; i >= 0; i--) { text[i] = 0; } } update(); }
void draw_string(Mat img, const string text, const int level) { Size size = getTextSize(text,FONT_HERSHEY_COMPLEX,0.6f,1,NULL); putText(img,text,Point(0,level*size.height),FONT_HERSHEY_COMPLEX,0.6f, Scalar::all(0),1,CV_AA); putText(img,text,Point(1,level*size.height+1),FONT_HERSHEY_COMPLEX,0.6f, Scalar::all(255),1,CV_AA); }
void WindowCaption::align() { MyGUI::IntSize textSize = getTextSize(); MyGUI::Widget* caption = mClient; caption->setSize(textSize.width + 24, caption->getHeight()); int barwidth = (getWidth()-caption->getWidth())/2; caption->setPosition(barwidth, caption->getTop()); if (mLeft) mLeft->setCoord(0, mLeft->getTop(), barwidth, mLeft->getHeight()); if (mRight) mRight->setCoord(barwidth + caption->getWidth(), mRight->getTop(), barwidth, mRight->getHeight()); }
Mat oneStr2oneImg (const string& text, int fontFace, int thickness, Scalar color) { double fontScale = 1; int baseline = 0; Size textSize = getTextSize(text, fontFace,fontScale, thickness, &baseline); // scale to fit Height = 1000; fontScale *= 1000 / textSize.height; baseline += thickness; textSize = getTextSize(text, fontFace,fontScale, thickness, &baseline); Mat img1(textSize.height*1.1, textSize.width*1.2, CV_8UC3, Scalar(0,0,0)); // center the text Point textOrg((img1.cols - textSize.width)/2,(img1.rows + textSize.height)/2); Mat img(textSize.height*1.5, textSize.width*1.2, CV_8UC3, Scalar(0,0,0)); // then put the text itself putText(img, text, textOrg, fontFace, fontScale,color, thickness, 8); /* namedWindow( "gg window", WINDOW_AUTOSIZE ); imshow( "gg window", img ); waitKey(0); */ return img; }
void Numkey::deleteChar(){ byte textSize = getTextSize(); //Serial.print("Size is ");Serial.println(textSize); if(textSize){ for(int i = textSize-1; i >= 0; i--) { if(text[i] != 0){ text[i] = 0; break; } } } update(); }
/** * Helper function to display text in the center of a contour */ void setLabel(Mat& im, const string label, vector<Point>& contour) { int fontface = FONT_HERSHEY_SIMPLEX; double scale = 0.4; int thickness = 1; int baseline = 0; Size text = getTextSize(label, fontface, scale, thickness, &baseline); Rect r = boundingRect(contour); Point pt(r.x + ((r.width - text.width) / 2), r.y + ((r.height + text.height) / 2)); rectangle(im, pt + cv::Point(0, baseline), pt + cv::Point(text.width, -text.height), CV_RGB(255,255,255), CV_FILLED); putText(im, label, pt, fontface, scale, CV_RGB(0,0,0), thickness, 8); }
bool Checkbox::getProperty(std::string property, std::string& value) const { property = toLower(property); if (property == "width") value = to_string(m_TextureUnchecked.sprite.getGlobalBounds().width); else if (property == "height") value = to_string(m_TextureUnchecked.sprite.getGlobalBounds().height); else if (property == "configfile") value = getLoadedConfigFile(); else if (property == "checked") value = m_Checked ? "true" : "false"; else if (property == "text") value = getText().toAnsiString(); else if (property == "textcolor") value = "(" + to_string(int(getTextColor().r)) + "," + to_string(int(getTextColor().g)) + "," + to_string(int(getTextColor().b)) + "," + to_string(int(getTextColor().a)) + ")"; else if (property == "textsize") value = to_string(getTextSize()); else if (property == "allowtextclick") value = m_AllowTextClick ? "true" : "false"; else if (property == "callback") { std::string tempValue; ClickableWidget::getProperty(property, tempValue); std::vector<sf::String> callbacks; if ((m_CallbackFunctions.find(Checked) != m_CallbackFunctions.end()) && (m_CallbackFunctions.at(Checked).size() == 1) && (m_CallbackFunctions.at(Checked).front() == nullptr)) callbacks.push_back("Checked"); if ((m_CallbackFunctions.find(Unchecked) != m_CallbackFunctions.end()) && (m_CallbackFunctions.at(Unchecked).size() == 1) && (m_CallbackFunctions.at(Unchecked).front() == nullptr)) callbacks.push_back("Unchecked"); if ((m_CallbackFunctions.find(SpaceKeyPressed) != m_CallbackFunctions.end()) && (m_CallbackFunctions.at(SpaceKeyPressed).size() == 1) && (m_CallbackFunctions.at(SpaceKeyPressed).front() == nullptr)) callbacks.push_back("SpaceKeyPressed"); if ((m_CallbackFunctions.find(ReturnKeyPressed) != m_CallbackFunctions.end()) && (m_CallbackFunctions.at(ReturnKeyPressed).size() == 1) && (m_CallbackFunctions.at(ReturnKeyPressed).front() == nullptr)) callbacks.push_back("ReturnKeyPressed"); encodeList(callbacks, value); if (value.empty()) value = tempValue; else if (!tempValue.empty()) value += "," + tempValue; } else return ClickableWidget::getProperty(property, value); // You pass here when one of the properties matched return true; }
void MGui2d::autoScaleFromText(void) { if(! isDrawingText()) return; const char * text = getText(); if(! text) return; setScale( getFont()->getMaxSize( getText(), getTextSize() ) ); }
void ListItem::onPreferredSize(PreferredSizeEvent& ev) { int w = 0, h = 0; Size maxSize; if (hasText()) maxSize = getTextSize(); else maxSize.w = maxSize.h = 0; UI_FOREACH_WIDGET(getChildren(), it) { Size reqSize = (*it)->getPreferredSize(); maxSize.w = MAX(maxSize.w, reqSize.w); maxSize.h = MAX(maxSize.h, reqSize.h); }
void draw_boxes(cv::Mat mat_img, std::vector<bbox_t> result_vec, std::vector<std::string> obj_names, unsigned int wait_msec = 0) { for (auto &i : result_vec) { cv::Scalar color(60, 160, 260); cv::rectangle(mat_img, cv::Rect(i.x, i.y, i.w, i.h), color, 5); if (obj_names.size() > i.obj_id) { std::string obj_name = obj_names[i.obj_id]; if (i.track_id > 0) obj_name += " - " + std::to_string(i.track_id); cv::Size const text_size = getTextSize(obj_name, cv::FONT_HERSHEY_COMPLEX_SMALL, 1.2, 2, 0); int const max_width = (text_size.width > i.w + 2) ? text_size.width : (i.w + 2); cv::rectangle(mat_img, cv::Point2f(std::max((int)i.x - 3, 0), std::max((int)i.y - 30, 0)), cv::Point2f(std::min((int)i.x + max_width, mat_img.cols-1), std::min((int)i.y, mat_img.rows-1)), color, CV_FILLED, 8, 0); putText(mat_img, obj_name, cv::Point2f(i.x, i.y - 10), cv::FONT_HERSHEY_COMPLEX_SMALL, 1.2, cv::Scalar(0, 0, 0), 2); } } cv::imshow("window name", mat_img); cv::waitKey(wait_msec); }
static void drawNode(Node p, int x, int y) { int textSize = getTextSize(p); print("<rect style=\"stroke: black; fill: white;\" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" rx=\"%d\" ry=\"%d\" ", x + X_OFFSET - X_SCALE/4 - CHAR_SIZE * textSize, y, 2 * CHAR_SIZE * textSize + X_SCALE/2, Y_SPACING, X_SCALE/4, X_SCALE/4); print("/>\n"); print("<text "); print("style=\"font-size:%d;font-style:normal;font-weight:normal;text-anchor:start;fill:#000000;font-family:sans\" ", FONT_SIZE); print("x=\"%d\" ", (x + X_OFFSET - CHAR_SIZE * textSize)); print("y=\"%d\" ", (y + Y_OFFSET + CHAR)); print("id=\"id%d\">", next_id++); print(getNodeText(p)); print(" [%s]" , type_name(p->x.exact_type)); print_type_set(p->x.type_set); if (p->x.ptype) print(" %t ", p->x.ptype); if (p->x.eliminated) print(" ELIMINATED "); print("</text>\n"); }
void UIWidget::updateText() { if(m_textWrap && m_rect.isValid()) m_drawText = m_font->wrapText(m_text, getWidth() - m_textOffset.x); else m_drawText = m_text; // update rect size if(!m_rect.isValid() || m_textAutoResize) { Size textBoxSize = getTextSize(); textBoxSize += Size(m_padding.left + m_padding.right, m_padding.top + m_padding.bottom); Size size = getSize(); if(size.width() <= 0 || (m_textAutoResize && !m_textWrap)) size.setWidth(textBoxSize.width()); if(size.height() <= 0 || m_textAutoResize) size.setHeight(textBoxSize.height()); setSize(size); } m_textMustRecache = true; }
//----------------------------------------------------------------------------- // Purpose: Label paint functions - take into account current highligh status //----------------------------------------------------------------------------- void CLabelHeader::paint() { Color oldFg; getFgColor(oldFg); if (gViewPort->GetScoreBoard()->m_iHighlightRow == _row) { setFgColor(255, 255, 255, 0); } // draw text int x, y, iwide, itall; getTextSize(iwide, itall); calcAlignment(iwide, itall, x, y); _dualImage->setPos(x, y); int x1, y1; _dualImage->GetImage(1)->getPos(x1, y1); _dualImage->GetImage(1)->setPos(_gap, y1); _dualImage->doPaint(this); // get size of the panel and the image if (_image) { Color imgColor; getFgColor( imgColor ); if( _useFgColorAsImageColor ) { _image->setColor( imgColor ); } _image->getSize(iwide, itall); calcAlignment(iwide, itall, x, y); _image->setPos(x, y); _image->doPaint(this); } setFgColor(oldFg[0], oldFg[1], oldFg[2], oldFg[3]); }
bool Input::keyDown(int key, int mask, WindowManager*) { osgText::String& s = _text->getText(); if(key == osgGA::GUIEventAdapter::KEY_BackSpace) { if(_index >= 1) { // s.erase(s.begin() + (_index - 1)); s[_index - 1] = ' '; _text->update(); _calculateCursorOffsets(); _index--; } } else { if(key > 255 || _index >= _maxSize) return false; // else if(_index < s.size()) s.insert(s.begin() + _index, key); // else if(_index == s.size()) s.push_back(key); s[_index] = key; _text->update(); _calculateCursorOffsets(); _index++; } // _text->update(); _calculateSize(getTextSize()); getParent()->resize(); return false; }
bool Label::getProperty(std::string property, std::string& value) const { property = toLower(property); if (property == "configfile") value = getLoadedConfigFile(); else if (property == "text") encodeString(getText(), value); else if (property == "textcolor") value = "(" + to_string(int(getTextColor().r)) + "," + to_string(int(getTextColor().g)) + "," + to_string(int(getTextColor().b)) + "," + to_string(int(getTextColor().a)) + ")"; else if (property == "textsize") value = to_string(getTextSize()); else if (property == "backgroundcolor") value = "(" + to_string(int(getBackgroundColor().r)) + "," + to_string(int(getBackgroundColor().g)) + "," + to_string(int(getBackgroundColor().b)) + "," + to_string(int(getBackgroundColor().a)) + ")"; else if (property == "autosize") value = m_AutoSize ? "true" : "false"; else // The property didn't match return ClickableWidget::getProperty(property, value); // You pass here when one of the properties matched return true; }
// 重写设置文本,计算大小。 void HLabel::setText(CString txt) { HCtrl::setText( txt ); if( !m_bAutoSize ) return; CRect rc; if( getTextSize( rc ) ) { if( m_bShadow ) // 如果有阴影,周围加大一个象素 rc.DeflateRect( -1, -1 ); //invalidate(); // 重画修改前的区域 //HCtrl::setText( txt )中有了 m_rcClient.right = m_rcClient.left + rc.Width(); // 用户区,相对于父控件坐标 m_rcClient.bottom = m_rcClient.top + rc.Height(); m_rcWnd.right = m_rcWnd.left + rc.Width(); // 窗口区,相对于窗口坐标 m_rcWnd.bottom = m_rcWnd.top + rc.Height(); invalidate(); // 重画修后的区域 } }
QSize PreviewContentWidget::getTextBubbleSize() const { auto bubbleSize = getTextSize(); const auto textHeight = bubbleSize.height(); bubbleSize.setHeight( std::max( Ui::MessageStyle::getBubbleHeight(), textHeight ) ); bubbleSize.setHeight( Utils::applyMultilineTextFix(textHeight, bubbleSize.height()) ); bubbleSize.rwidth() += Ui::MessageStyle::getBubbleHorPadding(); bubbleSize.rwidth() += Ui::MessageStyle::getBubbleHorPadding(); bubbleSize.rwidth() += Ui::MessageStatusWidget::getMaxWidth(); bubbleSize.rheight() += getBubbleVertPadding(); return bubbleSize; }
void MGuiEditText::draw(void) { MRenderingContext * render = MGui::getInstance()->getRenderingContext(); if(! isVisible()) return; if(! isPressed()) updateFromVariable(); // draw selection if(isPressed()) { render->disableTexture(); render->setColor4(MVector4(1, 0.1f, 0.1f, 0.3f)); getFont()->drawSelection(getText(), getPosition(), getTextSize(), m_startSelectionId, m_endSelectionId); } // set text color if(isPressed()){ render->setColor4(getPressedColor()); } else if(isHighLight()){ render->setColor4(getHighLightColor()); } else{ render->setColor4(getNormalColor()); } // draw text render->enableTexture(); getFont()->draw(getText(), getPosition(), getTextSize()); if(isPressed() && (m_startSelectionId == m_endSelectionId)) // cursor { render->disableTexture(); render->setColor4(MVector4(1, 0, 0, 0.5f)); // position MVector2 position = getFont()->getCharacterPosition( getText(), getPosition(), getTextSize(), getCharId() ); // scale MVector2 scale = MVector2(getTextSize() * 0.1f, getTextSize()); float offset = (getTextSize() - (getTextSize()*getFont()->getSpace()))*0.5f; float px = (float)((int)(position.x + offset)); float py = (float)((int)position.y); // draw render->disableNormalArray(); render->disableTexCoordArray(); render->disableColorArray(); render->enableVertexArray(); MVector2 vertices[4] = { MVector2(px, py), MVector2(px, py + scale.y), MVector2(px + scale.x, py), MVector2(px + scale.x, py + scale.y) }; render->setVertexPointer(M_FLOAT, 2, vertices); render->drawArray(M_PRIMITIVE_TRIANGLE_STRIP, 0, 4); } MGuiEvent guiEvent; guiEvent.type = MGUI_EVENT_DRAW; if(m_pointerEvent) m_pointerEvent(this, &guiEvent); }
inline int GameState::adjustedAlignment(const std::string& text, int x) const { return x - getTextSize(text); }
void SymbolLayer::setTextSize(PropertyValue<float> value) { if (value == getTextSize()) return; impl->layout.textSize.set(value); impl->observer->onLayerLayoutPropertyChanged(*this, "text-size"); }
void CameraCalibration::calibrate() { const string inputSettingsFile = "default.xml"; // Read the settings FileStorage fs( inputSettingsFile, FileStorage::READ ); if ( !fs.isOpened() ) { FileStorage fs( inputSettingsFile, FileStorage::WRITE ); fs.release(); cerr << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << endl; return; } else { s.read( fs["Settings"] ); // close Settings file fs.release(); } if ( !s.goodInput ) { cerr << "Invalid input detected. Application stopping." << endl; return; } vector<vector<Point2f> > imagePoints; Mat distCoeffs; Size imageSize; int mode = s.inputType == Settings::IMAGE_LIST ? CAPTURING : DETECTION; clock_t prevTimestamp = 0; const Scalar RED( 0, 0, 255 ), GREEN( 0, 255, 0 ); const char ESC_KEY = 27; for ( int i = 0; ; ++i ) { Mat view; bool blinkOutput = false; view = s.nextImage(); //----- If no more image, or got enough, then stop calibration and show result ------------- if ( mode == CAPTURING && imagePoints.size() >= (unsigned)s.nrFrames ) { if ( runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints ) ) { mode = CALIBRATED; } else { mode = DETECTION; } } // If no more images then run calibration, save and stop loop. if ( view.empty() ) { if ( imagePoints.size() > 0 ) { runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints); } break; } imageSize = view.size(); // Format input image. if ( s.flipVertical ) { flip( view, view, 0 ); } vector<Point2f> pointBuf; bool found; // Find feature points on the input format switch ( s.calibrationPattern ) { case Settings::CHESSBOARD: found = findChessboardCorners( view, s.boardSize, pointBuf, CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_FAST_CHECK | CALIB_CB_NORMALIZE_IMAGE); break; case Settings::CIRCLES_GRID: found = findCirclesGrid( view, s.boardSize, pointBuf ); break; case Settings::ASYMMETRIC_CIRCLES_GRID: found = findCirclesGrid( view, s.boardSize, pointBuf, CALIB_CB_ASYMMETRIC_GRID ); break; default: found = false; break; } // If done with success, improve the found corners' coordinate accuracy for chessboard if ( found ) { if ( s.calibrationPattern == Settings::CHESSBOARD ) { Mat viewGray; cvtColor( view, viewGray, COLOR_BGR2GRAY ); cornerSubPix( viewGray, pointBuf, Size( 11,11 ), Size(-1,-1), TermCriteria( TermCriteria::EPS + TermCriteria::MAX_ITER, 30, 0.1 ) ); } // For camera only take new samples after delay time if ( mode == CAPTURING && (!s.inputCapture.isOpened() || clock() - prevTimestamp > s.delay*1e-3*CLOCKS_PER_SEC) ) { imagePoints.push_back( pointBuf ); prevTimestamp = clock(); blinkOutput = s.inputCapture.isOpened(); } // Draw the corners. drawChessboardCorners( view, s.boardSize, Mat( pointBuf ), found ); } //----------------------------- Output Text ------------------------------------------------ string msg = ( mode == CAPTURING ) ? "100/100" : mode == CALIBRATED ? "Calibrated" : "Press 'g' to start"; int baseLine = 0; Size textSize = getTextSize( msg, 1, 1, 1, &baseLine ); Point textOrigin( view.cols - 2*textSize.width - 10, view.rows - 2*baseLine - 10 ); if ( mode == CAPTURING ) { if ( s.showUndistorsed ) { msg = format( "%d/%d Undist", (int)imagePoints.size(), s.nrFrames ); } else { msg = format( "%d/%d", (int)imagePoints.size(), s.nrFrames ); } } putText( view, msg, textOrigin, 1, 1, mode == CALIBRATED ? GREEN : RED ); if ( blinkOutput ) { bitwise_not( view, view ); } //------------------------- Video capture output undistorted ------------------------------ if ( mode == CALIBRATED && s.showUndistorsed ) { Mat temp = view.clone(); undistort( temp, view, cameraMatrix, distCoeffs ); } //------------------------------ Show image and check for input commands ------------------- imshow( "Image View", view ); char key = (char)waitKey( s.inputCapture.isOpened() ? 50 : s.delay ); if ( key == ESC_KEY ) { break; } if ( key == 'u' && mode == CALIBRATED ) { s.showUndistorsed = !s.showUndistorsed; } if ( s.inputCapture.isOpened() && key == 'g' ) { mode = CAPTURING; imagePoints.clear(); } } // -----------------------Show the undistorted image for the image list ------------------------ if ( s.inputType == Settings::IMAGE_LIST && s.showUndistorsed ) { Mat view, rview, map1, map2; initUndistortRectifyMap( cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix( cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0 ), imageSize, CV_16SC2, map1, map2 ); for ( int i = 0; i < (int)s.imageList.size(); i++ ) { view = imread( s.imageList[i], 1 ); if ( view.empty() ) { continue; } remap( view, rview, map1, map2, INTER_LINEAR ); imshow( "Image View", rview ); char c = (char)waitKey(); if ( c == ESC_KEY || c == 'q' || c == 'Q' ) { break; } } } }
int getFontHeight(HWND hwnd, HFONT font) { return getTextSize(hwnd, font, "0Ajg^_|").cy; }
int getFontHeight(HDC hdc) { return getTextSize(hdc, "0Ajg^_|").cy; }
void PM_dem::detect( Mat &img, float score_thresh, bool show_hints, bool show_img, string save_img ) { if( score_thresh==DEFAULT_THRESH ) model.threshing = model.thresh; else model.threshing = score_thresh; hints = show_hints; // 1. Feature pyramid <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< prag_start = yuGetCurrentTime('M'); if( hints ){ printf("Calculating feature pyramid ...\n"); start_clock = prag_start; } featpyramid2( img, model, pyra ); if( hints ){ end_clock = yuGetCurrentTime('M'); printf("Time for _featpyramid is %gs\n",(end_clock-start_clock)/1000.f); } // 2. Compute PCA projection of the feature pyramid <<<<<<<<<<<<<< if( hints ){ printf("Compute PCA projection of the feature pyramid ...\n"); start_clock = end_clock; } /*Mat Ctest = model.C2(Rect(0,155,32,1)); cout<<Ctest;*/ //project_pyramid( model, pyra ); if( hints ){ end_clock = yuGetCurrentTime('M'); printf("Time for _project_pyramid() is %gs\n",(end_clock-start_clock)/1000.f); } if (hints) { end_clock = start_clock; printf("QT\n"); } qtpyra(model,pyra); if (hints) { end_clock = yuGetCurrentTime('M'); printf("%gs\n",(end_clock-start_clock)/1000.f); } if( pyra.num_levels!=pyra.feat.size() ){ printf("pyra.num_levels!=pyra.feat.size()\n"); throw runtime_error(""); } // 3. Precompute location/scale scores <<<<<<<<<<<<<<<<<<<<<<< Mat loc_f = loc_feat( model, pyra.num_levels ); pyra.loc_scores.resize( model.numcomponents ); for( int c=0; c<model.numcomponents; c++ ){ Mat loc_w( 1, model.loc[c].w.size(), CV_32FC1, &(model.loc[c].w[0]) ); // loc_w = model.loc[c].w pyra.loc_scores[c] = loc_w * loc_f; } // 4. Gather PCA root filters for convolution <<<<<<<<<<<<<<<<<<< if( hints ){ printf("Gathering PCA root filters for convolution ...\n"); start_clock = end_clock; } if( rootscores[0].size()!=pyra.num_levels ){ vector<Mat> tmp_rootscores(pyra.num_levels); rootscores.assign(model.numcomponents,tmp_rootscores); } // ofstream f1("pj.txt"); int numrootlocs = 0; int s = 0; // will hold the amount of temp storage needed by cascade() for( int i=0; i<pyra.num_levels; i++ ){ s += pyra.feat[i].rows * pyra.feat[i].cols; if( i<model.interval ) continue; static vector<Mat> scores; //fconv( pyra.projfeat[i], rootfilters, 0, numrootfilters, scores ); fconv_root_qt(model, pyra.qtfeat[i], scores); for( int c=0; c<model.numcomponents; c++ ){ int u = model.components[c].rootindex; int v = model.components[c].offsetindex; float tmp = model.offsets[v].w + pyra.loc_scores[c].at<float>(i); rootscores[c][i] = scores[u] + Scalar(tmp); numrootlocs += scores[u].total(); } } cout<<numrootlocs<<endl; s = s * model.partfilters.size(); if( hints ){ end_clock = yuGetCurrentTime('M'); printf("Time for gathering PCA root filters is %gs\n",(end_clock-start_clock)/1000.f); } // 5. Cascade detection in action <<<<<<<<<<<<<<<<<<<<<<< if( hints ){ printf("Cascade detection in action ...\n"); start_clock = end_clock; } //Mat coords = cascade(model, pyra, rootscores, numrootlocs, s); Mat coords = cascade_qt(model, pyra, rootscores, numrootlocs, s); //cout<<coords; //cout<<"??"<<endl; if( hints ){ end_clock = yuGetCurrentTime('M'); printf("Time for _cascade() is %gs\n",(end_clock-start_clock)/1000.f); if( coords.empty() ){ printf("No Detection!\n"); return; } } // 6. Detection results <<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Mat boxes = getboxes( model, img_color, coords ); Mat x1 = boxes.col(0); Mat y1 = boxes.col(1); Mat x2 = boxes.col(2); Mat y2 = boxes.col(3); Mat Score = boxes.col( boxes.cols-1 ); detections.resize( x1.rows ); for( int i=0; i<x1.rows; i++ ){ detections[i][0] = x1.at<float>(i); detections[i][1] = y1.at<float>(i); detections[i][2] = x2.at<float>(i); detections[i][3] = y2.at<float>(i); detections[i][4] = Score.at<float>(i); } if( hints ){ prag_end = yuGetCurrentTime('M'); printf("Total detection time is : %gs\n",(prag_end-prag_start)/1000.f); } // 6. Draw and show <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< if( show_img || !save_img.empty() ){ //showboxes( img_color, boxes ); // const int fontFace = CV_FONT_HERSHEY_PLAIN; const double fontScale = 1; const Scalar drawColor = CV_RGB(255,0,0); const Scalar fontColor = CV_RGB(30,250,150); // for( int i=0; i!=detections.size(); i++ ){ float x1 = detections[i][0], y1 = detections[i][1], x2 = detections[i][2], y2 = detections[i][3]; float _score = detections[i][4]; // Point2f UL( x1, y1 ); Point2f BR( x2, y2 ); rectangle( img_color, UL, BR, drawColor, 2 ); printf("----------------------------\n"); printf("%g %g %g %g %g\n", x1, y1, x2, y2, _score ); // x1 = int(x1*10+0.5) / 10.f; // ½ö±£Áô1λСÊý y1 = int(y1*10+0.5) / 10.f; x2 = int(x2*10+0.5) / 10.f; y2 = int(y2*10+0.5) / 10.f; _score = int(_score*100+0.5) / 100.f; // char buf[50] = { 0 }; sprintf_s( buf, 50, "%d", i ); string text = buf; int baseline = 0; Size textSize = getTextSize( text, fontFace, fontScale, 1, &baseline ); Point2f textOrg2( x1, y1+textSize.height+2 ); putText( img_color, text, textOrg2, fontFace, fontScale, fontColor ); // sprintf_s( buf, 50, "%d %g %g %g %g %g", i, x1, y1, x2, y2, _score ); text = buf; textSize = getTextSize( text, fontFace, fontScale, 1, &baseline ); Point2f textOrg(5,(i+1)*(textSize.height+3)); putText( img_color, text, textOrg, fontFace, fontScale, fontColor ); } { char buf[30] = { 0 }; sprintf_s( buf, 30, "time : %gs", (prag_end-prag_start)/1000.f ); string time_text = buf; int baseline = 0; Size textSize = getTextSize( time_text, fontFace, fontScale, 1, &baseline ); Point2f time_orig(5,(detections.size()+1)*(textSize.height+3)); putText( img_color, time_text, time_orig, fontFace, fontScale, fontColor ); } if( show_img ) imshow( "OK", img_color ); if( !save_img.empty() ) imwrite( save_img, img_color ); } }
void genHardNegatives(string retrainAppendFile, FeatGen* ldgFeatGen,const path& baseDir, datasets currDataset, bool writeOutWins, bool viz,string modelfile, double negBoundary) { bool debugOnlySomeWins = false; vector<path> negativePaths; vector<path> negTrainPaths; vector<path> negTestPaths; FrameId firstTestFrame; // separates training and testing data string learnFileStem; vector<path> normPosWinPathsTrain; // if any use folder with normalized cropped windows vector<path> normPosWinPathsTest; // if any use folder with normalized cropped windows getLearnInfos(baseDir, currDataset, negativePaths, negTrainPaths, negTestPaths,normPosWinPathsTrain, normPosWinPathsTest, learnFileStem, firstTestFrame); path negTrainFolder = baseDir / "learning" / "train_neg_hard"; remove_all(negTrainFolder); create_directories(negTrainFolder); //std::ios_base::openmode mode = ; //fs::ofstream trainFile((baseDir / "learning" / learnFileStem).string(), std::ios_base::out | ios_base::app); //fs::ofstream trainFilesFile((baseDir / "learning" / learnFileStem).string() + ".files", std::ios_base::out | ios_base::app); //fs::ofstream trainFileHard((baseDir / "learning" / learnFileStem).string() + "_hard"); fs::ofstream trainFileHard(retrainAppendFile,std::ios_base::out | ios_base::app); if ( !(modelfile.length() > 0 ) ) { modelfile = (baseDir / "learning" / learnFileStem).string() + ".model"; } path mfp(modelfile); if ( !exists(mfp)) { cerr << "Modelfile does not exist: " << modelfile << endl; exit(EXIT_FAILURE); } Detector pd(ldgFeatGen); pd.setStartScale(1); pd.setScaleStep(1.0718); pd.loadSVMWeights(modelfile); if ( negBoundary < 0 ) negBoundary *= -1.0; float decThresh = -negBoundary; int countedWindows = 0; int nww = ldgFeatGen->getWinW(); int nwh = ldgFeatGen->getWinH(); cout << "genHardNegatives using model: " << mfp.string() << " dec: " << decThresh << endl; for ( vector<path>::iterator pit(negTrainPaths.begin()); pit != negTrainPaths.end(); ++pit) { path np = *pit; vector<path> v; copy(directory_iterator(np),directory_iterator(),back_inserter(v)); sort(v.begin(),v.end()); size_t featSize = ldgFeatGen->getWindowFeatLen(); // feature size int processedImages = 0; cout << "0% "; cout.flush(); for ( vector<path>::iterator it (v.begin()); it != v.end(); ++it) { if ( processedImages % 10 == 0 ) { cout << floor((processedImages/(double) v.size()* 100.0 )) << "% "; cout.flush(); } if (debugOnlySomeWins && processedImages > 30) { break; } //if ( processedImages/(double) v.size()* 100.0 < 62.9 ) /*if ( processedImages < 770) { processedImages++; continue; }*/ path nf = *it; string filePre = nf.parent_path().parent_path().stem().string() + nf.parent_path().stem().string() + "_" + nf.filename().stem().string(); Mat img = imread(nf.string(),CV_LOAD_IMAGE_COLOR); vector< pair<Detection,double*> > detections; vector<Detection> alldetections; pd.detect(img,detections,alldetections,decThresh,true); // pick random windows vector<size_t> randPicks; const int numPicks = 10; if ( detections.size() > numPicks ) { int picks = 0; int dSize = detections.size(); while(picks != numPicks) { int randPick = rand() % dSize; bool exists = false; for ( int i = 0; i < randPicks.size(); i++ ) { if ( randPicks[i] == randPick) { exists = true; break; } } if ( !exists ) { picks++; randPicks.push_back(randPick); } } } else { for ( int i = 0; i < detections.size(); i++ ) { randPicks.push_back(i); } } for ( size_t i = 0; i < randPicks.size(); i++) { pair < Detection,double* > mp = detections[randPicks[i]]; Detection det = mp.first; Rect r = det.r; double* f = mp.second; writeFeatToSVMStream(f,trainFileHard,featSize,false); countedWindows++; } // free cached features for ( size_t i = 0; i < detections.size(); i++) { pair < Detection,double* > mp = detections[i]; double* f = mp.second; delete [] f; } if ( viz || writeOutWins ) { Mat vizImg = img.clone(); for ( vector< Detection >::iterator it(alldetections.begin()); it != alldetections.end(); it++) { Detection det = *it; Rect r = det.rNormWin; //cout << r.x << " " << r.y << " " << r.width << "x" << r.height << " scale:" << det.scale << " decisionValue:" << det.decisionValue << endl; rectangle(vizImg,r,Scalar(255,50,50),1,8); } for ( size_t i = 0; i < detections.size(); i++) { Detection det = detections[i].first; Rect r = det.r; rectangle(vizImg,r,Scalar(0,0,255),1,8); // render detection score ostringstream detscoretxt; detscoretxt.precision(3); detscoretxt << det.decisionValue; string text = detscoretxt.str(); int fontFace = FONT_HERSHEY_DUPLEX; double fontScale = 0.5; int thickness = 0; int baseline=0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; Point textOrg(det.r.x + (det.r.width - textSize.width)/2.0, det.r.y + (det.r.height - textSize.height)/2.0); bool isPicked = false; for ( size_t k = 0; k < randPicks.size(); k++ ) { if ( randPicks[k] == i ) { isPicked = true; break; } } if (isPicked ) { rectangle(vizImg, textOrg + Point(0, baseline-3), textOrg + Point(textSize.width, -textSize.height), Scalar(80,200,80), CV_FILLED); } else { rectangle(vizImg, textOrg + Point(0, baseline-3), textOrg + Point(textSize.width, -textSize.height), Scalar(0,0,255), CV_FILLED); } // ... and the baseline first //line(img, textOrg + Point(0, thickness), // textOrg + Point(textSize.width, thickness), // Scalar(0, 0, 255)); putText(vizImg, text, textOrg, fontFace, fontScale, Scalar::all(255), thickness, 8); } if ( writeOutWins && detections.size() > 0 ) { string fileNameOnly = (filePre +"_hard.png"); path nwPath = negTrainFolder / fileNameOnly; imwrite(nwPath.string(),vizImg); } if ( viz ) { imshow("negative training image",vizImg); waitKey(0); } } processedImages++; } cout << "100% " << endl; } //trainFile.close(); trainFileHard.close(); cout << countedWindows << " hard negatives found." << endl; }