Skip to content
Snippets Groups Projects
petrack.cpp 175 KiB
Newer Older
d.kilic's avatar
d.kilic committed
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
    mControlWidget->mapNr->setMinimum(0);
    mControlWidget->mapNr->setMaximum(0);
    mControlWidget->mapX->setValue(0);
    mControlWidget->mapY->setValue(0);
    mControlWidget->mapW->setValue(0);
    mControlWidget->mapH->setValue(0);
    mControlWidget->mapColor->setCheckState(Qt::Checked);
    mControlWidget->mapHeight->setValue(180);
//    mControlWidget->colorPlot->replot();
    mControlWidget->mapDefaultHeight->setValue(180);

    ///
    /// tracking params
    ///
    mControlWidget->trackOnlineCalc->setCheckState(Qt::Checked);
    mControlWidget->trackRepeat->setCheckState(Qt::Checked);
    mControlWidget->trackRepeatQual->setValue(50);
    mControlWidget->trackExtrapolation->setCheckState(Qt::Checked);
    mControlWidget->trackMerge->setCheckState(Qt::Unchecked);
    mControlWidget->trackOnlyVisible->setCheckState(Qt::Checked);
    getTrackRoiItem()->setRect(0,0,0,0);

    // export options
    mControlWidget->trackMissingFrames->setCheckState(Qt::Checked);
    mControlWidget->trackRecalcHeight->setCheckState(Qt::Checked);
    mControlWidget->trackAlternateHeight->setCheckState(Qt::Unchecked);
    mControlWidget->exportElimTp->setCheckState(Qt::Unchecked);
    mControlWidget->exportElimTrj->setCheckState(Qt::Unchecked);
    mControlWidget->exportSmooth->setCheckState(Qt::Checked);
    mControlWidget->exportViewDir->setCheckState(Qt::Unchecked);
    mControlWidget->exportAngleOfView->setCheckState(Qt::Unchecked);
    mControlWidget->exportUseM->setCheckState(Qt::Unchecked);
    mControlWidget->exportComment->setCheckState(Qt::Unchecked);
    mControlWidget->exportMarkerID->setCheckState(Qt::Unchecked);

    // test options
    mControlWidget->testEqual->setCheckState(Qt::Checked);
    mControlWidget->testVelocity->setCheckState(Qt::Checked);
    mControlWidget->testInside->setCheckState(Qt::Checked);
    mControlWidget->testLength->setCheckState(Qt::Checked);
    setTrackFileName(NULL);

    // search region
    mControlWidget->trackRegionScale->setValue(16);
    mControlWidget->trackRegionLevels->setValue(3);
    mControlWidget->trackErrorExponent->setValue(0);
    mControlWidget->trackShowSearchSize->setCheckState(Qt::Unchecked);

    // path params
    mControlWidget->trackShow->setCheckState(Qt::Checked);
    mControlWidget->trackFix->setCheckState(Qt::Unchecked);

    mControlWidget->trackShowOnlyVisible->setCheckState(Qt::Unchecked);
    mControlWidget->trackShowOnly->setCheckState(Qt::Unchecked);
    mControlWidget->trackShowOnlyNr->setValue(1);
    mControlWidget->trackShowOnlyList->setCheckState(Qt::Unchecked);
    mControlWidget->trackShowOnlyNrList->setEnabled(false);
    mControlWidget->trackShowOnlyListButton->setEnabled(false);

    mControlWidget->trackShowCurrentPoint->setCheckState(Qt::Checked);
    mControlWidget->trackShowPoints->setCheckState(Qt::Unchecked);
    mControlWidget->trackShowPath->setCheckState(Qt::Checked);
    mControlWidget->trackShowColColor->setCheckState(Qt::Checked);
    mControlWidget->trackShowColorMarker->setCheckState(Qt::Checked);
    mControlWidget->trackShowNumber->setCheckState(Qt::Checked);
    mControlWidget->trackShowGroundPosition->setCheckState(Qt::Unchecked);
    mControlWidget->trackShowGroundPath->setCheckState(Qt::Unchecked);

    mControlWidget->setTrackPathColor(Qt::red);
    mControlWidget->setTrackGroundPathColor(Qt::green);
    mControlWidget->trackHeadSized->setCheckState(Qt::Checked);
    mControlWidget->trackCurrentPointSize->setValue(60);
    mControlWidget->trackPointSize->setValue(7);
    mControlWidget->trackPathWidth->setValue(2);
    mControlWidget->trackColColorSize->setValue(11);
    mControlWidget->trackColorMarkerSize->setValue(14);
    mControlWidget->trackNumberSize->setValue(14);
    mControlWidget->trackGroundPositionSize->setValue(1);
    mControlWidget->trackGroundPathSize->setValue(1);

    mControlWidget->trackShowPointsColored->setCheckState(Qt::Checked);
    mControlWidget->trackNumberBold->setCheckState(Qt::Checked);
    mControlWidget->trackShowBefore->setValue(15);
    mControlWidget->trackShowAfter->setValue(15);

    /// analysis params
    mControlWidget->anaMissingFrames->setCheckState(Qt::Checked);
    mControlWidget->anaMarkAct->setCheckState(Qt::Unchecked);
    mControlWidget->anaStep->setValue(25);
    mControlWidget->anaConsiderX->setCheckState(Qt::Unchecked);
    mControlWidget->anaConsiderY->setCheckState(Qt::Checked);
    mControlWidget->anaConsiderAbs->setCheckState(Qt::Unchecked);
    mControlWidget->anaConsiderRev->setCheckState(Qt::Unchecked);
    mControlWidget->showVoronoiCells->setCheckState(Qt::Unchecked);

