OTSU
#include
#include
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int OTSU(cv::Mat srcImage)
{
int nCols = srcImage.cols;
int nRows = srcImage.rows;
int threshold = 0;
int nSumPix[256];
float nProDis[256];
for (int i = 0; i < 256; i++)
{
nSumPix[i] = 0;
nProDis[i] = 0;
}
for (int i = 0; i < nCols; i++)
{
for (int j = 0; j < nRows; j++)
{
nSumPix[(int)srcImage.at(i, j)]++;
}
}
for (int i = 0; i < 256; i++)
{
nProDis[i] = (float)nSumPix[i] / (nCols * nRows);
}
float w0, w1, u0_temp, u1_temp, u0, u1, delta_temp;
double delta_max = 0.0;
for (int i = 0; i < 256; i++)
{
w0 = w1 = u0_temp = u1_temp = u0 = u1 = delta_temp = 0;
for (int j = 0; j < 256; j++)
{
if (j <= i)
{
w0 += nProDis[j];
u0_temp += j * nProDis[j];
}
else
{
w1 += nProDis[j];
u1_temp += j * nProDis[j];
}
}
u0 = u0_temp / w0;
u1 = u1_temp / w1;
delta_temp = (float)(w0 *w1* pow((u0 - u1), 2));
if (delta_temp > delta_max)
{
delta_max = delta_temp;
threshold = i;
}
}
return threshold;
}
int main()
{
cv::Mat srcImage = cv::imread("images/hand1.jpg");
if (!srcImage.data)
return 1;
cv::Mat srcGray;
cv::cvtColor(srcImage, srcGray, CV_RGB2GRAY);
cv::imshow("srcGray", srcGray);
int ostuThreshold = OTSU(srcGray);
std::cout << ostuThreshold << std::endl;
cv::Mat otsuResultImage =
cv::Mat::zeros(srcGray.rows, srcGray.cols, CV_8UC1);
for (int i = 0; i < srcGray.rows; i++)
{
for (int j = 0; j < srcGray.cols; j++)
{
if (srcGray.at(i, j) > ostuThreshold)
otsuResultImage.at(i, j) = 255;
else
otsuResultImage.at(i, j) = 0;
}
}
cv::imshow("otsuResultImage", otsuResultImage);
cv::waitKey(0);
return 0;
}
霍夫变换
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include
using namespace cv;
using namespace std;
int main( )
{
cv::Mat srcImage =
cv::imread("images/Pic3_3.png", 0);
if (!srcImage.data)
return -1;
cv::Mat edgeMat, houghMat;
Canny(srcImage, edgeMat, 50, 200, 3);
cvtColor(edgeMat, houghMat, CV_GRAY2BGR);
#if 0
vector lines;
HoughLines(edgeMat, lines, 1, CV_PI/180, 100, 0, 0 );
for( size_t i = 0; i < lines.size(); i++ )
{
float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
pt1.x = cvRound(x0 + 1000*(-b));
pt1.y = cvRound(y0 + 1000*(a));
pt2.x = cvRound(x0 - 1000*(-b));
pt2.y = cvRound(y0 - 1000*(a));
line( houghMat, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
}
#else
vector lines;
HoughLinesP(edgeMat, lines, 1, CV_PI/180, 50, 50, 10 );
for( size_t i = 0; i < lines.size(); i++ )
{
Vec4i l = lines[i];
line( houghMat, Point(l[0], l[1]),
Point(l[2], l[3]), Scalar(255,255,255), 3, CV_AA);
}
#endif
cv::imshow("srcImage", srcImage);
cv::imshow("houghMat", houghMat);
cv::waitKey();
return 0;
}