void Button::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QRectF rect = boundingRect(); painter->drawImage(rect,*outimg); painter->fillRect(rect, QColor(255, 255, 255, glow * 10)); }
void QDeclarativeMouseArea::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { Q_D(QDeclarativeMouseArea); if (!d->absorb) { QDeclarativeItem::mouseMoveEvent(event); return; } d->saveEvent(event); // ### we should skip this if these signals aren't used // ### can GV handle this for us? bool contains = boundingRect().contains(d->lastPos); if (d->hovered && !contains) setHovered(false); else if (!d->hovered && contains) setHovered(true); if (d->drag && d->drag->target()) { if (!d->moved) { d->startX = drag()->target()->x(); d->startY = drag()->target()->y(); } QPointF startLocalPos; QPointF curLocalPos; if (drag()->target()->parentItem()) { startLocalPos = drag()->target()->parentItem()->mapFromScene(d->startScene); curLocalPos = drag()->target()->parentItem()->mapFromScene(event->scenePos()); } else { startLocalPos = d->startScene; curLocalPos = event->scenePos(); } const int dragThreshold = QApplication::startDragDistance(); qreal dx = qAbs(curLocalPos.x() - startLocalPos.x()); qreal dy = qAbs(curLocalPos.y() - startLocalPos.y()); if (keepMouseGrab() && d->stealMouse) d->drag->setActive(true); if (d->dragX && d->drag->active()) { qreal x = (curLocalPos.x() - startLocalPos.x()) + d->startX; if (x < drag()->xmin()) x = drag()->xmin(); else if (x > drag()->xmax()) x = drag()->xmax(); drag()->target()->setX(x); } if (d->dragY && d->drag->active()) { qreal y = (curLocalPos.y() - startLocalPos.y()) + d->startY; if (y < drag()->ymin()) y = drag()->ymin(); else if (y > drag()->ymax()) y = drag()->ymax(); drag()->target()->setY(y); } if (!keepMouseGrab()) { if ((!d->dragY && dy < dragThreshold && d->dragX && dx > dragThreshold) || (!d->dragX && dx < dragThreshold && d->dragY && dy > dragThreshold) || (d->dragX && d->dragY && (dx > dragThreshold || dy > dragThreshold))) { setKeepMouseGrab(true); d->stealMouse = true; } } d->moved = true; } QDeclarativeMouseEvent me(d->lastPos.x(), d->lastPos.y(), d->lastButton, d->lastButtons, d->lastModifiers, false, d->longPress); emit mousePositionChanged(&me); me.setX(d->lastPos.x()); me.setY(d->lastPos.y()); emit positionChanged(&me); }
void Processor::Img_pro() { _rotation(); imwrite("/storage/emulated/0/baidu/img.jpg",_img); Mat gray; cvtColor(_img, gray, CV_RGB2GRAY); Mat bin; adaptiveThreshold(gray, bin, 255, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 101, 1); imwrite("/storage/emulated/0/baidu/bin.jpg", bin); std::vector<std::vector<cv::Point> > contours; //des,contours,�ⲿ������������ findContours(bin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); Mat des(_img.size(), CV_8UC1, Scalar(0)); for (int i = 0; i < contours.size(); i++) { if (contourArea(contours[i]) < 350) continue; drawContours(des, contours, i, Scalar(255), -1); } imwrite("/storage/emulated/0/baidu/des.jpg", des); Mat element = getStructuringElement(MORPH_RECT, Size(3,3)); dilate(des, des, element); contours.clear(); findContours(des, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); for (int i = 0; i < contours.size(); i++) { if (contourArea(contours[i]) < 350) continue; Mat sample(_img.size(), CV_8UC1, Scalar(0)); drawContours(sample, contours, i, Scalar(255), - 1); Mat regionOfInterest; Rect rec = boundingRect(contours[i]); Sample_Elem tmp; tmp.x_position = rec.x; tmp.y_position = rec.y; tmp.height = rec.height; tmp.weight = rec.width; if (rec.width < rec.height) { rec.x -= (rec.height - rec.width) / 2; if (rec.x < 0) rec.x = 0; if (rec.x + rec.height>sample.cols) rec.width = sample.cols - rec.x; else rec.width = rec.height; } else{ rec.y -= (rec.width - rec.height) / 2; if (rec.y < 0) rec.y = 0; if (rec.y + rec.width>sample.rows) rec.height = sample.rows - rec.y; else rec.height = rec.width; tmp.y_position = rec.y; tmp.height = rec.width; } /* FILE* fp; fp = fopen(".\\data\\sample_rect_data.txt", "a+"); if (fp == NULL) { std::cout << "rect error"; return; } fprintf(fp, "%d,%d,%d,%d\n", rec.x, rec.y, rec.width, rec.height); fclose(fp); */ regionOfInterest = sample(rec); resize(regionOfInterest, regionOfInterest, Size(SAMPLE_SIZE, SAMPLE_SIZE)); tmp.img = regionOfInterest; _Mat_contours.append(tmp); } }
FloatRect Path::fastBoundingRect() const { return boundingRect(); }
void DetectorObserver::display(QRectF region) { emit boundingRect(region); }
void CharacterAnalysis::filterBetweenLines(Mat img, TextContours& textContours, vector<TextLine> textLines ) { static float MIN_AREA_PERCENT_WITHIN_LINES = 0.88; static float MAX_DISTANCE_PERCENT_FROM_LINES = 0.15; if (textLines.size() == 0) return; vector<Point> validPoints; // Create a white mask for the area inside the polygon Mat outerMask = Mat::zeros(img.size(), CV_8U); for (unsigned int i = 0; i < textLines.size(); i++) fillConvexPoly(outerMask, textLines[i].linePolygon.data(), textLines[i].linePolygon.size(), Scalar(255,255,255)); // For each contour, determine if enough of it is between the lines to qualify for (unsigned int i = 0; i < textContours.size(); i++) { if (textContours.goodIndices[i] == false) continue; float percentInsideMask = getContourAreaPercentInsideMask(outerMask, textContours.contours, textContours.hierarchy, (int) i); if (percentInsideMask < MIN_AREA_PERCENT_WITHIN_LINES) { // Not enough area is inside the lines. if (config->debugCharAnalysis) cout << "Rejecting due to insufficient area" << endl; textContours.goodIndices[i] = false; continue; } // now check to make sure that the top and bottom of the contour are near enough to the lines // First get the high and low point for the contour // Remember that origin is top-left, so the top Y values are actually closer to 0. Rect brect = boundingRect(textContours.contours[i]); int xmiddle = brect.x + (brect.width / 2); Point topMiddle = Point(xmiddle, brect.y); Point botMiddle = Point(xmiddle, brect.y+brect.height); // Get the absolute distance from the top and bottom lines for (unsigned int i = 0; i < textLines.size(); i++) { Point closestTopPoint = textLines[i].topLine.closestPointOnSegmentTo(topMiddle); Point closestBottomPoint = textLines[i].bottomLine.closestPointOnSegmentTo(botMiddle); float absTopDistance = distanceBetweenPoints(closestTopPoint, topMiddle); float absBottomDistance = distanceBetweenPoints(closestBottomPoint, botMiddle); float maxDistance = textLines[i].lineHeight * MAX_DISTANCE_PERCENT_FROM_LINES; if (absTopDistance < maxDistance && absBottomDistance < maxDistance) { // It's ok, leave it as-is. } else { textContours.goodIndices[i] = false; if (config->debugCharAnalysis) cout << "Rejecting due to top/bottom points that are out of range" << endl; } } } }
/*----------------------------////????? * 功能 : 生成近距物体信息序列 *---------------------------- * 函数 : PointCloudAnalyzer::parseCandidates * 访问 : private * 返回 : void * * 参数 : objects [in] 深度阈值化后的二值图像,显示了近距物体的分布 * 参数 : depthMap [in] 从三维点云矩阵中抽取的深度数据矩阵 * 参数 : objectInfos [out] 目标信息序列 */ void PointCloudAnalyzer::parseCandidates(cv::Mat& objects, cv::Mat& depthMap, vector<ObjectInfo>& objectInfos) { // 提取物体轮廓 // Mat canny_output; vector<vector<cv::Point> > contours; // 物体轮廓点链 // vector<Vec4i>hierarchy; cv::Mat tempobjects=objects; /// 用Canny算子检测边缘 // Canny( tempobjects, canny_output, 80, 160, 3 ); findContours(tempobjects, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); /* Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 ); for( int i = 0; i< contours.size(); i++ ) { Scalar color = Scalar(0, 233, 0); drawContours( drawing, contours, i, color, 2, 8); } /// 在窗体中显示结果 namedWindow( "Contours", CV_WINDOW_AUTOSIZE ); imshow( "Contours", drawing );*/ // findContours(objects, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // findContours(objects,contours,hierarchy,CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); /* findContours后的轮廓信息contours可能过于复杂不平滑,可以用approxPolyDP函数对该多边形曲线做适当近似 contourArea函数可以得到当前轮廓包含区域的大小,方便轮廓的筛选 findContours经常与drawContours配合使用,用来将轮廓绘制出来。 其中第一个参数image表示目标图像,第二个参数contours表示输入的轮廓组,每一组轮廓由点vector构成, 第三个参数contourIdx指明画第几个轮廓,如果该参数为负值,则画全部轮廓,第四个参数color为轮廓的颜色, 第五个参数thickness为轮廓的线宽,如果为负值或CV_FILLED表示填充轮廓内部,第六个参数lineType为线型, 第七个参数为轮廓结构信息,第八个参数为maxLevel*/ // 分析轮廓 double areaThresh = 0.005 * depthMap.rows * depthMap.cols; cv::Mat mask = cv::Mat::zeros(objects.size(), CV_8UC1);////1 bool useMeanDepth = false; // CString str; // str.Format(_T("%d"),contours.size()); // AfxMessageBox(str); for( UINT objID = 0; objID < contours.size(); objID++ )//得出每个轮廓的信息 { cv::Mat contour = cv::Mat( contours[objID] ); double area = contourArea( contour );//计算轮廓面积 if(area>0) { ObjectInfo object; // 填充物体内部轮廓作为掩码区域 mask = cv::Scalar(0); drawContours(mask,contours,objID,cv::Scalar(255),-1); /* 用来将轮廓绘制出来。其中第一个参数image表示目标图像, 第二个参数contours表示输入的轮廓组,每一组轮廓由点vector构成, 第三个参数contourIdx指明画第几个轮廓,如果该参数为负值, 则画全部轮廓,第四个参数color为轮廓的颜色, 第五个参数thickness为轮廓的线宽, 如果为负值或CV_FILLED表示填充轮廓内部, 第六个参数lineType为线型,第七个参数为轮廓结构信息,第八个参数为maxLevel */ double minVal = 0, maxVal = 0; cv::Point minPos; cv::minMaxLoc(depthMap, &minVal, &maxVal, &minPos, NULL, mask); object.distance = depthMap.at<float>(minPos.y, minPos.x); // } // 计算轮廓矩形 object.boundRect = boundingRect( contour );//计算点集的最外面(up-right)矩形边界 object.minRect = minAreaRect( contour ); object.center = object.minRect.center; // 保存物体轮廓信息 objectInfos.push_back( object ); } } // 按物体距离重新排序 //std::sort( objectInfos.begin(), objectInfos.end(), std::greater<ObjectInfo>() ); }
QPainterPath Cell::shape() const { QPainterPath path; path.addRect(boundingRect()); return path; }
void VNote::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); Q_UNUSED(option); switch (notetype) { case ScoreViewModel::whole: pixmap.load("./res/whole_note.png"); painter->drawPixmap(0,0,30,20,pixmap); break; case ScoreViewModel::half: pixmap.load("./res/half_note.png"); painter->drawPixmap(0,0,24,20,pixmap); break; case ScoreViewModel::quarter: pixmap.load("./res/quarter_note.png"); painter->drawPixmap(0,0,24,20,pixmap); break; case ScoreViewModel::eighth: pixmap.load("./res/quarter_note.png"); painter->drawPixmap(0,0,24,20,pixmap); break; case ScoreViewModel::whole_rest: pixmap.load("./res/whole_rest.png"); painter->drawPixmap(0,0,30,10,pixmap); break; case ScoreViewModel::half_rest: pixmap.load("./res/half_rest.png"); painter->drawPixmap(0,0,30,20,pixmap); break; case ScoreViewModel::quarter_rest: pixmap.load("./res/quarter_rest.png"); painter->drawPixmap(0,-10,20,63,pixmap); break; case ScoreViewModel::eighth_rest: pixmap.load("./res/eighth_rest.png"); painter->drawPixmap(0,2.5,20,36,pixmap); break; default: pixmap.load("./res/half_note.png"); painter->drawPixmap(0,0,24,20,pixmap); break; } QPixmap accentpixmap = QPixmap(); if(!iskeysig){ switch (accent) { case Accent::sharp: accentpixmap.load("./res/sharp.png"); painter->drawPixmap(-20,-5,16,35,accentpixmap); break; case Accent::flat: accentpixmap.load("./res/flat.png"); painter->drawPixmap(-20,-15,16,35,accentpixmap); break; default: break; } }else if(accent == Accent::natural){ accentpixmap.load("./res/natural.png"); painter->drawPixmap(-20,-10,11,40,accentpixmap); } QPen pen(Qt::black); pen.setWidth(2); if(notetype == ScoreViewModel::half || notetype == ScoreViewModel::quarter || notetype == ScoreViewModel::eighth){ painter->setPen(pen); if(getStaffpos() < 8){ painter->drawLine(boundingRect().right()-1, 5, boundingRect().right()-1, -60); //note line if(notetype == ScoreViewModel::eighth){ QPixmap flagpixmap("./res/flag.png"); painter->drawPixmap(boundingRect().right(), -60, 26, 60, flagpixmap); //eighth flag } }else{ painter->drawLine(boundingRect().left()+1, 15, boundingRect().left()+1, 80); if(notetype == ScoreViewModel::eighth){ QPixmap flagpixmap("./res/flag_flip.png"); painter->drawPixmap(boundingRect().left(), 20, 26, 60, flagpixmap); } } } if(staffpos == 0){ painter->drawLine(-10, 10, 35, 10); painter->drawLine(-10, -10, 35, -10); }else if(staffpos == 1){ painter->drawLine(-10, 0, 35, 0); }else if(staffpos == 15){ painter->drawLine(-10, 20, 35, 20); }else if(staffpos == 16){ painter->drawLine(-10, 10, 35, 10); painter->drawLine(-10, 30, 35, 30); }else if(staffpos == 2 || staffpos == 14){ painter->drawLine(-10, 10, 35, 10); } if(this->isSelected()){ pen.setColor(Qt::red); pen.setWidth(1); painter->setPen(pen); painter->drawRect(boundingRect()); if(!parentItem()->isSelected()){ this->parentItem()->setSelected(true); } } }
void GraphicsEdge::unSetColor() { setZValue(_zValue); _overrideColor = false; scene()->update(boundingRect()); }
//bool Depth_and_Disparity::calc_disperity(int desiredPhase, Mat in_left_clr, Mat in_right_clr, bool Depth_and_Disparity::calc_disperity(int desiredPhase, Mat left_im_gray, Mat right_im_gray, Mat BgMask , Target *previousTarget, Mat *disperity_out, double *min_depth_of_ROI) { double max_disperity; const double allowed_disp_delta_between_cycles = 0.1 ; //10[%] if ( ! (desiredPhase==2) ) //calculate the new disparity for new inputs { // delivers new input , when the process is waiting (not in calculation process) set_disparity_input(right_im_gray,left_im_gray, /*myStereoCams.GetFrameCycleCounter()*/ 1 ); // waiting trial : while (! get_rectified_and_disparity(last_result_of_disparity, last_result_of_disparity_struct) ) { } if ((desiredPhase==1)) { *disperity_out = last_result_of_disparity.clone() ; return true; } } // continue to give the filtered disparity (for the new or the last calculated) /* if output is ready from disparity calculation , it returns true */ //if ( localDisp.get_rectified_and_disparity(disp_temporary, disperity_struct) ) { /* calculate average depth for the ROI of the target */ Mat tmpma = last_result_of_disparity; if ( ! BgMask.empty() ) { filtered_disparity = Mat(); last_result_of_disparity.copyTo(filtered_disparity , BgMask); threshold (filtered_disparity , filtered_disparity , minDisparityToCut , 255,THRESH_TOZERO); } else /* no additional mask */ if ((*previousTarget).target_object_prop.relevant_disparity > -999) { threshold (last_result_of_disparity , filtered_disparity , (*previousTarget).target_object_prop.relevant_disparity * (1-allowed_disp_delta_between_cycles) , (*previousTarget).target_object_prop.relevant_disparity * (1+allowed_disp_delta_between_cycles), THRESH_TOZERO); //.15?? } else /* loose the far away objects (small disparities) */ threshold (last_result_of_disparity , filtered_disparity , minDisparityToCut , 255,THRESH_TOZERO); int an=1; //an=1->kernel of 3 Mat element = getStructuringElement(MORPH_RECT, Size(an*2+1, an*2+1), Point(an, an) ); medianBlur (filtered_disparity, filtered_disparity, an*3); erode (filtered_disparity , filtered_disparity, element); dilate (filtered_disparity, filtered_disparity, element); //max disperity into avg_disp var // minMaxLoc(filtered_disparity, 0, &max_disperity ); // convert_disperity_value_to_depth(max_disperity , *min_depth_of_ROI); // last_disparity_min_depth = *min_depth_of_ROI; Scalar mean; Scalar stddev; Rect tmp = boundingRect(filtered_disparity); Mat tmpMask = filtered_disparity; ///meanStdDev ( filtered_disparity, mean, stddev ); ///meanStdDev ( filtered_disparity(tmp), mean, stddev ); meanStdDev ( filtered_disparity, mean, stddev , tmpMask); //uchar mean_pxl = mean.val[0]; int mean_val = mean.val[0]; //uchar stddev_pxl = stddev.val[0]; int stddev_val = stddev.val[0]; int minDispToTake = mean_val - stddev_val * 1 ; if (minDispToTake > mean_val * (1-allowed_disp_delta_between_cycles/2.) ) minDispToTake = mean_val * (1-allowed_disp_delta_between_cycles/2.) ; //minimum for case of ~zero std ; // furthest object //int maxDispToTake = max_disperity ; // closest object convert_disperity_value_to_depth(mean_val , *min_depth_of_ROI); last_disparity_depth = *min_depth_of_ROI; /* filter far or close objects then the target itself (mean) */ threshold (filtered_disparity , filtered_disparity , minDispToTake , 255/*max_disperity*/,THRESH_TOZERO); /* set partial data for current target */ (*previousTarget).target_object_prop.relevant_disparity = mean_val; } *disperity_out = filtered_disparity.clone() ; return true; // TODO: set as SUCCESS system enum }
QPainterPath QtBouncingBall::shape() const { QPainterPath p; p.addEllipse(boundingRect()); return p; }
void TargetExtractor::regionGrow(int threshold) { Mat gray; cvtColor(mFrame, gray, CV_BGR2GRAY); Mat temp; mMask.copyTo(temp); vector<vector<Point> > contours; findContours(temp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); int maxQueueSize = mFrame.rows * mFrame.cols / 4; static int direction[8][2] = { { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 } }; for (int i = 0; i < contours.size(); i++) { Rect rect = boundingRect(Mat(contours[i])); Mat mask = Mat::zeros(gray.size(), CV_8U); drawContours(mask, contours, i, Scalar::all(255), CV_FILLED); int size = sum(mask(rect))[0] / 255; Scalar m, s; meanStdDev(gray(rect), m, s, mask(rect)); double mean = m[0], stdDev = s[0]; Mat temp; mMask.copyTo(temp); int origSize = size; queue<Point> pointQueue; for (int j = 0; j < contours[i].size(); j++) { uchar pixel = gray.at<uchar>(contours[i][j]); if (abs(pixel - mean) < 1.0 * stdDev) { pointQueue.push(contours[i][j]); } } Point cur, pop; while (!pointQueue.empty() && pointQueue.size() < maxQueueSize) { pop = pointQueue.front(); pointQueue.pop(); uchar pixel = gray.at<uchar>(pop); for (int k = 0; k < 8; k++) { cur.x = pop.x + direction[k][0]; cur.y = pop.y + direction[k][1]; if (cur.x < 0 || cur.x > gray.cols - 1 || cur.y < 0 || cur.y > gray.rows - 1) { continue; } if (temp.at<uchar>(cur) != 255) { uchar curPixel = gray.at<uchar>(cur); if (abs(curPixel - pixel) < threshold && abs(curPixel - mean) < 1.0 * stdDev) { temp.at<uchar>(cur) = 255; double diff = curPixel - mean; double learningRate = 1.0 / (++size); mean = (1 - learningRate) * mean + learningRate * curPixel; stdDev = sqrt((1 - learningRate) * stdDev * stdDev + learningRate * diff * diff); pointQueue.push(cur); } } } } if (pointQueue.empty()) { int incSize = size - origSize; if (incSize < mFrame.rows * mFrame.cols / 6 && incSize / origSize < 5) { mMask = temp; } } } }
void Button::init() { setFlags(ItemIsFocusable); setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::LeftButton); title = new QPixmap(size.toSize()); title->fill(QColor(0, 0, 0, 0)); QPainter pt(title); pt.setFont(font); pt.setPen(Config.TextEditColor); pt.setRenderHint(QPainter::TextAntialiasing); pt.drawText(boundingRect(), Qt::AlignCenter, label); title_item = new QGraphicsPixmapItem(this); title_item->setPixmap(*title); title_item->show(); QGraphicsDropShadowEffect *de = new QGraphicsDropShadowEffect; de->setOffset(0); de->setBlurRadius(12); de->setColor(QColor(255, 165, 0)); title_item->setGraphicsEffect(de); QImage bgimg("image/system/button/button.png"); outimg = new QImage(size.toSize(), QImage::Format_ARGB32); qreal pad = 10; int w = bgimg.width(); int h = bgimg.height(); int tw = outimg->width(); int th = outimg->height(); qreal xc = (w - 2 * pad) / (tw - 2 * pad); qreal yc = (h - 2 * pad) / (th - 2 * pad); for (int i = 0; i < tw; i++) { for (int j = 0; j < th; j++) { int x = i; int y = j; if (x >= pad && x <= (tw - pad)) x = pad + (x - pad) * xc; else if (x >= (tw - pad)) x = w - (tw - x); if (y >= pad && y <= (th - pad)) y = pad + (y - pad) * yc; else if (y >= (th - pad)) y = h - (th - y); QRgb rgb = bgimg.pixel(x, y); outimg->setPixel(i, j, rgb); } } QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect; effect->setBlurRadius(5); effect->setOffset(this->boundingRect().height() / 7.0); effect->setColor(QColor(0, 0, 0, 200)); this->setGraphicsEffect(effect); glow = 0; timer_id = 0; }
void ItemComp::setHeight(int _value) { mHeight = _value; update(boundingRect()); }
void TopLevelWindowManager::createBrickModeWindow() { qreal opacity = 0.0; if(m_brickWindow) { if (m_brickSurfAnimation.targetObject()) m_brickSurfAnimation.stop(); m_brickSurfAnimation.setTargetObject(NULL); opacity = m_brickWindow->opacity(); m_brickWindow->setParentItem(0); delete m_brickWindow; m_brickWindow = 0; if( m_brickSurf ) { delete m_brickSurf; m_brickSurf = 0; } } // create scratch context QPainter* painter = new QPainter(); m_brickSurf = new QPixmap(boundingRect().width(), boundingRect().height()); // fill with black m_brickSurf->fill(QColor(0x00, 0x00, 0x00, 0xFF)); // blit brick image centered painter->begin(m_brickSurf); std::string filePath = Settings::LunaSettings()->lunaSystemResourcesPath; std::string bgPath = filePath + "/normal-bg.png"; std::string fgPath = filePath + "/normal-usb.png"; QPixmap image(bgPath.c_str()); if (!image.isNull()) { painter->drawPixmap((m_brickSurf->width() - image.width())/2, (m_brickSurf->height() - image.height())/2, image.width(), image.height(), image); } else { g_warning("Failed to load brick image: %s", bgPath.c_str()); } image.load(fgPath.c_str()); if (!image.isNull()) { painter->drawPixmap((m_brickSurf->width() - image.width())/2, (m_brickSurf->height() - image.height())/2, image.width(), image.height(), image); } else { g_warning("Failed to load brick image: %s", fgPath.c_str()); } painter->end(); // clean up delete painter; m_brickWindow = new Window(Window::Type_Invalid, *m_brickSurf); m_brickWindow->setOpacity(opacity); m_brickWindow->setParentItem(this); }
// Thought: simply use the bounding box of the feature points as the head. void HeartFeatureTracker::track(Mat &colorImage, Mat &depthImage) { Mat gray; vector<uchar> status; vector<float> err; vector<Point2f> points; cvtColor(depthImage, gray, COLOR_BGR2GRAY); Mat roiColor = depthImage(bbox); Mat roi = gray(bbox); if(prevPoints.empty()) { return; } calcOpticalFlowPyrLK(prevGray, roi, prevPoints, points, status, err, Size(10,10), 3, TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 20, 0.03), 0, 0.001); Mat transform = estimateRigidTransform(prevPoints, points, false); //applyTransformToPoints(boundBox, transform); //applyTransformToPoints(patchOfInterest, transform); size_t i, k; bool brokeOut = false; for( i = k = 0; i < points.size(); i++ ) { if( !status[i] ) { continue; } points[k++] = points[i]; circle( roiColor, points[i], 3, Scalar(0,255,0), -1, 8); } points.resize(k); Rect dumbRect = boundingRect(points); convertRectToMats(boundBox, dumbRect); rectangle(roiColor, dumbRect, Scalar(0,255,0)); convertRectToMats(patchOfInterest, getForeheadFromBbox(dumbRect)); RotatedRect dumbRotated = minAreaRect(points); Point2f rect_points[4]; dumbRotated.points(rect_points); Scalar color = Scalar( 255, 0, 0 ); for( int j = 0; j < 4; j++ ) line( roiColor, rect_points[j], rect_points[(j+1)%4], color, 1, 8 ); DrawBoxFromPoints(boundBox, roiColor); DrawBoxFromPoints(patchOfInterest, roiColor); prevGray = roi; prevPoints = points; }
CharacterSegmenter::CharacterSegmenter(Mat img, bool invertedColors, Config* config) { this->config = config; this->confidence = 0; if (this->config->debugCharSegmenter) cout << "Starting CharacterSegmenter" << endl; //CharacterRegion charRegion(img, debug); timespec startTime; getTime(&startTime); Mat img_gray(img.size(), CV_8U); cvtColor( img, img_gray, CV_BGR2GRAY ); //normalize(img_gray, img_gray, 0, 255, CV_MINMAX ); medianBlur(img_gray, img_gray, 3); if (invertedColors) bitwise_not(img_gray, img_gray); charAnalysis = new CharacterAnalysis(img_gray, config); charAnalysis->analyze(); if (this->config->debugCharSegmenter) { displayImage(config, "CharacterSegmenter Thresholds", drawImageDashboard(charAnalysis->thresholds, CV_8U, 3)); } if (this->config->debugCharSegmenter) { Mat img_contours(charAnalysis->bestThreshold.size(), CV_8U); charAnalysis->bestThreshold.copyTo(img_contours); cvtColor(img_contours, img_contours, CV_GRAY2RGB); vector<vector<Point> > allowedContours; for (int i = 0; i < charAnalysis->bestContours.size(); i++) { if (charAnalysis->bestCharSegments[i]) allowedContours.push_back(charAnalysis->bestContours[i]); } drawContours(img_contours, charAnalysis->bestContours, -1, // draw all contours cv::Scalar(255,0,0), // in blue 1); // with a thickness of 1 drawContours(img_contours, allowedContours, -1, // draw all contours cv::Scalar(0,255,0), // in green 1); // with a thickness of 1 if (charAnalysis->linePolygon.size() > 0) { line(img_contours, charAnalysis->linePolygon[0], charAnalysis->linePolygon[1], Scalar(255, 0, 255), 1); line(img_contours, charAnalysis->linePolygon[3], charAnalysis->linePolygon[2], Scalar(255, 0, 255), 1); } Mat bordered = addLabel(img_contours, "Best Contours"); imgDbgGeneral.push_back(bordered); } // Figure out the average character width float totalCharWidth = 0; float totalCharHeight = 0; if (charAnalysis->linePolygon.size() > 0) { this->top = LineSegment(charAnalysis->linePolygon[0].x, charAnalysis->linePolygon[0].y, charAnalysis->linePolygon[1].x, charAnalysis->linePolygon[1].y); this->bottom = LineSegment(charAnalysis->linePolygon[3].x, charAnalysis->linePolygon[3].y, charAnalysis->linePolygon[2].x, charAnalysis->linePolygon[2].y); for (int i = 0; i < charAnalysis->bestContours.size(); i++) { if (charAnalysis->bestCharSegments[i] == false) continue; Rect mr = boundingRect(charAnalysis->bestContours[i]); totalCharWidth += mr.width; totalCharHeight += mr.height; } int numSamples = charAnalysis->bestCharSegmentsCount; float avgCharWidth = totalCharWidth / numSamples; float avgCharHeight = totalCharHeight / numSamples; removeSmallContours(charAnalysis->thresholds, charAnalysis->allContours, avgCharWidth, avgCharHeight); // Do the histogram analysis to figure out char regions timespec startTime; getTime(&startTime); vector<Mat> allHistograms; vector<Rect> allBoxes; for (int i = 0; i < charAnalysis->allContours.size(); i++) { Mat histogramMask = Mat::zeros(charAnalysis->thresholds[i].size(), CV_8U); fillConvexPoly(histogramMask, charAnalysis->linePolygon.data(), charAnalysis->linePolygon.size(), Scalar(255,255,255)); VerticalHistogram vertHistogram(charAnalysis->thresholds[i], histogramMask); if (this->config->debugCharSegmenter) { Mat histoCopy(vertHistogram.debugImg.size(), vertHistogram.debugImg.type()); //vertHistogram.copyTo(histoCopy); cvtColor(vertHistogram.debugImg, histoCopy, CV_GRAY2RGB); allHistograms.push_back(histoCopy); } // float score = 0; vector<Rect> charBoxes = getHistogramBoxes(vertHistogram.debugImg, avgCharWidth, avgCharHeight, &score); if (this->config->debugCharSegmenter) { for (int cboxIdx = 0; cboxIdx < charBoxes.size(); cboxIdx++) { rectangle(allHistograms[i], charBoxes[cboxIdx], Scalar(0, 255, 0)); } Mat histDashboard = drawImageDashboard(allHistograms, allHistograms[0].type(), 3); displayImage(config, "Char seg histograms", histDashboard); } for (int z = 0; z < charBoxes.size(); z++) allBoxes.push_back(charBoxes[z]); //drawAndWait(&histogramMask); } float biggestCharWidth = avgCharWidth; // Compute largest char width for (int i = 0; i < allBoxes.size(); i++) { if (allBoxes[i].width > biggestCharWidth) biggestCharWidth = allBoxes[i].width; } if (config->debugTiming) { timespec endTime; getTime(&endTime); cout << " -- Character Segmentation Create and Score Histograms Time: " << diffclock(startTime, endTime) << "ms." << endl; } //ColorFilter colorFilter(img, charAnalysis->getCharacterMask()); vector<Rect> candidateBoxes = getBestCharBoxes(charAnalysis->thresholds[0], allBoxes, biggestCharWidth); if (this->config->debugCharSegmenter) { // Setup the dashboard images to show the cleaning filters for (int i = 0; i < charAnalysis->thresholds.size(); i++) { Mat cleanImg = Mat::zeros(charAnalysis->thresholds[i].size(), charAnalysis->thresholds[i].type()); Mat boxMask = getCharBoxMask(charAnalysis->thresholds[i], candidateBoxes); charAnalysis->thresholds[i].copyTo(cleanImg); bitwise_and(cleanImg, boxMask, cleanImg); cvtColor(cleanImg, cleanImg, CV_GRAY2BGR); for (int c = 0; c < candidateBoxes.size(); c++) rectangle(cleanImg, candidateBoxes[c], Scalar(0, 255, 0), 1); imgDbgCleanStages.push_back(cleanImg); } } getTime(&startTime); filterEdgeBoxes(charAnalysis->thresholds, candidateBoxes, biggestCharWidth, avgCharHeight); candidateBoxes = filterMostlyEmptyBoxes(charAnalysis->thresholds, candidateBoxes); candidateBoxes = combineCloseBoxes(candidateBoxes, biggestCharWidth); cleanCharRegions(charAnalysis->thresholds, candidateBoxes); cleanMostlyFullBoxes(charAnalysis->thresholds, candidateBoxes); //cleanBasedOnColor(thresholds, colorFilter.colorMask, candidateBoxes); candidateBoxes = filterMostlyEmptyBoxes(charAnalysis->thresholds, candidateBoxes); this->characters = candidateBoxes; if (config->debugTiming) { timespec endTime; getTime(&endTime); cout << " -- Character Segmentation Box cleaning/filtering Time: " << diffclock(startTime, endTime) << "ms." << endl; } if (this->config->debugCharSegmenter) { Mat imgDash = drawImageDashboard(charAnalysis->thresholds, CV_8U, 3); displayImage(config, "Segmentation after cleaning", imgDash); Mat generalDash = drawImageDashboard(this->imgDbgGeneral, this->imgDbgGeneral[0].type(), 2); displayImage(config, "Segmentation General", generalDash); Mat cleanImgDash = drawImageDashboard(this->imgDbgCleanStages, this->imgDbgCleanStages[0].type(), 3); displayImage(config, "Segmentation Clean Filters", cleanImgDash); } } if (config->debugTiming) { timespec endTime; getTime(&endTime); cout << "Character Segmenter Time: " << diffclock(startTime, endTime) << "ms." << endl; } }
QRectF QgsPaintEffect::imageBoundingRect( const QgsRenderContext &context ) const { return boundingRect( mPicture->boundingRect(), context ); }
void CharacterSegmenter::cleanCharRegions(vector<Mat> thresholds, vector<Rect> charRegions) { const float MIN_SPECKLE_HEIGHT_PERCENT = 0.13; const float MIN_SPECKLE_WIDTH_PX = 3; const float MIN_CONTOUR_AREA_PERCENT = 0.1; const float MIN_CONTOUR_HEIGHT_PERCENT = 0.60; Mat mask = getCharBoxMask(thresholds[0], charRegions); for (int i = 0; i < thresholds.size(); i++) { bitwise_and(thresholds[i], mask, thresholds[i]); vector<vector<Point> > contours; Mat tempImg(thresholds[i].size(), thresholds[i].type()); thresholds[i].copyTo(tempImg); //Mat element = getStructuringElement( 1, // Size( 2 + 1, 2+1 ), // Point( 1, 1 ) ); //dilate(thresholds[i], tempImg, element); //morphologyEx(thresholds[i], tempImg, MORPH_CLOSE, element); //drawAndWait(&tempImg); findContours(tempImg, contours, RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); for (int j = 0; j < charRegions.size(); j++) { const float MIN_SPECKLE_HEIGHT = ((float)charRegions[j].height) * MIN_SPECKLE_HEIGHT_PERCENT; const float MIN_CONTOUR_AREA = ((float)charRegions[j].area()) * MIN_CONTOUR_AREA_PERCENT; int tallestContourHeight = 0; float totalArea = 0; for (int c = 0; c < contours.size(); c++) { if (contours[c].size() == 0) continue; if (charRegions[j].contains(contours[c][0]) == false) continue; Rect r = boundingRect(contours[c]); if (r.height <= MIN_SPECKLE_HEIGHT || r.width <= MIN_SPECKLE_WIDTH_PX) { // Erase this speckle drawContours(thresholds[i], contours, c, Scalar(0,0,0), CV_FILLED); if (this->config->debugCharSegmenter) { drawContours(imgDbgCleanStages[i], contours, c, COLOR_DEBUG_SPECKLES, CV_FILLED); } } else { if (r.height > tallestContourHeight) tallestContourHeight = r.height; totalArea += contourArea(contours[c]); } //else if (r.height > tallestContourHeight) //{ // tallestContourIndex = c; // tallestContourHeight = h; //} } if (totalArea < MIN_CONTOUR_AREA) { // Character is not voluminous enough. Erase it. if (this->config->debugCharSegmenter) { cout << "Character CLEAN: (area) removing box " << j << " in threshold " << i << " -- Area " << totalArea << " < " << MIN_CONTOUR_AREA << endl; Rect boxTop(charRegions[j].x, charRegions[j].y - 10, charRegions[j].width, 10); rectangle(imgDbgCleanStages[i], boxTop, COLOR_DEBUG_MIN_AREA, -1); } rectangle(thresholds[i], charRegions[j], Scalar(0, 0, 0), -1); } else if (tallestContourHeight < ((float) charRegions[j].height * MIN_CONTOUR_HEIGHT_PERCENT)) { // This character is too short. Black the whole thing out if (this->config->debugCharSegmenter) { cout << "Character CLEAN: (height) removing box " << j << " in threshold " << i << " -- Height " << tallestContourHeight << " < " << ((float) charRegions[j].height * MIN_CONTOUR_HEIGHT_PERCENT) << endl; Rect boxBottom(charRegions[j].x, charRegions[j].y + charRegions[j].height, charRegions[j].width, 10); rectangle(imgDbgCleanStages[i], boxBottom, COLOR_DEBUG_MIN_HEIGHT, -1); } rectangle(thresholds[i], charRegions[j], Scalar(0, 0, 0), -1); } } Mat closureElement = getStructuringElement( 1, Size( 2 + 1, 2+1 ), Point( 1, 1 ) ); //morphologyEx(thresholds[i], thresholds[i], MORPH_OPEN, element); //dilate(thresholds[i], thresholds[i], element); //erode(thresholds[i], thresholds[i], element); morphologyEx(thresholds[i], thresholds[i], MORPH_CLOSE, closureElement); // Lastly, draw a clipping line between each character boxes for (int j = 0; j < charRegions.size(); j++) { line(thresholds[i], Point(charRegions[j].x - 1, charRegions[j].y), Point(charRegions[j].x - 1, charRegions[j].y + charRegions[j].height), Scalar(0, 0, 0)); line(thresholds[i], Point(charRegions[j].x + charRegions[j].width + 1, charRegions[j].y), Point(charRegions[j].x + charRegions[j].width + 1, charRegions[j].y + charRegions[j].height), Scalar(0, 0, 0)); } } }
void CvScan::charsSegement( IplImage *src, vector<Mat> &vector){ if (src == NULL) { return; } IplImage *pimg = cvCreateImage(cvSize(src->width*1.1, src->height*1.1), src->depth, src->nChannels); /* int m_otsu = otsu(pimg); printf("m_otsu:%d\n",m_otsu); cvReleaseImage(&pimg); pimg = cvCreateImage(cvGetSize(src), src->depth, src->nChannels); cvThreshold(src, pimg, m_otsu, 255, CV_THRESH_BINARY); //cvZero(pimg); //*/ //IplImage imgHSV = *cvCreateImage(cvGetSize(pimg), 8, 1); //cv::Mat matImg(&imgHSV,true); cv::Mat img_contours(pimg->width,pimg->height,CV_8UC1,Scalar::all(0)); img_contours.data = (uchar *)pimg->imageData; std::vector< std::vector< CvPoint> > contours; findContours(img_contours, contours, // a vector of contours CV_RETR_EXTERNAL, // retrieve the external contours CV_CHAIN_APPROX_NONE); // all pixels of each contours //Start to iterate to each contour founded std::vector<std::vector<CvPoint>>::iterator itc = contours.begin(); std::vector<CvRect> vecRect; //Remove patch that are no inside limits of aspect ratio and area. //将不符合特定尺寸的图块排除出去 while (itc != contours.end()){ Rect mr = boundingRect(cv::Mat(*itc)); cv::Mat auxRoi(img_contours, mr); if (verifyMatCharSizes(auxRoi)) vecRect.push_back(mr); ++itc; } if (vecRect.size() == 0) return ; std::vector<CvRect> sortedRect; ////对符合尺寸的图块按照从左到右进行排序 sortRect(vecRect, sortedRect); for (int i = 0; i < sortedRect.size(); i++){ CvRect mr = sortedRect[i]; cv::Mat auxRoi(img_contours, mr); auxRoi = preprocessChar(auxRoi); vector.push_back(auxRoi); } /* 另一个方法 //*/ return ; }
vector<Rect> CharacterSegmenter::filterMostlyEmptyBoxes(vector<Mat> thresholds, const vector<Rect> charRegions) { // Of the n thresholded images, if box 3 (for example) is empty in half (for example) of the thresholded images, // clear all data for every box #3. //const float MIN_AREA_PERCENT = 0.1; const float MIN_CONTOUR_HEIGHT_PERCENT = 0.65; Mat mask = getCharBoxMask(thresholds[0], charRegions); vector<int> boxScores(charRegions.size()); for (int i = 0; i < charRegions.size(); i++) boxScores[i] = 0; for (int i = 0; i < thresholds.size(); i++) { for (int j = 0; j < charRegions.size(); j++) { //float minArea = charRegions[j].area() * MIN_AREA_PERCENT; Mat tempImg = Mat::zeros(thresholds[i].size(), thresholds[i].type()); rectangle(tempImg, charRegions[j], Scalar(255,255,255), CV_FILLED); bitwise_and(thresholds[i], tempImg, tempImg); vector<vector<Point> > contours; findContours(tempImg, contours, RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); float biggestContourHeight = 0; vector<Point> allPointsInBox; for (int c = 0; c < contours.size(); c++) { if (contours[c].size() == 0) continue; for (int z = 0; z < contours[c].size(); z++) allPointsInBox.push_back(contours[c][z]); } float height = 0; if (allPointsInBox.size() > 0) { height = boundingRect(allPointsInBox).height; } if (height >= ((float) charRegions[j].height * MIN_CONTOUR_HEIGHT_PERCENT)) { boxScores[j] = boxScores[j] + 1; } else if (this->config->debugCharSegmenter) { drawX(imgDbgCleanStages[i], charRegions[j], COLOR_DEBUG_EMPTYFILTER, 3); } } } vector<Rect> newCharRegions; int maxBoxScore = 0; for (int i = 0; i < charRegions.size(); i++) { if (boxScores[i] > maxBoxScore) maxBoxScore = boxScores[i]; } // Need a good char sample in at least 50% of the boxes for it to be valid. int MIN_FULL_BOXES = maxBoxScore * 0.49; // Now check each score. If it's below the minimum, remove the charRegion for (int i = 0; i < charRegions.size(); i++) { if (boxScores[i] > MIN_FULL_BOXES) newCharRegions.push_back(charRegions[i]); else { // Erase the box from the Mat... mainly for debug purposes if (this->config->debugCharSegmenter) { cout << "Mostly Empty Filter: box index: " << i; cout << " this box had a score of : " << boxScores[i];; cout << " MIN_FULL_BOXES: " << MIN_FULL_BOXES << endl;; for (int z = 0; z < thresholds.size(); z++) { rectangle(thresholds[z], charRegions[i], Scalar(0,0,0), -1); drawX(imgDbgCleanStages[z], charRegions[i], COLOR_DEBUG_EMPTYFILTER, 1); } } } if (this->config->debugCharSegmenter) cout << " Box Score: " << boxScores[i] << endl; } return newCharRegions; }
/*! \brief Draw the contents inside the frame QColorGroup::Background is the background color outside of the frame. QColorGroup::Base is the background color inside the frame. QColorGroup::Foreground is the background color inside the scale. \param painter Painter \sa QwtDial::boundingRect, QwtDial::contentsRect, QwtDial::scaleContentsRect, QWidget::setPalette */ void QwtDial::drawContents(QPainter *painter) const { if ( backgroundMode() == NoBackground || colorGroup().brush(QColorGroup::Base) != colorGroup().brush(QColorGroup::Background) ) { // Don´t use QPainter::drawEllipse. There are some pixels // different compared to the region in the mask, leaving // them in background color. painter->save(); painter->setPen(Qt::NoPen); painter->setBrush(colorGroup().brush(QColorGroup::Base)); // Even if we want to fill the contentsRect only, we fill the // complete boundingRect. The frame will be painted later // above, but we want to have the base color below it // because round objects doesn´t cover all pixels. QRect br = boundingRect(); #if QT_VERSION < 300 #ifdef _WS_WIN32_ // Qt-230-NC draws ellipses not as nicely as Qt-2.3.x on X Windows br.setTop(br.top()-1); br.setLeft(br.left()-1); br.setBottom(br.bottom()+1); br.setRight(br.right()+1); #endif #endif painter->setClipRegion(QRegion(painter->xForm(br), QRegion::Ellipse)); painter->drawRect(br); painter->restore(); } const QRect insideScaleRect = scaleContentsRect(); if ( colorGroup().brush(QColorGroup::Foreground) != colorGroup().brush(QColorGroup::Base) ) { painter->save(); painter->setPen(Qt::NoPen); painter->setBrush(colorGroup().brush(QColorGroup::Foreground)); painter->setClipRegion( QRegion(painter->xForm(insideScaleRect), QRegion::Ellipse)); painter->drawRect(insideScaleRect); painter->restore(); } const QPoint center = insideScaleRect.center(); const int radius = insideScaleRect.width() / 2; painter->save(); drawScaleContents(painter, center, radius); painter->restore(); double direction = d_origin; if (isValid()) { direction = d_origin + d_minScaleArc; if ( maxValue() > minValue() && d_maxScaleArc > d_minScaleArc ) { const double ratio = (value() - minValue()) / (maxValue() - minValue()); direction += ratio * (d_maxScaleArc - d_minScaleArc); } if ( direction >= 360.0 ) direction -= 360.0; } double origin = d_origin; if ( mode() == RotateScale ) { origin -= direction - d_origin; direction = d_origin; } painter->save(); drawScale(painter, center, radius, origin, d_minScaleArc, d_maxScaleArc); painter->restore(); if ( isValid() ) { QPalette::ColorGroup cg; if ( isEnabled() ) cg = hasFocus() ? QPalette::Active : QPalette::Inactive; else cg = QPalette::Disabled; painter->save(); drawNeedle(painter, center, radius, direction, cg); painter->restore(); } }
void AbstractFigure::move(const QPoint& delta) { center += delta; update(boundingRect()); }
void HoverPoints::movePoint(int index, const QPointF &point, bool emitUpdate) { m_points[index] = bound_point(point, boundingRect(), m_locks.at(index)); if (emitUpdate) firePointChange(); }
void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { ServerInfo_User *info = owner->getUserInfo(); const qreal border = 2; QRectF avatarBoundingRect = boundingRect().adjusted(border, border, -border, -border); QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect); QSize translatedSize = translatedRect.size().toSize(); QPixmap cachedPixmap; const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" + QString::number(info->getUserLevel()) + "_" + QString::number(fullPixmap.cacheKey()); #if QT_VERSION >= 0x040600 if (!QPixmapCache::find(cacheKey, &cachedPixmap)) { #else if (!QPixmapCache::find(cacheKey, cachedPixmap)) { #endif cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height()); QPainter tempPainter(&cachedPixmap); QRadialGradient grad(translatedRect.center(), sqrt(translatedSize.width() * translatedSize.width() + translatedSize.height() * translatedSize.height()) / 2); grad.setColorAt(1, Qt::black); grad.setColorAt(0, QColor(180, 180, 180)); tempPainter.fillRect(QRectF(0, 0, translatedSize.width(), translatedSize.height()), grad); QPixmap tempPixmap; if (fullPixmap.isNull()) tempPixmap = UserLevelPixmapGenerator::generatePixmap(translatedSize.height(), info->getUserLevel()); else tempPixmap = fullPixmap.scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); tempPainter.drawPixmap((translatedSize.width() - tempPixmap.width()) / 2, (translatedSize.height() - tempPixmap.height()) / 2, tempPixmap); QPixmapCache::insert(cacheKey, cachedPixmap); } painter->save(); painter->resetTransform(); painter->translate((translatedSize.width() - cachedPixmap.width()) / 2.0, 0); painter->drawPixmap(translatedRect, cachedPixmap, cachedPixmap.rect()); painter->restore(); QRectF nameRect = QRectF(0, boundingRect().height() - 20, 110, 20); painter->fillRect(nameRect, QColor(0, 0, 0, 160)); QRectF translatedNameRect = painter->combinedTransform().mapRect(nameRect); painter->save(); painter->resetTransform(); QString name = info->getName(); if (name.size() > 13) name = name.mid(0, 10) + "..."; QFont font; font.setPixelSize(qMax((int) round(translatedNameRect.height() / 1.5), 9)); painter->setFont(font); painter->setPen(Qt::white); painter->drawText(translatedNameRect, Qt::AlignVCenter | Qt::AlignLeft, " " + name); painter->restore(); QPen pen(QColor(100, 100, 100)); pen.setWidth(border); pen.setJoinStyle(Qt::RoundJoin); painter->setPen(pen); painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2)); if (getBeingPointedAt()) painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100))); } AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, int _value) { if (playerCounter) return 0; playerCounter = new PlayerCounter(owner, _counterId, _name, _value, this); playerCounter->setPos(boundingRect().width() - playerCounter->boundingRect().width(), boundingRect().height() - playerCounter->boundingRect().height()); connect(playerCounter, SIGNAL(destroyed()), this, SLOT(delCounter())); return playerCounter; } void PlayerTarget::delCounter() { playerCounter = 0; }
void CachedSvgItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { if (painter->paintEngine()->type() != QPaintEngine::OpenGL && painter->paintEngine()->type() != QPaintEngine::OpenGL2) { // Fallback to direct painting QGraphicsSvgItem::paint(painter, option, widget); return; } QRectF br = boundingRect(); QTransform transform = painter->worldTransform(); qreal sceneScale = transform.map(QLineF(0, 0, 1, 0)).length(); bool stencilTestEnabled = glIsEnabled(GL_STENCIL_TEST); bool scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST); painter->beginNativePainting(); if (stencilTestEnabled) { glEnable(GL_STENCIL_TEST); } if (scissorTestEnabled) { glEnable(GL_SCISSOR_TEST); } bool dirty = false; if (!m_texture) { glGenTextures(1, &m_texture); m_context = const_cast<QGLContext *>(QGLContext::currentContext()); dirty = true; } if (!qFuzzyCompare(sceneScale, m_scale)) { m_scale = sceneScale; dirty = true; } int textureWidth = (int(br.width() * m_scale) + 3) & ~3; int textureHeight = (int(br.height() * m_scale) + 3) & ~3; if (dirty) { // qDebug() << "re-render image"; QImage img(textureWidth, textureHeight, QImage::Format_ARGB32); { img.fill(Qt::transparent); QPainter p; p.begin(&img); p.setRenderHints(painter->renderHints()); p.translate(br.topLeft()); p.scale(m_scale, m_scale); QGraphicsSvgItem::paint(&p, option, 0); p.end(); img = img.rgbSwapped(); } glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_texture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glDisable(GL_TEXTURE_2D); dirty = false; } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_texture); // texture may be slightly large than svn image, ensure only used area is rendered qreal tw = br.width() * m_scale / textureWidth; qreal th = br.height() * m_scale / textureHeight; glBegin(GL_QUADS); glTexCoord2d(0, 0); glVertex3d(br.left(), br.top(), -1); glTexCoord2d(tw, 0); glVertex3d(br.right(), br.top(), -1); glTexCoord2d(tw, th); glVertex3d(br.right(), br.bottom(), -1); glTexCoord2d(0, th); glVertex3d(br.left(), br.bottom(), -1); glEnd(); glDisable(GL_TEXTURE_2D); painter->endNativePainting(); }
void Graph::DrawBackground(QSGNode * rootNode) { QSGSimpleRectNode * node = new QSGSimpleRectNode(boundingRect(), m_color); rootNode->appendChildNode(node); }
QVariant HandleItem::itemChange( GraphicsItemChange change, const QVariant &data ) { if ( change == ItemPositionChange && m_pressed ) { QPointF newData = data.toPointF(); QRectF newRect = m_item->rect(); QPointF movement = newData - pos(); switch ( m_role ) { case RightHandle: { // Prevent the rectangle from collapsing. if ( newRect.width() + movement.x() <= MinSize ) { newRect.setWidth(MinSize); m_item->setRect(newRect); newData.setX(m_item->boundingRect().x() + MinSize/2); newData.setY(pos().y()); } else { // Snap the movement to the X direction newData.setY(m_item->rect().y() + m_item->rect().height() / 2 - HandleRadius); // Resize the rectangle newRect.setRight(m_item->rect().right() + movement.x()); m_item->setRect(newRect); } break; } case LeftHandle: { // Prevent the rectangle from collapsing if ( newRect.width() - movement.x() <= MinSize ) { newRect.setLeft(newRect.right() - MinSize); //float oldLeft = m_item->rect().left(); //newRect.setWidth(MinSize); //newRect.setLeft(oldLeft); m_item->setRect(newRect); newData.setX(m_item->boundingRect().x() - MinSize / 2); newData.setY(pos().y()); } else { // Snap the movement to the X direction newData.setY(m_item->rect().y() + m_item->rect().height() / 2 - HandleRadius); // Resize the rectangle newRect.setLeft(m_item->rect().left() + movement.x()); m_item->setRect(newRect); } break; } case TopHandle: { // Prevent the rectangle from collapsing. if ( newRect.height() - movement.y() <= MinSize ) { newRect.setTop(newRect.bottom() - MinSize); //newRect.setHeight(MinSize); m_item->setRect(newRect); newData.setX(pos().x()); newData.setY(m_item->boundingRect().y() - boundingRect().height() / 2); // + m_item->boundingRect().height()); } else { // Snap the movement to the Y direction newData.setX(m_item->rect().x() + m_item->rect().width() / 2 - HandleRadius); // Resize the rectangle newRect.setTop(m_item->rect().top() + movement.y()); m_item->setRect(newRect); } break; } case BottomHandle: { // Prevent the rectangle from collapsing. if ( newRect.height() + movement.y() <= MinSize ) { newRect.setBottom(newRect.top() + MinSize); m_item->setRect(newRect); newData.setX(pos().x()); newData.setY(m_item->boundingRect().y() + boundingRect().height() / 2); } else { // Snap the movement to the Y direction newData.setX(m_item->rect().x() + m_item->rect().width() / 2 - HandleRadius); // Resize the rectangle newRect.setBottom(m_item->rect().bottom() + movement.y()); m_item->setRect(newRect); } break; } case CenterHandle: { //m_item->translate(movement.x(), movement.y()); QRectF rect = m_item->rect(); rect.setX(rect.x() + movement.x()); rect.setY(rect.y() + movement.y()); rect.setWidth(rect.width() + movement.x()); rect.setHeight(rect.height() + movement.y()); m_item->setRect(rect); break; } } // end switch emit Changed(); return QGraphicsItem::itemChange( change, newData ); } // end if pressed return QGraphicsItem::itemChange( change, data ); }
void TextureBuilderTexture::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setPen(QPen(QColor(0,0,0,255))); painter->fillRect(boundingRect(),QBrush(QColor(255,255,255,255))); painter->drawRect(boundingRect()); }