//    updateImage();

}

void Petrack::setStatusStereo(float x, float y, float z)
{
    if (mStatusLabelStereo)
    {
        if (z<0)
            mStatusLabelStereo->setText(QString("x= novalue  y= novalue  z= novalue  "));
        else
            mStatusLabelStereo->setText(QString("x=%1cm  y=%2cm  z=%3cm  ").arg(x, 6, 'f', 1).arg(y, 6, 'f', 1).arg(z, 6, 'f', 1));
    }
}

void Petrack::setStatusTime()
{
    if (mStatusLabelTime)
        mStatusLabelTime->setText(mAnimation->getTimeString());
}

void Petrack::setStatusFPS()
{
    if (mStatusLabelFPS)
    {
        mStatusLabelFPS->setText(QString("%1fps  ").arg(mShowFPS, 5, 'f', 1));

        QPalette pal = mStatusLabelFPS->palette(); // static moeglich?
        QColor color;//(qRed(col), qGreen(col), qBlue(col));

        double diff = mShowFPS-mAnimation->getFPS();
        int opacity = mPlayerWidget->getPlayerSpeedFixed() ? 128 : 20;

        if( diff < -6 ) // very slow ==> red
            color.setRgb(200,0,0,opacity);//mStatusLabelFPS->setStyleSheet("background-color: rgba(200,0,0,20);");// border-style: outset; border-width: 1px; border-color: yellow;");//, qRgba(250,0,0,50));//Qt::yellow);
        else if( diff < -2 ) // better ==> yellow
            color.setRgb(200,200,0,opacity);//mStatusLabelFPS->setStyleSheet("background-color: rgba(200,200,0,20);");// border-style: outset; border-width: 1px; border-color: yellow;");//, qRgba(250,0,0,50));//Qt::yellow);
        else if (diff > -2) // nearly ok ==> green
            color.setRgb(0,200,0,opacity);//mStatusLabelFPS->setStyleSheet("background-color: rgba(0,200,0,20);");// border-style: outset; border-width: 1px; border-color: red;");//, qRgba(250,0,0,50));//Qt::yellow);

        pal.setColor(QPalette::Window, color);
//        pal.setColor(QPalette::WindowText,mPlayerWidget->getPlayerSpeedFixed() ? QColor(100,100,100) : QColor(0,0,0));
        //        pal.setBrush(QPalette::WindowText, mPlayerWidget->getPlayerSpeedFixed() ? QBrush(QColor(50,50,50),Qt::Dense2Pattern) : QBrush(QColor(0,0,0),Qt::SolidPattern));

        mStatusLabelFPS->setPalette(pal);
    }
}
void Petrack::setShowFPS(double fps)
{
    if ((fps == 0.) || (mShowFPS == 0))
        mShowFPS = fps;
    else
        mShowFPS = mShowFPS*.9+fps*.1; // glaetten durch Hinzunahme des alten Wertes
    setStatusFPS();
}

void Petrack::updateShowFPS()
{
    static clock_t lastTime = -1;

    if (mPlayerWidget->getPaused()) //(!imageChanged)
    {
        setShowFPS(0.);
        lastTime = -1;
    }
    else
    {
        //            int milliSec = updateTime.restart();
        //            if (milliSec != 0)
        //                mShowFPS = 1000./milliSec;
        //            updateTime.start();

        if (lastTime != -1)
            if ((lastTime = clock()-lastTime) != 0)
                setShowFPS(CLOCKS_PER_SEC / ((double)(lastTime)));
        lastTime = clock();
    }
}

