在圖像處理和計算機視覺領(lǐng)域中恰响,如何沖當(dāng)前的退選哪個中提取出所需要的特征信息是圖像識別的關(guān)鍵所在。在許多應(yīng)用場合中需要快速的檢測出直線或者是圓涌献。其中一種非常有效的的解決方法是霍夫變換胚宦,其為圖像處理中從圖像中識別幾何圖形的基本方法。
霍夫變換的概述
霍夫變換在opencv中分為霍夫線變換和霍夫圓變換
opencv中的霍夫線變換
霍夫線變換是一種用來尋找直線的方法燕垃,在使用霍夫線變換之前枢劝,首先對圖像進行邊緣檢測,即霍夫線變換的直接輸入只能是邊緣二值圖像卜壕。
opencv中霍夫線變換有三種
(1)標(biāo)準(zhǔn)霍夫變換(SHT)您旁,由HoughLines調(diào)用
(2)多尺度霍夫變換(MSHT),由HoughLines調(diào)用轴捎,
(3)累計概率霍夫變換(PPHT)鹤盒,由HoughLinesP調(diào)用蚕脏,可以在一定范圍內(nèi)進行霍夫變換
霍夫變換的原理
標(biāo)準(zhǔn)霍夫變換函數(shù):HoughLines()
void HoughLines( InputArray image,// 源圖像,需為8位的單通道二進制圖像侦锯,可以將任意的源圖像載進來驼鞭,并由函數(shù)修改成此格式再放進來
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OutputArray lines,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? double rho,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double theta,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?int threshold,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double srn = 0,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double stn = 0,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double min_theta = 0,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double max_theta = CV_PI );
參數(shù)詳解
代碼實現(xiàn)
NSString *image = @"lou.png";? ??
UIImage *image1 = [UIImage imageNamed:image];? ??
Mat im;? ? UIImageToMat(image1, im);? ? ? ?
?if (im.empty()) {? ? ? ? ??
? ? ? return;??
? }??
? // 創(chuàng)建零時變量? ??
Mat midImage,dstImage;? ??
// 進行邊緣檢測和轉(zhuǎn)換為灰度圖? ??
Canny(im, midImage, 50, 200);? ??
cvtColor(midImage, dstImage, COLOR_GRAY2BGR);? ? ? ??
// 進行霍夫變換? ??
std::vector<Vec2f>lines;// 定義一個矢量lines,存放得到的線段矢量集合
HoughLines(midImage, lines, CV_PI/180, 150, 0);
for (size_t i = 0; i < lines.size(); i++) {
float rho = lines[i][0],theta = lines[i][1];
cv::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(dstImage, pt1, pt2, Scalar(100,100,195));
}
self.secondImageView.image = MatToUIImage(dstImage);
效果
累計概率霍夫變換函數(shù):HoughLinesP() 函數(shù)
void HoughLinesP( InputArray image,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? OutputArray lines,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double rho,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double theta,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?int threshold,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double minLineLength = 0,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?double maxLineGap = 0
?);
參數(shù)詳解
代碼實現(xiàn)
NSString *image = @"xixi.jpg";? ??
UIImage *image1 = [UIImage imageNamed:image]; ??
?Mat im;? ??
UIImageToMat(image1, im);? ? ? ?
?if (im.empty()) {? ? ? ? ? ? ? ? return;? ? }? ??
// 創(chuàng)建零時變量? ?
?Mat midImage,dstImage;? ??
// 進行邊緣檢測和轉(zhuǎn)換為灰度圖? ?
?Canny(im, midImage, 50, 200,3);? ??
cvtColor(midImage, dstImage, CV_GRAY2BGR);? ?
std::vector<Vec4i>lines;// 定義一個矢量lines尺碰,存放得到的線段矢量集合
HoughLinesP(midImage,lines, 1,CV_PI/180, 80, 50, 10);
for (size_t i = 0; i < lines.size(); i++) {
Vec4i l = lines[i];
line(dstImage, cv::Point(l[0],l[1]),cv::Point(l[2],l[3]) , Scalar(186,88,255),1,LINE_AA);
}
self.secondImageView.image = MatToUIImage(dstImage);
效果