46

I was using a fixed threshold but turns out that it's not so good for me. Then, someone told me about the otsu threshold. How can I use it in my code? I read about it and I don't understand very well. Could someone explain to me how to use it in OpenCV the otsu threshold?

Here is my code now:

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

    using namespace cv;

    int main ( int argc, char **argv )
    {
       Mat im_gray = imread("img3.jpg",CV_LOAD_IMAGE_GRAYSCALE);

       Mat im_rgb  = imread("img3.jpg");
       cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

       Mat img_bw = im_gray > 115;

       imwrite("img_bw3.jpg", img_bw);

       return 0;
    }  

With this I have to change the threshold to any image that I want to convert to binary. I found this:

    cvThreshold(scr, dst, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

Is that right? I don't understand very well and because of that, didn't know how I could adapt to my code.

4

3 回答 3

84

以下行进行 otsu 阈值操作:

cv::threshold(im_gray, img_bw, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
  • im_gray是一个源 8 位图像,
  • img_bw是一个结果,
  • 0 表示实际被省略的阈值水平,因为我们使用了 CV_THRESH_OTSU 标志,
  • 255 是一个值,将分配给结果中的各个像素(即,源中的值大于计算的阈值级别的所有像素)
  • CV_THRESH_BINARY | CV_THRESH_OTSU是执行 Otsu 阈值处理所需的标志。因为实际上我们想要执行二进制阈值,所以我们使用CV_THRESH_BINARY(您可以使用 opencv 提供的 5 个标志中的任何一个)结合CV_THRESH_OTSU

文档链接: http: //docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#threshold

于 2013-06-19T09:42:17.107 回答
16

在python中很简单

import cv2

img = cv2.imread('img.jpg',0)  #pass 0 to convert into gray level 
ret,thr = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)
cv2.imshow('win1', thr)
cv2.waitKey(0)  
cv2.destroyAllWindows()
于 2016-02-06T18:28:47.987 回答
-1

在 Android 中是一条线。

Imgproc.threshold(matGrayIn, matOtsuOut, 0, 255, Imgproc.THRESH_OTSU | Imgproc.THRESH_BINARY);
于 2017-04-21T07:56:43.093 回答