// ohne neue positionsangabe, sinnvoll, wenn berechnungsweise sich in getPosReal geaendert hat
// gebraucht in control.cpp
void Petrack::setStatusPosReal() // pos in cm
{
    if (mImageItem)
        setStatusPosReal(mImageItem->getPosReal(mMousePosOnImage, getStatusPosRealHeight()));
}
void Petrack::setStatusPosReal(const QPointF &pos) // pos in cm
{
    if (mStatusLabelPosReal)
    {
        QChar deg(0xB0);
        QString labelText = QString(" cm from ground:%1cm,%2cm,%3").arg(pos.x(), 6, 'f', 1).arg(pos.y(), 6, 'f', 1).arg(
                                    getImageItem()->getAngleToGround(mMousePosOnImage.x(), mMousePosOnImage.y(), getStatusPosRealHeight()), 5, 'f', 1);
        labelText.append(deg);
        mStatusLabelPosReal->setText(labelText);
    }
}
void Petrack::setStatusPos(const QPoint &pos) // pos in pixel
{
    mStatusLabelPos->setText(QString("%1x%2").arg(pos.x(), 4).arg(pos.y(), 4));
}
void Petrack::setStatusColor(const QRgb &col)
{
    QString s("#%1%2%3"); // static moeglich?
    s = s.arg(qRed(col), 2, 16, QChar('0')).arg(qGreen(col), 2, 16, QChar('0')).arg(qBlue(col), 2, 16, QChar('0'));
    if ((qRed(col)+qGreen(col)+qBlue(col))/3 < 128)
        mStatusLabelColor->setText(QString("<font color=\"#ffffff\">&nbsp;%1</font>").arg(s));
    else
        mStatusLabelColor->setText(QString("<font color=\"#000000\">&nbsp;%1</font>").arg(s));

    //     mStatusLabelColor->setBackgroundRole(QPalette::Text);
    QPalette pal = mStatusLabelColor->palette(); // static moeglich?
    QColor color(qRed(col), qGreen(col), qBlue(col));

    pal.setColor(QPalette::Window, color);
    mStatusLabelColor->setPalette(pal);

    mControlWidget->getColorPlot()->setCursor(color);
    mControlWidget->getColorPlot()->replot();

    //debout << "QColor: " << color << " height: " << mControlWidget->getColorPlot()->map(color) << endl;
}
void Petrack::setStatusColor()
{
    QPointF pos = getMousePosOnImage();
    if ((int)(pos.x())<mImage->width() && (int)(pos.y())<mImage->height())
    {
        QPoint pos2((int)(pos.x()), (int)(pos.y())); // .toPoint() ???
        setStatusColor(mImage->pixel(pos2));
    }
    //     else
    //         setStatusColor(qRgb(255, 255, 255));
}

double Petrack::getStatusPosRealHeight()
{
    if (mStatusPosRealHeight)
        return mStatusPosRealHeight->value();
    else
        return 0.;
}

void Petrack::readSettings()
{
    QSettings settings("Forschungszentrum Juelich GmbH", "PeTrack by Maik Boltes, Daniel Salden");
    QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
    QSize size = settings.value("size", QSize(400, 400)).toSize();
    mAntialiasAct->setChecked(settings.value("antialias", false).toBool());
    mOpenGLAct->setChecked(settings.value("opengl", false).toBool());
    mSeqFileName = settings.value("seqFileName", QDir::currentPath()).toString();
    mProFileName = settings.value("proFilePath", QDir::currentPath()).toString();
    // nicht ganz sauber, da so immer schon zu anfang in calib file list etwas drin steht und somit auto ausgefuehrt werden kann
    // wird aber beim ersten openCalib... ueberschrieben
    mAutoCalib.addCalibFile(settings.value("calibFile", QDir::currentPath()).toString());
    resize(size);
    move(pos);
    antialias();
    opengl();
}

void Petrack::writeSettings()
{
    QSettings settings("Forschungszentrum Juelich GmbH", "PeTrack by Maik Boltes, Daniel Salden");
    settings.setValue("pos", pos());
    settings.setValue("size", size());
    settings.setValue("antialias", mAntialiasAct->isChecked());
    settings.setValue("opengl", mOpenGLAct->isChecked());
    settings.setValue("seqFileName", mSeqFileName);
    settings.setValue("proFilePath", QFileInfo(mProFileName).path()); // nur path, damit bei saveCurrentProject
    if (!mAutoCalib.isEmptyCalibFiles()) //!mCalibFiles.isEmpty()
        settings.setValue("calibFile", mAutoCalib.getCalibFile(0));
}

bool Petrack::maybeSave()
{
    int ret = QMessageBox::warning(this, tr("PeTrack"),
                                   tr("Do you want to save\n"
                                      "the current project?\n"
                                      "Be sure to save trajectories, background\n"
                                      "and 3D calibration point separately!"),
                                   QMessageBox::Yes | QMessageBox::Default,
                                   QMessageBox::No,
                                   QMessageBox::Cancel | QMessageBox::Escape);

    if (ret == QMessageBox::Yes)
    {
        if (saveSameProject())
            return true;
        else
            return false;
    }
    else if (ret == QMessageBox::Cancel)
        return false;
    else
        return true;
}

void Petrack::closeEvent(QCloseEvent *event)
{

    if (maybeSave())
    {
        writeSettings();
        event->accept();
    }
    else
        event->ignore();

}

void Petrack::setMousePosOnImage(QPointF pos)
{
    if (mImage)
    {
        mMousePosOnImage = pos;
        // real coordinate
        setStatusPosReal(mImageItem->getPosReal(pos, getStatusPosRealHeight()));

        // pixel coordinate
        //s.sprintf("%4dx%4d", event->pos().x(), event->pos().y());
        //QTextStream(&s) << event->pos().x() << "x" << event->pos().y();
        QPoint pos1((int)(pos.x())+1, (int)(pos.y())+1);
        setStatusPos(pos1);  //QString("%1x%2").arg((int)event->pos().x()+1, 4).arg((int)event->pos().y()+1, 4)
        //== event->scenePos().x()
        // Koordinaten auf dem Bildschirm: event->screenPos().x(), event->screenPos().y()
        
        // pixel color
        QPoint pos2((int)(pos.x()), (int)(pos.y()));
        setStatusColor(mImage->pixel(pos2));//(mImage->toImage()).pixel(pos... wenn pixmap

        //        if ((mStereoContext) && mStereoContext->getDisparity())
        //        {
        //        }
    }
}

void Petrack::keyPressEvent(QKeyEvent * event)
{
    switch (event->key()) {
    case Qt::Key_Left:
        mPlayerWidget->frameBackward();
        break;
    case Qt::Key_Right:
        mPlayerWidget->frameForward();
        break;
    case Qt::Key_Down:
        mViewWidget->zoomOut(1);
        break;
    case Qt::Key_Up:
        mViewWidget->zoomIn(1);
        break;
    case Qt::Key_Space:
        // space wird von buttons, wenn focus drauf ist als Aktivierung vorher abgegriffen und nicht durchgereicht
        mPlayerWidget->togglePlayPause();
        break;
    case Qt::Key_D:
//        debout << "test Key_D" << endl;
        break;
    default:
        ;
    }
//    QMainWindow::keyPressEvent(event);
}

void Petrack::mousePressEvent(QMouseEvent *event)
{
    // mouse click in fps status label ?
    if( event->pos().x() >= mStatusLabelFPS->pos().x() && event->pos().x() <= mStatusLabelFPS->pos().x()+mStatusLabelFPS->width() )
    {
        mPlayerWidget->togglePlayerSpeedFixed();
        setStatusFPS();
    }
}

// update control widget, if image size changed (especially because of changing border)
void Petrack::updateControlImage(Mat &img)
{

    // auch moeglich hoehe und breite von bild stat border veraenderungen zu checken
    static int lastBorderSize = -1;

    if( isLoading() )
        lastBorderSize = -1;

    int diffBorderSize=0;
    int iW = img.cols;
    int iH = img.rows;

    // wird auch nochmal in ImageWidget gemacht, aber ist hier frueher noetig
    double cX = mControlWidget->getCalibCxValue(); // merken, da min/max value verandernkann wenn aus dem rahmen
    double cY = mControlWidget->getCalibCyValue();

    mControlWidget->setCalibCxMin(0  /*iW/2.-50.*/);
    mControlWidget->setCalibCxMax(iW /*iW/2.+50.*/);
    mControlWidget->setCalibCyMin(0  /*iH/2.-50.*/);
    mControlWidget->setCalibCyMax(iH /*iH/2.+50.*/);

    if (mControlWidget->fixCenter->checkState() == Qt::Checked)
    {
        mControlWidget->setCalibCxValue((iW-1)/2.);
        mControlWidget->setCalibCyValue((iH-1)/2.);
    }
    else
    {
        if (lastBorderSize != -1)
            diffBorderSize = getImageBorderSize()-lastBorderSize;
        lastBorderSize = getImageBorderSize();

        mControlWidget->setCalibCxValue(cX+diffBorderSize);
        mControlWidget->setCalibCyValue(cY+diffBorderSize);
    }
}

void Petrack::importTracker(QString dest) //default = ""
{
    static QString lastFile;

    if (lastFile == "")
        lastFile = mTrcFileName;

    // if no destination file or folder is given
    if (dest.isEmpty())
    {
        dest = QFileDialog::getOpenFileName(this, tr("Select file for importing tracking pathes"), lastFile,
                                            tr("PeTrack tracker (*.trc *.txt);;All files (*.*)"));
    }
    // in control
    //     else
    //         dest = getExistingFile(dest); // ueberprueft die ;-getrennten Dateinamen auf existenz und gibt ersten zurueck - interessant fuer relativen und absoluten pfad

    if (!dest.isEmpty())
    {
        if (dest.right(4) == ".trc")
        {
            QFile file(dest);
            int i, sz;

            if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                // errorstring ist je nach Betriebssystem in einer anderen Sprache!!!!
                QMessageBox::critical(this, tr("PeTrack"), tr("Cannot open %1:\n%2").arg(dest).arg(file.errorString()));
                return;
            }

            setTrackChanged(true);// flag changes of track parameters
            mTracker->reset();

            QTextStream in(&file);
            TrackPerson tp;
            QString comment;

            bool ok; // shows if int stands in first line - that was in the first version of trc file
            QString firstLine = in.readLine();
            sz = firstLine.toInt(&ok);
            if (!ok)
            {
                if (firstLine.contains("version 4",Qt::CaseInsensitive))
                {
                    trcVersion = 4;
                }
                else if (firstLine.contains("version 3",Qt::CaseInsensitive))
d.kilic's avatar
d.kilic committed
                {
                    trcVersion = 3;
                }
                else if(firstLine.contains("version 2",Qt::CaseInsensitive))
d.kilic's avatar
d.kilic committed
                {
                    trcVersion = 2;
d.kilic's avatar
d.kilic committed
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
                {
                    debout << "Error: wrong header while reading TRC file." << endl;
                    sz = 0;
                }
                in >> sz;
            }
            else
                trcVersion = 1;

            if ((sz > 0) && (mTracker->size() != 0))
                debout << "Warning: Overlapping trajectories will be joined not until tracking adds new trackpoints." << endl;
            for (i = 0; i < sz; ++i)
            {
                if( trcVersion == 2)
                {
                    in >> tp;
                }else if( trcVersion >= 3)
                {

//                    in.skipWhiteSpace(); // skip white spaces for reading the comment line without this the reading makes some problems
//                    // Kommentarzeile lesen
//                    comment = in.readLine();
//                    // Kommentarzeichen entfernen - wird beim exportieren wieder hinzugefuegt
//                    if( comment.startsWith("#"))
//                    {
//                        comment = comment.remove(0,2);
//                    }
                    in >> tp;
//                    tp.setComment(comment);

                }
                mTracker->append(tp);
                tp.clear();  // loeschen, sonst immer weitere pfade angehangen werden
            }

            mControlWidget->trackNumberAll->setText(QString("%1").arg(mTracker->size()));
            mControlWidget->trackShowOnlyNr->setMaximum(MAX(mTracker->size(),1));
            mControlWidget->trackNumberVisible->setText(QString("%1").arg(mTracker->visible(mAnimation->getCurrentFrameNum())));
            mControlWidget->colorPlot->replot();
            file.close();
            debout << "import " << dest << " (" << sz << " person(s), file version " << trcVersion << ")" << endl;
            mTrcFileName = dest; // fuer Project-File, dann koennte track path direkt mitgeladen werden, wenn er noch da ist
        }else
        if (dest.right(4) == ".txt") // 3D Koordinaten als Tracking-Daten importieren Zeilenformat: Personennr, Framenr, x, y, z
        {
            QMessageBox::warning(this,tr("PeTrack"), tr("Are you sure you want to import 3D data from TXT-File? You have to make sure that the coordinate system now is exactly at the same position and orientation than at export time!"));

            QFile file(dest);
            // size of person list
            int sz = 0;

            if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                // errorstring ist je nach Betriebssystem in einer anderen Sprache!!!!
                QMessageBox::critical(this, tr("PeTrack"), tr("Cannot open %1:\n%2").arg(dest).arg(file.errorString()));
                return;
            }

            setTrackChanged(true);// flag changes of track parameters
            mTracker->reset();

            //mTrackerReal->reset(); ???

            QTextStream in(&file);
            TrackPerson tp;
            TrackPoint tPoint;
            Point2f p2d;

            QString line;
            QString headerline;
            bool exec_once_flag = false;
            double conversionFactorTo_cm = 1.0;
            int personNr = -1, frameNr = -1, current_personNr = 1;
            float x, y ,z;

            while( 1 )
            {

                // Falls Datei am Ende letzte Person abspeichern und Lese-Schleife beenden
                if( in.atEnd() )
                {
                    tp.setLastFrame(frameNr);
                    mTracker->append(tp);
                    ++sz;
                    tp.clear();
                    break;
                }

                line = in.readLine();

                // Kommentare ueberlesen
                if( line.startsWith("#",Qt::CaseInsensitive) )
                {
                    headerline = line;
                    continue;
                }

                // Test-Ausgabe
                //debout << line << endl;

                if ((!exec_once_flag) && (!headerline.contains("cm")))
                {
                    conversionFactorTo_cm = 100.0;
                    exec_once_flag = true;
                    QMessageBox::warning(this,tr("PeTrack"), tr("PeTrack will interpret position data as unit [m]. No header with [cm] found."));
                }

                QTextStream stream(&line);

                // Zeile als Stream einlesen Format: [id frame x y z]
                stream >> personNr
                       >> frameNr
                       >> x
                       >> y
                       >> z;

                // convert data to cm
                x = x * conversionFactorTo_cm;
                y = y * conversionFactorTo_cm;
                z = z * conversionFactorTo_cm;

                // 3-dimensionale Berechnung/Anzeige des Punktes
                if( mControlWidget->getCalibCoordDimension() == 0 )
                {
                    p2d = mExtrCalibration.getImagePoint(Point3f(x,y,z));
                }
                // 2-dimensionale Berechnung/Anzeige des Punktes
                else
                {
                    QPointF pos = mImageItem->getPosImage(QPointF(x,y),z);
                    p2d.x = pos.x();
                    p2d.y = pos.y();
                }

                tPoint = TrackPoint(Vec2F(p2d.x,p2d.y),100);
                tPoint.setSp(x,y,-mControlWidget->getCalibExtrTrans3()-z); // fuer den Abstand zur Kamera in z-Richtung wie bei einer Stereokamera
                //tPoint.setSp(x,y,z); // Eigentlich bisher nur fuer Stereodaten verwendet

                // Neue ID ? ==> letzte Person beendet ==> abspeichern
                if( personNr > current_personNr )
                {
                    mTracker->append(tp);
                    ++sz;
                    current_personNr++;
                    tp.clear();
                }

                // TrackPerson leer ? ==> Neue TrackPerson erstellen
                if ( tp.isEmpty() )
                {
                    tp = TrackPerson(personNr, frameNr, tPoint);
                    tp.setFirstFrame(frameNr);
                    tp.setHeight(z);
                }
                // TrackPoint an TrackPerson anhaengen
                else
                {
                    tp.setLastFrame(frameNr);
                    tp.append(tPoint);
                }

                // Test-Ausgabe
                //debout << "Person: " << personNr << " at Frame: " << frameNr << " at 2D-Position: (" << p2d.x << ", " << p2d.y << ") and 3D-Position: (" << x << ", " << y << ", " << z << ")" << endl;

            }

            mControlWidget->trackNumberAll->setText(QString("%1").arg(mTracker->size()));
            mControlWidget->trackShowOnlyNr->setMaximum(MAX(mTracker->size(),1));
            mControlWidget->trackNumberVisible->setText(QString("%1").arg(mTracker->visible(mAnimation->getCurrentFrameNum())));
            mControlWidget->colorPlot->replot();
            file.close();
            debout << "import " << dest << " (" << sz << " person(s) )" << endl;
            mTrcFileName = dest; // fuer Project-File, dann koennte track path direkt mitgeladen werden, wenn er noch da ist
        }
        else
        {
            QMessageBox::critical(this, tr("PeTrack"), tr("Cannot load %1 maybe because of wrong file extension.").arg(dest));
        }
        lastFile = dest;
    }
}

