1

The dst = signum(src) function set the values of all positive elements in src to 1, and the values of all negative elements to -1.

However, it seems that it is not possible to implement the signum() function by applying the OpenCV function threshold(). I do not want to traverse src neither, because it is inefficient.

ZHOU
  • 1,151
  • 2
  • 12
  • 27

1 Answers1

6

I don't know which language you are using, but in OpenCV C++, signum function can be implemented as follows:

Mat signum(Mat src)
{
    Mat dst = (src >= 0) & 1;
    dst.convertTo(dst,CV_32F, 2.0, -1.0);
    return dst;
}

Of-course, the returned matrix would have floating point or a signed type to store the value of -1.

Update:

The previous implementation returns only 1 or -1 depending on the input values, but according to signum definition, 0 should remain 0 in the output. So getting reference from this answer, the standard signum function can be implemented as follows using OpenCV:

Mat signum(Mat src)
{
    Mat z = Mat::zeros(src.size(), src.type()); 
    Mat a = (z < src) & 1;
    Mat b = (src < z) & 1;

    Mat dst;
    addWeighted(a,1.0,b,-1.0,0.0,dst, CV_32F);
    return dst;
}
Community
  • 1
  • 1
sgarizvi
  • 16,623
  • 9
  • 64
  • 98