radial_variance_hash.cpp 11.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

#include "precomp.hpp"

using namespace cv;
using namespace cv::img_hash;
using namespace std;

namespace {

enum
{
    hashSize = 40,
};

inline float roundingFactor(float val)
{
    return val >= 0 ? 0.5f : -0.5f;
}

inline int createOffSet(int length)
{
    float const center = static_cast<float>(length/2);
    return static_cast<int>(std::floor(center + roundingFactor(center)));
}

class RadialVarianceHashImpl : public ImgHashBase::ImgHashImpl
{
public:
    cv::Mat blurImg_;
    std::vector<double> features_;
    cv::Mat grayImg_;
    int numOfAngelLine_;
    cv::Mat pixPerLine_;
    cv::Mat projections_;
    double sigma_;

    RadialVarianceHashImpl(double sigma, int numOfAngleLine)
        : numOfAngelLine_(numOfAngleLine), sigma_(sigma)
    {
    }

    ~RadialVarianceHashImpl() {}

    virtual void compute(cv::InputArray inputArr, cv::OutputArray outputArr)
    {
        cv::Mat const input = inputArr.getMat();
        CV_Assert(input.type() == CV_8UC4 ||
                  input.type() == CV_8UC3 ||
                  input.type() == CV_8U);

        if(input.type() == CV_8UC3)
        {
            cv::cvtColor(input, grayImg_, CV_BGR2GRAY);
        }
        else if(input.type() == CV_8UC4)
        {
            cv::cvtColor(input, grayImg_, CV_BGRA2GRAY);
        }
        else
        {
            grayImg_ = input;
        }

        cv::GaussianBlur(grayImg_, blurImg_, cv::Size(0,0), sigma_, sigma_);
        radialProjections(blurImg_);
        findFeatureVector();
        outputArr.create(1, hashSize, CV_8U);
        cv::Mat hash = outputArr.getMat();
        hashCalculate(hash);
    }

    virtual double compare(cv::InputArray hashOne, cv::InputArray hashTwo) const
    {
        cv::Mat const hashOneF = hashOne.getMat();
        cv::Mat const hashTwoF = hashTwo.getMat();
        CV_Assert(hashOneF.cols == hashSize && hashOneF.cols == hashTwoF.cols);

        float bufferOne[hashSize];
        cv::Mat hashFloatOne(1, hashSize, CV_32F, bufferOne);
        hashOneF.convertTo(hashFloatOne, CV_32F);

        float bufferTwo[hashSize];
        cv::Mat hashFloatTwo(1, hashSize, CV_32F, bufferTwo);
        hashTwoF.convertTo(hashFloatTwo, CV_32F);

        int const pixNum = hashFloatOne.rows * hashFloatOne.cols;
        cv::Scalar hOneMean, hOneStd, hTwoMean, hTwoStd;
        cv::meanStdDev(hashFloatOne, hOneMean, hOneStd);
        cv::meanStdDev(hashFloatTwo, hTwoMean, hTwoStd);

        // Compute covariance and correlation coefficient
        hashFloatOne -= hOneMean;
        hashFloatTwo -= hTwoMean;
        double max = std::numeric_limits<double>::min();
        for(int i = 0; i != hashSize; ++i)
        {
            double const covar = (hashFloatOne).dot(hashFloatTwo) / pixNum;
            double const corre = covar / (hOneStd[0] * hTwoStd[0] + 1e-20);
            max = std::max(corre, max);
            //move last value to first position, first value to second position,
            //second value to third position and so on
            float const preValue = bufferTwo[hashSize-1];
            std::copy_backward(bufferTwo, bufferTwo + hashSize - 1, bufferTwo + hashSize);
            bufferTwo[0] = preValue;
        }

        //return peak correlation coefficient
        return max;
    }

    int getNumOfAngleLine() const
    {
        return numOfAngelLine_;
    }
    double getSigma() const
    {
        return sigma_;
    }

    void setNumOfAngleLine(int value)
    {
        CV_Assert(value > 0);
        numOfAngelLine_ = value;
    }
    void setSigma(double value)
    {
        CV_Assert(value >= 1.0);
        sigma_ = value;
    }