void Petrack::testTracker()
{
    static int idx=0; // index in Fehlerliste, die als letztes angesprungen wurde
    QList<int> pers, frame;

    mTracker->checkPlausibility(pers, frame,
                                mControlWidget->testEqual->isChecked(),
                                mControlWidget->testVelocity->isChecked(),
                                mControlWidget->testInside->isChecked(),
                                mControlWidget->testLength->isChecked());
    if (pers.length()<=idx)
        idx=0;
    if (pers.length()>idx)
    {
        mControlWidget->trackShowOnly->setCheckState(Qt::Checked);
        mControlWidget->trackShowOnlyNr->setValue(pers[idx]);
//        mControlWidget->trackShowOnlyNr->setValue(pers[idx]);
        mPlayerWidget->skipToFrame(frame[idx]); // QString().number(mAnimation->getCurrentFrameNum())
        //mControlWidget->trackGotoNr->click();

        ++idx;
    }

}

int Petrack::calculateRealTracker()
{
    bool autoCorrectOnlyExport = (mControlWidget->getRecoMethod() == 5) && // multicolor
            mMultiColorMarkerWidget->autoCorrect->isChecked() &&
            mMultiColorMarkerWidget->autoCorrectOnlyExport->isChecked();
    //int anz = mTrackerReal->calculate(mTracker, mImageItem, mControlWidget->getColorPlot(), getImageBorderSize(), mControlWidget->anaMissingFrames->checkState());
    int anz = mTrackerReal->calculate(mTracker, mImageItem, mControlWidget->getColorPlot(), getImageBorderSize(),
                            mControlWidget->anaMissingFrames->checkState(), //mControlWidget->trackMissingFrames->checkState(),
                            mStereoWidget->stereoUseForExport->isChecked(),
                            mControlWidget->trackAlternateHeight->checkState(), mControlWidget->coordAltitude->value(), mStereoWidget->stereoUseCalibrationCenter->isChecked(),
                            mControlWidget->exportElimTp->isChecked(), mControlWidget->exportElimTrj->isChecked(), mControlWidget->exportSmooth->isChecked(),
                            mControlWidget->exportViewDir->isChecked(), mControlWidget->exportAngleOfView->isChecked(), mControlWidget->exportMarkerID->isChecked(),
                            autoCorrectOnlyExport);

    mTrackerReal->calcMinMax();
    return anz;
}


// Veraltet wird in extCalibration gemacht!
//void Petrack::load3DCalibPoints(QString src) // default = ""
//{

//    bool all_ok = true;

//    vector<Point3f> list3D;
//    vector<Point2f> list2D;

//    if( !src.isEmpty() )
//    {
//        if( src.right(4) == ".3dc" )
//        {
//            //mExtrCalibration->setExtrCalibFile(src);
//            QFile file(src);
//            if( !file.open(QIODevice::ReadOnly | QIODevice::Text) )
//            {
//                QMessageBox::critical(this, tr("PeTrack"), tr("Error: Cannot open %1:\n%2.").arg(src).arg(file.errorString()));
//                return;
//            }

//            debout << "reading 3D calibration data from " << src << "..." << endl;

//            QTextStream in(&file);
//            QString line;
//            int lineCount = 0;
//            QStringList values;

//            line = in.readLine();
//            lineCount++;
//            int sz_3d = line.toInt(&all_ok);
//            if( !all_ok ){
//                QMessageBox::critical(this, tr("PeTrack"), tr("Error: First line of 3D point file should only contain the number of listed 3D-Points."));
//                return;
//            }

//            bool withImageData = false;
//            double coords[5];
//            while( !in.atEnd() )
//            {
//                line = in.readLine();

//                lineCount++;
//                // comment lines
//                if( line.startsWith("#") || line.startsWith(";;") || line.startsWith("//") || line.startsWith("!") )
//                    continue;

//                //QStream stream(line);

//                //stream >> x_3d >> y_3d << z_3d
//                //       >> x_2d << y_2d;

//                values = line.split(" ");
//                //cout << line << " (" << values.size() << ")" << endl;
//                if( lineCount == 2 && values.size() == 5 )
//                {
//                    withImageData = true;
//                }
//                if( values.size() == 3 || values.size() == 5 )
//                {
//                    //debout << values.at(0) << ", " << values.at(1) << ", " << values.at(2) << endl;
//                    for(int i=0; i<3; i++)
//                    {
//                        coords[i] = values.at(i).toDouble(&all_ok);
//                        if(!all_ok)
//                        {
//                            QMessageBox::critical(this, tr("PeTrack"), tr("Error: Reading Float-Value in line %1 column %2 crashed: %3 (File: %4)").arg(lineCount).arg(i).arg(values.at(i)).arg(src));
//                            return;
//                        }
//                    }
//                    list3D.push_back( Point3f( coords[0], coords[1], coords[2] ) );
//                    if (values.size() == 5)
//                    {
//                        if( !withImageData ){
//                            QMessageBox::critical(this, tr("PeTrack"), tr("Error: Unsupported File Format in: %1 (Only 3D-Points or 3D-Points and 2D-Points, but no mix)").arg(src));
//                            return;
//                        }
//                        for(int i=3; i<5; i++)
//                        {
//                            coords[i] = values.at(i).toDouble(&all_ok);
//                            if(!all_ok)
//                            {
//                                QMessageBox::critical(this, tr("PeTrack"), tr("Error: Reading Float-Value in line %1 column %2 crashed: %3 (File: %4)").arg(lineCount).arg(i).arg(values.at(i)).arg(src));
//                                return;
//                            }
//                        }
//                        list2D.push_back( Point2f( coords[3], coords[4] ) );

//                    }else if( withImageData )
//                    {
//                        QMessageBox::critical(this, tr("PeTrack"), tr("Error: Unsupported File Format in: %1 (Only 3D-Points or 3D-Points and 2D-Points, but no mix)").arg(src));
//                        return;
//                    }
//                }else
//                {
//                    QMessageBox::critical(this, tr("PeTrack"), tr("Error: Unsupported File Format in: %1").arg(src));
//                    return;
//                }


//            }
//            file.close();
//            all_ok = true;
//            int sz_2d = 0;
//            if( !mTracker || mTracker->size() < 4 )
//            {
//                if( !withImageData )
//                {
//                    QMessageBox::critical(this, tr("PeTrack"), tr("Error: At minimum four 3D calibration points needed for 3D calibration."));
//                }
//            }else
//            {
//                sz_2d = mTracker->size();
//                list2D.clear();

//                if( sz_2d != sz_3d ){
//                    if( !withImageData )
//                    {
//                        QMessageBox::critical(this, tr("PeTrack"), tr("Count of 2D-Points (%1) and 3D-Points (%2) disagree").arg(sz_2d).arg(sz_3d));
//                        all_ok = false;
//                    }
//                }
//                //debout << "Marked 2D-Image-Points: " << endl;
//                if( all_ok )
//                {
//                    for(int i = 0; i < sz_2d; i++)
//                    {
//                        //debout << "[" << i << "]: (" << mTracker->at(i).at(0).x() << ", " << mTracker->at(i).at(0).y() << ")" << endl;
//                        // Info: Tracker->TrackPerson->TrackPoint->Vec2F
//                        list2D.push_back(Point2f(mTracker->at(i).at(0).x(),mTracker->at(i).at(0).y()));
//                    }
//                }
//            }


//            //            mExtrCalibration->set3DList(list3D);
//            //            mExtrCalibration->set2DList(list2D);
//            //debout << "3D.x " << "3D.y " << "3D.z " << "2D.x " << "2D.y " << endl;
//            for( int i=0; i<sz_3d; i++ )
//            {
//                //                debout << ((Point3f) mExtrCalibration->get3DList().at(i)).x << " "
//                //                       << ((Point3f) mExtrCalibration->get3DList().at(i)).y << " "
//                //                       << ((Point3f) mExtrCalibration->get3DList().at(i)).z << " "
//                //                       << ((Point2f) mExtrCalibration->get2DList().at(i)).x << " "
//                //                       << ((Point2f) mExtrCalibration->get2DList().at(i)).y << endl;
//            }

//            if( !withImageData )
//            {
//                // Save corresponding image-points,
//                QFile file(src);
//                int i;

//                if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
//                {
//                    QMessageBox::critical(this, tr("PeTrack"), tr("Cannot open %1:\n%2.").arg(src).arg(file.errorString()));
//                    return;
//                }

//                QTextStream out(&file);

//                out << sz_3d << endl;
//                for (i = 0; i < sz_3d; ++i)
//                {
//                    out << list3D.at(i).x << " " << list3D.at(i).y << " " << list3D.at(i).z << " " << list2D.at(i).x << " " << list2D.at(i).y << endl;
//                }

//                file.close();

//            }

//            //            mExtrCalibration->calibExtrinsicParams();
//        }else // is 3dc-File ?
//        {
//            QMessageBox::critical(this, tr("PeTrack"), tr("File format is not supported for 3D calibration input files: %1 (supported: .3dc ").arg(src.right(4)));
//            return;
//        }
//    }else // src empty ?
//    {
//        QMessageBox::critical(this, tr("PeTrack"), tr("Cannot open 3D calibration file: file is missing."));
//        return;
//    }
//}

void Petrack::exportTracker(QString dest) //default = ""
{
    static QString lastFile;

    if (lastFile == "")
        lastFile = mTrcFileName;

    if (mTracker)
    {
        // if no destination file or folder is given
        if (dest.isEmpty())
        {
            //             if (lastFile.isEmpty() && !mSeqFileName.isEmpty())
            //                 lastFile = QFileInfo(mSeqFileName).path();
            //getSaveFileName(  ==> Wird keine Dateiendung angegeben wird automatisch die erste aus dem Filter angehangen
            //QUrl url = QFileDialog::getSaveFileUrl(this,
            //                                    tr("Select file for exporting tracking pathes"),
            //                                    lastFile,
            //                                    tr("Tracker (*.*);;Petrack tracker (*.trc);;Text (*.txt);;Text for gnuplot(*.dat);;XML Travisto (*.trav);;All supported types (*.txt *.trc *.dat *.trav *.);;All files (*.*)"));
            //dest = url.toLocalFile();//path();//toString();

            QFileDialog fileDialog(this,
                                   tr("Select file for exporting tracking pathes"),
                                   lastFile,
                                   tr("Tracker (*.*);;Petrack tracker (*.trc);;Text (*.txt);;Text for gnuplot(*.dat);;XML Travisto (*.trav);;All supported types (*.txt *.trc *.dat *.trav *.);;All files (*.*)"));
            fileDialog.setAcceptMode(QFileDialog::AcceptSave);
            fileDialog.setFileMode(QFileDialog::AnyFile);
            fileDialog.setDefaultSuffix("");
            //fileDialog.setOption();

//            foreach (QString filter, fileDialog.mimeTypeFilters()) {
//                debout << "MIME-Typ Filter: " << filter << endl;

//            }
//            foreach (QString filter, fileDialog.nameFilters()) {
//                debout << "Name Filter: " << filter << endl;

//            }

            if( fileDialog.exec() ){
                dest = fileDialog.selectedFiles().at(0);
//                debout << "selectedFiles" << endl;
            }
            //dest = QFileDialog::getSaveFileName(this,
            //                                    tr("Select file for exporting tracking pathes"),
            //                                    lastFile,
            //                                    tr("Tracker (*.*);;Petrack tracker (*.trc);;Text (*.txt);;Text for gnuplot(*.dat);;XML Travisto (*.trav);;All supported types (*.txt *.trc *.dat *.trav *.);;All files (*.*)"));

       }

        if (!dest.isEmpty())
        {
            QList<int> pers, frame;
            bool autoCorrectOnlyExport = (mControlWidget->getRecoMethod() == 5) && // multicolor
                    mMultiColorMarkerWidget->autoCorrect->isChecked() &&
                    mMultiColorMarkerWidget->autoCorrectOnlyExport->isChecked();

//            debout << "dest: " << dest << " suffix: " << dest.right(4) << endl;

            if (dest.right(4) == ".trc")
            {
#ifdef TIME_MEASUREMENT
                double time1 = 0.0, tstart;
                tstart = clock();
#endif
                //QFile file(dest);
                QTemporaryFile file;
                int i;

                if (!file.open()/*!file.open(QIODevice::WriteOnly | QIODevice::Text)*/)
                {
                    QMessageBox::critical(this, tr("PeTrack"), tr("Cannot open %1:\n%2.").arg(dest).arg(file.errorString()));
                    return;
                }
                QProgressDialog progress("Export TRC-File",NULL,0,mTracker->size()+1,this->window());
                progress.setWindowTitle("Export .trc-File");
                progress.setWindowModality(Qt::WindowModal);
                progress.setVisible(true);
                progress.setValue(0);
                progress.setLabelText(QString("Export tracking data ..."));

                qApp->processEvents();

                //if (mControlWidget->exportComment->isChecked())
d.kilic's avatar
d.kilic committed
                //else
                //    trcVersion = 2;

                debout << "export tracking data to " << dest << " (" << mTracker->size() << " person(s), file version " << trcVersion << ")..." << endl;
                QTextStream out(&file);

                out << "version " << trcVersion << endl;
                out << mTracker->size() << endl;
                for (i = 0; i < mTracker->size(); ++i)
                {
                    qApp->processEvents();
                    progress.setLabelText(QString("Export person %1 of %2 ...").arg(i+1).arg(mTracker->size()));
                    progress.setValue(i+1);
                    //if(mControlWidget->exportComment->isChecked())
                    //    out << "# " << (*mTracker)[i].comment() << endl;
                    out << (*mTracker)[i] << endl;
                }
                file.flush();
                file.close();
#ifdef TIME_MEASUREMENT
                time1 += clock() - tstart;
                time1 = time1/CLOCKS_PER_SEC;
                cout << "  time(writing) = " << time1 << " sec." << endl;

                time1 = 0.0;
                tstart = clock();
#endif
                progress.setLabelText(QString("Save file ..."));
                qApp->processEvents();

                if (QFile::exists(dest))
                    QFile::remove(dest);

                if( !file.copy(dest) )
                    QMessageBox::critical(this, tr("PeTrack"),
                                                   tr("Could not export tracking data.\n"
                                                      "Please try again!"),
                                                   QMessageBox::Ok);
                else
                    statusBar()->showMessage(tr("Saved tracking data to %1.").arg(dest), 5000);