Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void otsu() {
- char fname[10000];
- while (openFileDlg(fname))
- {
- Mat img = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- imshow("original image", img);
- Mat dst = Mat::zeros(img.rows, img.cols, CV_8UC1);
- for (int i = 0; i < 256; i++)
- {
- histValues[i] = 0;
- }
- for (int i = 0; i < img.rows; i++)
- {
- for (int j = 0; j < img.cols; j++)
- {
- histValues[img.at<uchar>(i, j)]++;
- }
- }
- for (int i = 0; i < 256; i++)
- {
- histNorm[i] = (double)histValues[i] / 256;
- }
- showHistogram("MyHist", histValues, 256, 500);
- showHistogram("MyHistNormalized", histNorm, 256, 500);
- double miu = 0;
- double suma = 0, sumaB = 0;
- int N, threshold, q1 = 0, q2 = 0, miu1 = 0, miu2 = 0;
- N = img.rows * img.cols;
- double teta = 0, var_max = 0;
- for (int i = 0; i < 256; i++)
- {
- suma += i * histValues[i];
- }
- for (int t = 0; t < 256; t++)
- {
- q1 += histValues[t];
- if (q1 != 0)
- {
- q2 = N - q1;
- sumaB += t * histValues[t];
- miu1 = sumaB / q1;
- miu2 = (suma - sumaB) / q2;
- teta = q1 * q2 * (miu1 - miu2) * (miu1 - miu2);
- if (teta > var_max)
- {
- threshold = t;
- var_max = teta;
- }
- }
- }
- printf("Threshold = %d", threshold);
- for (int i = 0; i < img.rows; i++) {
- for (int j = 0; j < img.cols; j++)
- {
- if (img.at<uchar>(i, j) > threshold)
- dst.at<uchar>(i, j) = 255;
- else
- dst.at<uchar>(i, j) = 0;
- }
- }
- imshow("Otsu", dst);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement