Opencv3 C++ VS2017 study notes 11 basic threshold operation

  • Image threshold Threshold
    • Set a value, and perform some operation on the pixels whose pixels are higher or lower than this value, that is, threshold operation
    • API: threshold(src, dst, value, value_max, type);
      • type is the Treshold type
      • Parameters: original image, output image, initial threshold, maximum threshold, threshold type
      • Otsu algorithm: automatically determine the optimal threshold
        • Replace the value value with TRESH_OTSU
        • 或者threshold(gray, dst, 0, 255, THRESH_OTSU | value);
          • A threshold range of 0-255 is specified
        • Principle: Traverse all possible thresholds, and calculate the variance of two types of pixels (pixel values ​​above and below the threshold) as a result of calculating each threshold. The Otsu algorithm will make the following formula have a minimum
          • \large \sigma ^{2}_{w} = w_{1}(t)\sigma^2_{1}+w_{2}(t)\sigma^2_{2}
    • An adaptive threshold is recorded in the previous notes. This is a different thresholding method. Compared with the general thresholding operation, the effect is very good when the difference between light and dark is large.
      • This adaptiveTreshold() can only handle single-channel 8-bit pictures
    • Threshold type
      • TRESHOLD_BINARY threshold binarization
      • TRESHOLD_BINARY_INV threshold de-binarization
      • TRESHOLD_TRUNC threshold truncation
      • TRESHOLD_TOZERO threshold is zero
      • TRESHOLD_TOZERO_INV threshold is reversed to zero
#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include <string>

using namespace std;
using namespace cv;
int threshold_value = 127;
int threshold_max = 255;
void Threshold_demo(int, void*);
int value = 1;
int value_max = 5;
Mat src0, gray, bin, dst;
int main(int argc, char ** argv)
{
	src0 = imread("C:\\Users\\xujin\\Desktop\\test1.JPG");
	if (!src0.data)
	{
		cout << "no image";
		return -1;
	}
	namedWindow("src0_image", WINDOW_AUTOSIZE);
	imshow("src0_image", src0);
	namedWindow("dst_image", WINDOW_AUTOSIZE);

	createTrackbar("threshold_value", "dst_image", &threshold_value, threshold_max, Threshold_demo);
	createTrackbar("value_choice", "dst_image", &value, value_max, Threshold_demo);
	waitKey(0);
	return 0;
}
void Threshold_demo(int, void*)
{
	cvtColor(src0, gray, CV_RGB2GRAY);
	//threshold(gray, dst, threshold_value, threshold_max, value);
	//自动调节阈值
	threshold(gray, dst, 0, 255, THRESH_OTSU | value);
	imshow("dst_image", dst);
}

 

Guess you like

Origin blog.csdn.net/Mrsherlock_/article/details/104520759