Перейти к содержимому
Compvision.ru

RinOS

Пользователи
  • Количество публикаций

    99
  • Зарегистрирован

  • Посещение

  • Days Won

    8

Сообщения, опубликованные пользователем RinOS


  1. Встретил такую штуку в opencv2.3 ExposureCompensator используется как раз для выравнивания экспозиции при склейке изображений в панораму.

    Весь функционал opencv_stitching мне не нужен, нужно лишь выравнивание экспозиции относительно первой (главной) картинки.

    Документации по ExposureCompensator очень мало. Особенно не понятно какие числа должны быть в corners

    compensator->feed( corners, images, mask )

    Пока что делаю так но эффекта не замечаю. Хотя отрабатывает функция без ошибок.

    
    void Compensator::feed(Mat &etalon, Mat &fix)
    
    {
    
        pt0.x = 1; //???
    
        pt0.y = 1; //???
    
    
        pt1.x = frame.rows - 1; //???
    
        pt1.y = frame.cols - 1; //???
    
    
        corners.push_back( pt0 );
    
        corners.push_back( pt1 );
    
    
        m0.create( frame.rows, frame.cols, CV_8U );
    
        m0.setTo( cv::Scalar::all(255) );
    
    
        m1.create( frame.rows, frame.cols, CV_8U );
    
        m1.setTo( cv::Scalar::all(255) );
    
    
        mask.push_back( m0 );
    
        mask.push_back( m1 );
    
    
        images.push_back( etalon );
    
        images.push_back( fix );
    
    
        compensator->feed( corners, images, mask );
    
        compensator->apply( images.size() - 1, pt0, fix, m0 );
    
    }
    
    


  2. Долгими поисками по гуглу нашел одну замечательную функцию:

    
    CVStatus cvNormalizeIllum(IplImage *img, const float destMean, const float destMse)
    
    {
    
        uchar* src_data;
    
        float* dst_data;
    
        CvRect src_roi;
    
        int width_step, width, height, roi_size, img_index, data_index;
    
        CvSize data_size;
    
        float temp_float, mse_ratio;
    
        int i, x, y;
    
        float A11=0, A12=0, A13=0, A21=0, A22=0, A23=0, A31=0, A32=0, A33=0;
    
        float I_point;
    
        float B1=0, B2 = 0, B3 = 0;
    
        float Det;
    
        float B11, B12, B13, B22, B23, B33;
    
        float A1, A2, A3;
    
        float cal_mean, cal_mse;
    
    
        // check arguments
    
        if (destMean < 0.0f || destMse < 0.0f)
    
            return CV_StsBadArg;
    
    
        // check image
    
        if (img->depth != IPL_DEPTH_8U)
    
            return CV_BadDepth;
    
        if (img->nChannels != 1)
    
            return CV_BadNumChannels;
    
    
        // Get raw data
    
        cvGetRawData(img, (uchar **) &src_data, &width_step, &data_size);
    
        src_roi = cvGetImageROI(img);
    
    
        width = data_size.width;
    
        height = data_size.height;
    
        roi_size = width * height;
    
        dst_data = (float *)cvAlloc(roi_size * sizeof(float));
    
    
        //1. Caculate the A'A
    
        for(y=0; y<height; y++)
    
        {
    
            for(x=0; x<width; x++)
    
            {
    
                A11 += x * x;
    
                A12 += x * y;
    
                A13 += x;
    
                A22 += y * y;
    
                A23 += y;
    
            }
    
        }
    
        A33 = (float)roi_size;
    
    
        //2. Caculate the A'B
    
        img_index = 0;
    
        for(y=0; y<height; y++)
    
        {
    
            for(x=0; x<width; x++)
    
            {
    
                I_point = (float)src_data[img_index + x];
    
                B1 += x * I_point;
    
                B2 += y * I_point;
    
                B3 += I_point;
    
            }
    
            img_index += width_step;
    
        }
    
    
        //3. Caculate the inverse matrix (A'A)
    
        Det = - A11*A22*A33 + A11*A23*A23 + A12*A12*A33 - 2*A12*A13*A23 + A13*A13*A22;
    
        if(Det == 0)
    
            return CV_StsError;
    
        B11 =  - (A22*A33 - A23*A23) / Det;
    
        B12 = (A12*A33 - A13*A23) / Det;
    
        B13 = - (A12*A23 - A13*A22) / Det;
    
        B22 = - (A11*A33 - A13*A13) / Det;
    
        B23 = - ( - A11*A23 + A12*A13) / Det;
    
        B33 = ( - A11*A22+A12*A12) / Det;
    
    
        //4. Solve equations and find a1, a2, a3
    
        A1 = B11 * B1 + B12 * B2 + B13 * B3;
    
        A2 = B12 * B1 + B22 * B2 + B23 * B3;
    
        A3 = B13 * B1 + B23 * B2 + B33 * B3;
    
    
        //5. Brightness correction
    
        cal_mean = 0;
    
        data_index = 0;
    
        img_index = 0;
    
        for (y=0; y<height; y++)
    
        {
    
            for (x=0; x<width; x++)
    
            {
    
                I_point = (float)src_data[img_index + x] - (A1 * x + A2 * y + A3);
    
                dst_data[data_index] = I_point;
    
                data_index ++;
    
                cal_mean += I_point;
    
            }
    
            img_index += width_step;
    
        }
    
        cal_mean /= (width * height);
    
    
        // MSE Caculation
    
        cal_mse = 0;
    
        for( i=0; i<roi_size; i++)
    
        {
    
            temp_float = dst_data[i] - cal_mean;
    
            cal_mse += temp_float * temp_float;
    
        }
    
        cal_mse = (float)sqrt( cal_mse / roi_size );
    
    
        // MSE normalization and write back to image buffer
    
        if (cal_mse == 0) {
    
            data_index = 0;
    
            img_index = 0;
    
            for (y=0; y<height; y++)
    
            {
    
                for (x=0; x<width; x++)
    
                {
    
                    src_data[img_index + x] = (unsigned char)destMean;
    
                }
    
                img_index += width_step;
    
            }
    
        }
    
        else {
    
            mse_ratio = destMse / cal_mse;
    
            data_index = 0;
    
            img_index = 0;
    
            for (y=0; y<height; y++)
    
            {
    
                for (x=0; x<width; x++)
    
                {
    
                    temp_float = (dst_data[data_index] - cal_mean) * mse_ratio + destMean;
    
                    data_index ++;
    
                    if(temp_float > 255.0f)
    
                        src_data[img_index + x] = 255;
    
                    else if (temp_float < 0.0f)
    
                        src_data[img_index + x] = 0;
    
                    else
    
                        src_data[img_index + x] = (uchar)(temp_float + 0.5f);
    
                }
    
                img_index += width_step;
    
            }
    
        }
    
    
        cvFree((void**)&dst_data);
    
    
        return CV_StsOk;
    
    }

    У нее есть две переменные destMean и destMse.

    destMean - destation mean value of the MSE normalization

    destMse - destation MSE of the MSE normalization

    Что бы не задавать их жестко хотелось бы как ни будь вычислить эти два значения, на основании background image взятого у BackgroundSubtractorMOG2. Тем самым функция станет чуть более адаптивной.

    • Like 2

  3. Можно выровнять яркость по гистограмме (cvEqualizeHist). Но там надо с серым изображением работать. Если нужно цветное, то конвертировать в YUV или HSV, применить cvEqualizeHist к каналу с яркостью и снова конвертировать в RGB.

    Да, видел пост в котором советовали использовать cvEqualizeHist, пробовал и с YUV и HSV. Сначала cvSplit, потом пробовал со всеми слоями и комбинировал) (в общем по всякому тестил) cvEqualizeHist, потом снова собирал cvMerge и передавал полученную картинку BackgroundSubtractorMOG2, но результат не лучше а порой даже хуже.


  4. Ну я эти картинки привел что бы понятнее было в чем проблема, на деле все не так запущено.

    Максимум как предпоследняя картинка.

    Видео обычное avi c кодеком mjpg.

    Пока не придумал как нормализовать изображение... сложность возникает даже с запросом к гуглу...


  5. Не нужны тебе сторонние компоненты, используй OpenCV. Необходимые тебе функции и структуры переписывай из С в Delphi.

    Вот для начала:

    
    const
    
      HighGUI = 'libopencv_highgui231.dll';
    
      CxCore = 'libopencv_core231.dll';
    
    
    type
    
      PCvArr = ^CvArr;
    
      CvArr = Pointer;
    
    
      PIplTileInfo = ^IplTileInfo;
    
      IplTileInfo = record
    
    
      end;
    
    
      PIplROI = ^IplROI;
    
      IplROI = record
    
        coi: Longint;
    
        xOffset: Longint;
    
        yOffset: Longint;
    
        width: Longint;
    
        height: Longint;
    
      end;
    
    
      PIplImage = ^IplImage;
    
      IplImage = record
    
        nSize: Longint;       
    
        ID: Longint;
    
        nChannels: Longint;
    
        alphaChannel: Longint;
    
        depth: Longint;
    
        colorModel: array [0..3] of Byte;
    
        channelSeq: array [0..3] of Byte;
    
        dataOrder: Longint;
    
        origin: Longint;
    
        align: Longint;
    
        width: Longint;
    
        height: Longint;
    
        roi: PIplROI;
    
        maskROI: PIplImage;
    
        imageId: Pointer;
    
        tileInfo: PIplTileInfo;
    
        imageSize: Longint;
    
        imageData: PChar;
    
        widthStep: Longint;
    
        BorderMode: array [0..3] of Longint;
    
        BorderConst: array [0..3] of Longint;
    
        imageDataOrigin: PChar;
    
      end;
    
    
      CvPoint = record
    
        x: Integer;
    
        y: Integer;
    
      end;
    
    
      CvSize = record
    
        width: Integer;
    
        height: Integer;
    
      end;
    
    
      CvScalar = record
    
        B: Double;
    
        G: Double;
    
        R: Double;
    
        A: Double;
    
      end;
    
    
      PCvFont = ^CvFont;
    
      CvFont = record
    
        font_face: Longint;
    
        ascii: PLongint;          
    
        greek: PLongint;
    
        cyrillic: PLongint;
    
        hscale: Single;
    
        vscale: Single;
    
        shear: Single;            
    
        thickness: Longint;       
    
        dx: Single;
    
        line_type: Longint;
    
      end;
    
    
      function cvNamedWindow(const name: PChar; flags: Integer = 1): Integer; cdecl;
    
      procedure cvShowImage(const name: PChar; const image: PIplImage); cdecl;
    
      function cvWaitKey(delay: Integer = 0): Integer; cdecl;
    
      procedure cvLine(img: PIplImage; pt1, pt2: CvPoint; color: CvScalar;
    
        thickness: Integer = 1; line_type: Integer = 8; shift: Integer = 0); cdecl;
    
      procedure cvCircle(img: PIplImage; center: CvPoint; radius: Integer;
    
        color: CvScalar; thickness: Integer = 1; line_type: Integer = 8;
    
        shift: Integer = 0); cdecl;
    
      procedure cvInitFont(font: PCvFont; font_face: Longint; hscale: Double;
    
        vscale: Double; shear: Double; thickness: Longint; line_type: Longint); cdecl;
    
      procedure cvPutText(img: PIplImage; text: PChar; org: CvPoint; font: PCvFont;
    
        color: CvScalar); cdecl;
    
      function cvCloneImage(const image: PIplImage): PIplImage; cdecl;
    
      function cvCreateImage(size: CvSize; depth: Integer; channels: Integer): PIplImage; cdecl;
    
      procedure cvReleaseImage(image: PIplImage); cdecl;
    
    
    
    implementation
    
    
      function cvNamedWindow; external HighGUI;
    
      procedure cvShowImage; external HighGUI;
    
      function cvWaitKey; external HighGUI;
    
      procedure cvLine; external CxCore;
    
      procedure cvCircle; external CxCore;
    
      procedure cvInitFont; external CxCore;
    
      procedure cvPutText; external CxCore;
    
      function cvCloneImage; external CxCore;
    
      function cvCreateImage; external CxCore;
    
      procedure cvReleaseImage; external CxCore;
    
    

    и т.д.


  6. Всем привет!

    Делаю отсечение фона с помощью BackgroundSubtractorMOG2, до недавнего времени все отлично работало и качественно отсекало фон.

    Но столкнулся с проблемой, когда под камерой появляется слишком контрастный (относительно фона) объект, у всего кадра меняется толи цветовой баланс толи экспозиция.

    В качестве примера привожу картинки:

    0287fb7790ebt.jpg 622e998bbbeet.jpg 1a6ed57ee54at.jpg b15353966492t.jpg dbe2b272378bt.jpg

    На деле не так экстремально но BackgroundSubtractorMOG2 ужасно глючит.

    Подскажите как бороться с этой проблемой?


  7. Потестил этот код, неплохо ведет цель.

    
    X  Y  Z
    
    
    predict -0.466858  0.808474  2.26073
    
    real    -0.309018  0.486225  1.53683
    
    
    -0.423659  0.684607  2.0921
    
    -0.296634  0.412955  1.49816
    
    
    -0.358051  0.502584  1.80924
    
    -0.284429  0.322137  1.45931
    
    
    -0.302884  0.319587  1.56944
    
    -0.24458  0.255752  1.44207
    
    
    -0.23795  0.192976  1.43535
    
    -0.23719  0.200144  1.42542
    
    
    -0.211506  0.116637  1.37693
    
    -0.21606  0.155456  1.42932
    
    
    -0.190204  0.0749303  1.37846
    
    -0.202409  0.0838827  1.41801
    
    
    -0.178239  0.0161604  1.38489
    
    -0.193323  0.047973  1.42875
    
    
    -0.173382  -0.0163037  1.40925
    
    -0.185071  -0.00390054  1.43147
    
    
    -0.170241  -0.0576007  1.42664
    
    -0.18052  -0.0539902  1.43713
    
    
    -0.169671  -0.103587  1.43971
    
    -0.185037  -0.0819764  1.44412
    
    
    -0.177794  -0.130038  1.4502
    
    -0.20676  -0.128047  1.44989
    
    
    -0.205006  -0.169031  1.45739
    
    -0.239146  -0.156521  1.45426
    
    
    -0.247401  -0.196648  1.46161
    
    -0.260618  -0.190315  1.46437
    
    
    -0.280221  -0.226259  1.47075
    
    -0.27879  -0.215011  1.47307
    
    

    Хочу реализовать мультитрекинг, есть у кого ни будь примеры или инфа?

    Свой уже написал но довольно косячно работает путает цели которые пересекаются.


  8. >В случае добавления вращения

    Наверно глубины? (третье измерение)

    Буквально прям сейчас нашел реализацию, вроде 3D но матрица создается 6х3, оно ли это))?

    #ifndef _KALMAN_FILTER_H_
    
    #define _KALMAN_FILTER_H_
    
    
    
    #include <vector>
    
    
    
    #include <cv.h>
    
    #include "base.h"
    
    
    
    #include "Structures/Vector.h"
    
    #include "Structures/Calibration.h"
    
    
    
    namespace windage
    
    {
    
            namespace Algorithms
    
            {
    
                    /**
    
                     * @defgroup Algorithms Algorithm classes
    
                     * @brief
    
                     *              algorithm classes
    
                     * @addtogroup Algorithms
    
                     * @{
    
                     */
    
    
    
                    /**
    
                     * @defgroup AlgorithmsPoseEstimator Pose Estimator
    
                     * @brief
    
                                    camera pose estimator in 3D
    
                     * @addtogroup AlgorithmsPoseEstimator
    
                     * @{
    
                     */
    
    
    
                    /**
    
                     * @brief       class for kalman filtering to prevent zitering
    
                     * @author      Woonhyuk Baek
    
                     */
    
                    class DLLEXPORT KalmanFilter
    
                    {
    
                    private:
    
                            /** Tx, Ty, Tz, dTx, dTy, dTz */
    
                            CvKalman* kalman;
    
                            CvMat* measurement;
    
    
    
                    public:
    
                            virtual char* GetFunctionName(){return "KalmanFilter";};
    
                            KalmanFilter()
    
                            {
    
                                    kalman = cvCreateKalman( 6, 3, 0 );
    
                                    measurement = cvCreateMat( 3, 1, CV_32FC1 );
    
                                    this->Initialize();
    
                            }
    
                            ~KalmanFilter()
    
                            {
    
                                    if(kalman) cvReleaseKalman(&kalman);
    
                                    if(measurement) cvReleaseMat(&measurement);
    
                            }
    
    
    
                            void Initialize();
    
                            windage::Vector3 Predict();
    
                            bool Correct(windage::Vector3 T);
    
                    };
    
                    /** @} */ // addtogroup AlgorithmsPoseEstimator
    
                    /** @} */ // addtogroup Algorithms
    
            }
    
    }
    
    #endif // _KALMAN_FILTER_H_
    
    
    
    #include "Algorithms/KalmanFilter.h"
    
    using namespace windage;
    
    using namespace windage::Algorithms;
    
    
    
    void KalmanFilter::Initialize()
    
    {
    
            const float A[] = { 1, 0, 0, 1, 0, 0,
    
                                                    0, 1, 0, 0, 1, 0,
    
                                                    0, 0, 1, 0, 0, 1,
    
                                                    0, 0, 0, 1, 0, 0,
    
                                                    0, 0, 0, 0, 1, 0,
    
                                                    0, 0, 0, 0, 0, 1,};
    
    
    
            memcpy( this->kalman->transition_matrix->data.fl, A, sizeof(A));
    
            cvSetIdentity( this->kalman->measurement_matrix, cvRealScalar(1) );
    
            cvSetIdentity( this->kalman->process_noise_cov, cvRealScalar(1e-5) );
    
            cvSetIdentity( this->kalman->measurement_noise_cov, cvRealScalar(1e-1) );
    
            cvSetIdentity( this->kalman->error_cov_post, cvRealScalar(1));
    
    }
    
    
    
    windage::Vector3 KalmanFilter::Predict()
    
    {
    
            windage::Vector3 prediction;
    
    
    
            const CvMat* predictionMat = cvKalmanPredict( this->kalman, 0 );
    
    
    
            prediction.x = (double)predictionMat->data.fl[0];
    
            prediction.y = (double)predictionMat->data.fl[1];
    
            prediction.z = (double)predictionMat->data.fl[2];
    
    
    
            return prediction;
    
    }
    
    
    
    bool KalmanFilter::Correct(windage::Vector3 T)
    
    {
    
            measurement->data.fl[0] = (float)T.x;
    
            measurement->data.fl[1] = (float)T.y;
    
            measurement->data.fl[2] = (float)T.z;
    
    
    
            cvKalmanCorrect( kalman, measurement );
    
            return true;
    
    }

    • Like 1

  9. Всем привет!

    Есть трёхслойная картинка

    image3D = cvCreateImage( imageSize, IPL_DEPTH_32F, 3 );

    Как можно получить значения каждого канала?

    cхематично изображу так

    x = getnvalue(image3D,0,0,0)
    
    y = getnvalue(image3D,1,0,0)
    
    z = getnvalue(image3D,3,0,0)
    Знаю способ используя COI
    cvSetImageCOI(image3D, 3);
    
    cvCopy(image3D, imageZ, 0);
    
    cvResetImageROI(image3D);

    Но по моему медленно тк потом придется гонять 3 цикла для каждого слоя


  10. Собрал проект CMake-ом для VS 2008, пару либов он скомпилил, застрял на pcl_filters выдает кучу ошибок вида:

    pcl/filters/impl/passthrough.hpp(104) : error C2039: 'NdConcatenateFunctor' : is not a member of 'pcl'
    
    pcl/filters/impl/passthrough.hpp(104) : error C2065: 'NdConcatenateFunctor' : undeclared identifier
    
    pcl/filters/impl/passthrough.hpp(104) : error C2275: 'PointT' : illegal use of this type as an expression
    
    

    Что делать?


  11. На одном китайском сайте, нашел пример вывода в 3d, disparity image :)

    Для лучшего эффекта предварительно нормализуем изображение

    
    imageDepthNormalized = cvCreateMat( imageSize.height,imageSize.width, CV_8U );
    
    cvScale(imageDepth, imageDepthNormalized, 1, 256);
    
    

    8ea589a7a5f1.png

    Программа, исходник и картинка во вложении, картинку берет из "c:\z.bmp"

    glut3d.rar

    • Like 2

  12. Так и не понял, где там ее можно скачать) Бродил бродил по ссылкам... заблудился и в конце пришел на туже страницу откуда начал))

    upd:

    Через сайт я эту страничку так бы и не нашел... гугл помог

    http://www.ros.org/wiki/pcl/standalone/


  13. А может 1 и 2 поставить?

    0 - это же вроде к любой означает.

    Пробовал... не помогло, пробовал и комбинировал с разными типами CV_CAP_ANY, CV_CAP_MIL и т.д. но не получилось... даже не знаю по чему(


  14. У меня у одного такая проблема, с 2.2?

    Пытаюсь подключится к 2 вебкам:

    
        captures[0] = cvCreateCameraCapture(0);
    
        captures[1] = cvCreateCameraCapture(1);
    
    

    к первой подключается ко второй нет. Хотя компилировал под 1 версию все отлично работало...

    Люююдиии) помогите!

×