简体   繁体   中英

Convert Grayscale Image to Binary Without Thresholding

I am trying to process the elements in a grayscale image ( cv::Mat ) and assigning it either 1 or 0 depending if it meets a certain criteria. So now, the question arises how to create a binary image from those 1's and 0's that got produced. Well, reason I am asking is because I want to throw that binary image as an argument for cv::calcOpticalFlowPyrLK , like this person did in this video (I am assuming you can pass a binary image for Lucas-Kanade, apologies if it's not, I'm still rather new to OpenCV) .

Anyways, should I just declare a new cv::Mat binImg(grayImg.rows, grayImg.cols, CV_8UC1); and iterate to that matrix to assign my values?

Any help is appreciated. Thank you!

You could use compare :

C++: void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop)

The key idea is to encoding your criteria in a mat with the same size and use it to compare with the source image. Here is an example.

Let say that your criteria is a parabola curve:

在此处输入图片说明

Such that x is the image row (0-512) and y is the regular gray scale (0-255). Given this criteria it is possible to draw a gray image:

在此处输入图片说明

At than use compare to apply the criteria to the pic:

在此处输入图片说明

I used a parabola in this example, of course you should to adapt the model for your own criteria and needs.

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include "opencv2/photo.hpp"

#include <iostream>

using namespace std;
using namespace cv;

int main() {

    Mat src = imread("Lenna.png", CV_LOAD_IMAGE_GRAYSCALE);

    namedWindow("src", WINDOW_AUTOSIZE);
    imshow("src", src);

    Mat someGradientMat(src.size(), CV_8U, Scalar(0));

    int limit = src.size().height;

    double a = -255.0*4.0 / (limit*limit);
    double b = 255.0*4.0 / limit;
    double c = 0;

    for (int r = 0; r < limit; r++) {

        //value is the parabole y = ax^2 + b + c
        int value = (int)(a*r*r + b*r + c);

        someGradientMat.row(r).setTo(value);
    }
    namedWindow("someGradientMat", CV_WINDOW_NORMAL);
    imshow("someGradientMat", someGradientMat);

    Mat dst;
    compare(src, someGradientMat, dst, CMP_LT);

    namedWindow("dst", CV_WINDOW_NORMAL);
    imshow("dst", dst);

    waitKey(0);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM