如何在opencv中使用OTSU阈值? [英] How to use the OTSU Threshold in opencv?
问题描述
我使用的是固定的阈值,但事实证明这对我不太好.然后,有人告诉我有关大津的门槛.如何在我的代码中使用它? 我读了一下,但我不太了解.有人可以告诉我如何在OpenCV中使用otsu阈值吗?
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?
这是我的代码:
#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.
推荐答案
以下行进行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
结合使用
im_gray
is a source 8-bit image,img_bw
is a result,- 0 means threshold level which actually is omitted because we used CV_THRESH_OTSU flag,
- 255 is a value that is going to be assigned to respectively pixels in the result (namely, to all pixels which value in the source is greater then computed threshold level)
CV_THRESH_BINARY | CV_THRESH_OTSU
is a required flag to perform Otsu thresholding. Because in fact we would like to perform binary thresholding, so we useCV_THRESH_BINARY
(you can use any of 5 flags opencv provides) combined withCV_THRESH_OTSU
文档链接: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#threshold
这篇关于如何在opencv中使用OTSU阈值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!