opencv_ex18-圖像放大pyrUp、彩色轉灰階cvtColor、灰階圖像邊緣檢測Laplacian、計算輸入圖各像素,並將結果轉成8位元圖convertScaleAbs、轉二值化threshold [THRESH_OTSU | THRESH_BINARY]
opencv_ex18-圖像放大pyrUp、彩色轉灰階cvtColor、灰階圖像邊緣檢測Laplacian、計算輸入圖各像素,並將結果轉成8位元圖convertScaleAbs、轉二值化threshold [THRESH_OTSU | THRESH_BINARY]
GITHUB:https://github.com/jash-git/CPP_opencv249_ex
Otsu流程:
先計算影像的直方圖
把直方圖強度大於閾值的像素分成一組,把小於閾值的像素分成另一組。
分別計算這兩組的組內變異數,並把兩個組內變異數相加。
將0~255依序當作閾值來計算組內變異數和,總和值最小的就是結果閾值。
OpenCV自適應閾值二值化
一樣是用threshold()函式,使用方式也一樣,只是最後一個參數增加CV_THRESH_OTSU,目前otsu只能使用在8位元圖。
double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)
src:輸入圖,只能輸入單通道,8位元或32位元浮點數影像。
dst:輸出圖,尺寸大小、深度會和輸入圖相同。
thresh:閾值。
maxval:二值化結果的最大值。
type:二值化操作型態,共有THRESH_BINARY、THRESH_BINARY_INV、THRESH_TRUNC、THRESH_TOZERO、THRESH_TOZERO_INV五種。
type從上述五種結合CV_THRESH_OTSU,類似寫成:THRESH_BINARY | CV_THRESH_OTSU
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/ml/ml.hpp> #include <iostream> #include <cstdio> #include <sys/timeb.h> #if defined(WIN32) #define TIMEB _timeb #define ftime _ftime typedef __int64 TIME_T; #else #define TIMEB timeb typedef long long TIME_T; #endif using namespace cv; using namespace std; Mat src;//input image void Pause() { printf("Press Enter key to continue..."); fgetc(stdin); } int main() { Mat input,gray_src,dst; input = imread("Lena_original.jpg"); if (!input.data) { printf("could not load image...\n"); } else { //放大 pyrUp(input, src, Size(input.cols*2, input.rows*2)); GaussianBlur(src, dst, Size(3, 3), 0, 0);//高斯模糊GaussianBlur目的為了給圖像預處理時候減低噪聲(雜訊) cvtColor(dst, gray_src, CV_BGR2GRAY);//彩色轉灰階 imshow("Lena_gray", gray_src); Mat edge_image; char output_title[] = "Laplaiance Result"; Laplacian(gray_src, edge_image, CV_16S, 3); convertScaleAbs(edge_image, edge_image); namedWindow(output_title, CV_WINDOW_AUTOSIZE); imshow(output_title, edge_image); threshold(edge_image, edge_image, 0, 255, THRESH_OTSU | THRESH_BINARY); namedWindow("Laplacian_threshold", CV_WINDOW_AUTOSIZE); imshow("Laplacian_threshold", edge_image); } waitKey(0); Pause(); return 0; }