    void afterHalfProjections(cv::Mat const &input, int D, int xOff, int yOff)
    {
        int *pplPtr = pixPerLine_.ptr<int>(0);
        int const init = 3*numOfAngelLine_/4;
        for(int k = init, j = 0; k < numOfAngelLine_; ++k, j += 2)
        {
            float const theta = k*3.14159f/numOfAngelLine_;
            float const alpha = std::tan(theta);
            uchar *projDown = projections_.ptr<uchar>(k);
            uchar *projUp = projections_.ptr<uchar>(k-j);
            for(int x = 0; x < D; ++x)
            {
                float const y = alpha*(x-xOff);
                int const yd = static_cast<int>(std::floor(y + roundingFactor(y)));
                if((yd + yOff >= 0)&&(yd + yOff < input.rows) && (x < input.cols))
                {
                    projDown[x] = input.at<uchar>(yd+yOff, x);
                    pplPtr[k] += 1;
                }
                if ((yOff - yd >= 0)&&(yOff - yd < input.cols)&&
                        (2*yOff - x >= 0)&&(2*yOff- x < input.rows)&&
                        (k != init))
                {
                    projUp[x] =
                            input.at<uchar>(-(x-yOff)+yOff, -yd+yOff);
                    pplPtr[k-j] += 1;
                }
            }
        }
    }

    void findFeatureVector()
    {
        features_.resize(numOfAngelLine_);
        double sum = 0.0;
        double sumSqd = 0.0;
        int const *pplPtr = pixPerLine_.ptr<int>(0);
        for(int k=0; k < numOfAngelLine_; ++k)
        {
            double lineSum = 0.0;
            double lineSumSqd = 0.0;
            //original implementation of pHash may generate zero pixNum, this
            //will cause NaN value and make the features become less discriminative
            //to avoid this problem, I add a small value--0.00001
            double const pixNum = pplPtr[k] + 0.00001;
            double const pixNumPow2 = pixNum * pixNum;
            uchar const *projPtr = projections_.ptr<uchar>(k);
            for(int i = 0; i < projections_.cols; ++i)
            {
                double const value = projPtr[i];
                lineSum += value;
                lineSumSqd += value * value;
            }
            features_[k] = (lineSumSqd/pixNum) -
                    (lineSum*lineSum)/(pixNumPow2);
            sum += features_[k];
            sumSqd += features_[k]*features_[k];
        }
        double const numOfALPow2 = numOfAngelLine_ * numOfAngelLine_;
        double const mean = sum/numOfAngelLine_;
        double const var  = std::sqrt((sumSqd/numOfAngelLine_) - (sum*sum)/(numOfALPow2));
        for(int i = 0; i < numOfAngelLine_; ++i)
        {
            features_[i] = (features_[i] - mean)/var;
        }
    }

    void firstHalfProjections(cv::Mat const &input, int D, int xOff, int yOff)
    {
        int *pplPtr = pixPerLine_.ptr<int>(0);
        for(int k = 0; k < numOfAngelLine_/4+1; ++k)
        {
            float const theta = k*3.14159f/numOfAngelLine_;
            float const alpha = std::tan(theta);
            uchar *projOne = projections_.ptr<uchar>(k);
            uchar *projTwo = projections_.ptr<uchar>(numOfAngelLine_/2-k);
            for(int x = 0; x < D; ++x)
            {
                float const y = alpha*(x-xOff);
                int const yd = static_cast<int>(std::floor(y + roundingFactor(y)));
                if((yd + yOff >= 0)&&(yd + yOff < input.rows) && (x < input.cols))
                {
                    projOne[x] = input.at<uchar>(yd+yOff, x);
                    pplPtr[k] += 1;
                }
                if((yd + xOff >= 0) && (yd + xOff < input.cols) &&
                        (k != numOfAngelLine_/4) && (x < input.rows))
                {
                    projTwo[x] =
                            input.at<uchar>(x, yd+xOff);
                    pplPtr[numOfAngelLine_/2-k] += 1;
                }
            }
        }
    }

    void hashCalculate(cv::Mat &hash)
    {
        double temp[hashSize];
        double max = 0;
        double min = 0;
        size_t const featureSize = features_.size();
        //constexpr is a better choice
        double const sqrtTwo = 1.4142135623730950488016887242097;
        for(int k = 0; k < hash.cols; ++k)
        {
            double sum = 0;
            for(size_t n = 0; n < featureSize; ++n)
            {
                sum += features_[n]*std::cos((3.14159*(2*n+1)*k)/(2*featureSize));
            }
            temp[k] = k == 0 ? sum/std::sqrt(featureSize) :
                               sum*sqrtTwo/std::sqrt(featureSize);
            if(temp[k] > max)
            {
                max = temp[k];
            }
            else if(temp[k] < min)
            {
                min = temp[k];
            }
        }

        double const range = max - min;
        if(range != 0)
        {
            //std::transform is a better choice if lambda supported
            uchar *hashPtr = hash.ptr<uchar>(0);
            for(int i = 0; i < hash.cols; ++i)
            {
                hashPtr[i] = static_cast<uchar>((255*(temp[i] - min)/range));
            }
        }
        else
        {
            hash = 0;
        }
    }

    void radialProjections(cv::Mat const &input)
    {
        int const D = (input.cols > input.rows) ? input.cols : input.rows;
        //Different with PHash, this part reverse the row size and col size,
        //because cv::Mat is row major but not column major
        projections_.create(numOfAngelLine_, D, CV_8U);
        projections_ = 0;
        pixPerLine_.create(1, numOfAngelLine_, CV_32S);
        pixPerLine_ = 0;
        int const xOff = createOffSet(input.cols);
        int const yOff = createOffSet(input.rows);

        firstHalfProjections(input, D, xOff, yOff);
        afterHalfProjections(input, D, xOff, yOff);
    }
};

inline RadialVarianceHashImpl *getLocalImpl(ImgHashBase::ImgHashImpl *ptr)
{
    RadialVarianceHashImpl * impl = static_cast<RadialVarianceHashImpl*>(ptr);
    CV_Assert(impl);
    return impl;
}

} // namespace::

//==================================================================================================

namespace cv { namespace img_hash {

Ptr<RadialVarianceHash> RadialVarianceHash::create(double sigma, int numOfAngleLine)
{
    Ptr<RadialVarianceHash> res(new RadialVarianceHash);
    res->pImpl = makePtr<RadialVarianceHashImpl>(sigma, numOfAngleLine);
    return res;
}

int RadialVarianceHash::getNumOfAngleLine() const
{
    return getLocalImpl(pImpl)->getNumOfAngleLine();
}

double RadialVarianceHash::getSigma() const
{
    return getLocalImpl(pImpl)->getSigma();
}

void RadialVarianceHash::setNumOfAngleLine(int value)
{
    getLocalImpl(pImpl)->setNumOfAngleLine(value);
}

void RadialVarianceHash::setSigma(double value)
{
    getLocalImpl(pImpl)->setSigma(value);
}

std::vector<double> RadialVarianceHash::getFeatures()
{
    getLocalImpl(pImpl)->findFeatureVector();
    return getLocalImpl(pImpl)->features_;
}

cv::Mat RadialVarianceHash::getHash()
{
    cv::Mat hash;
    getLocalImpl(pImpl)->hashCalculate(hash);
    return hash;
}

Mat RadialVarianceHash::getPixPerLine(Mat const &input)
{
    getLocalImpl(pImpl)->radialProjections(input);
    return getLocalImpl(pImpl)->pixPerLine_;
}

Mat RadialVarianceHash::getProjection()
{
    return getLocalImpl(pImpl)->projections_;
}

void radialVarianceHash(cv::InputArray inputArr,
                        cv::OutputArray outputArr,
                        double sigma, int numOfAngleLine)
{
    RadialVarianceHashImpl(sigma, numOfAngleLine).compute(inputArr, outputArr);
}

}} // cv::img_hash::