Android+OpenCv4實(shí)現(xiàn)邊緣檢測及輪廓繪制出圖像最大邊緣
實(shí)現(xiàn)步驟:
- 圖像灰度化
- 邊緣檢測
- 根據(jù)Canny檢測得出來的Mat尋找輪廓
- 算出最大輪廓周長or面積
- 根據(jù)獲取到的最大輪廓下標(biāo)進(jìn)行輪廓繪制
- 畫出最大矩形,并返回Rect
Canny邊緣檢測
基于Canny算法的邊緣檢測主要有5個步驟,依次是
高斯濾波、像素梯度計(jì)算、非極大值像素梯度抑制、滯后閾值處理和孤立弱邊緣抑制。Canny在有噪聲的情況下表現(xiàn)好不好,取決于前面的降噪過程,可以手動做高斯處理提高識別率。
/** image 輸入圖像,必須是CV_8U的單通道或者三通道圖像。 edges 輸出圖像,與輸入圖像具有相同尺寸的單通道圖像,且數(shù)據(jù)類型為CV_8U。 threshold1 第一個滯后閾值。 threshold2 第二個滯后閾值。 apertureSize Sobel算子的直徑。 L2gradient 計(jì)算圖像梯度幅值方法的標(biāo)志。默認(rèn)為false **/ public static void Canny(Mat image, Mat edges, double threshold1, double threshold2, int apertureSize, boolean L2gradient)
使用
/**
* canny算法,邊緣檢測
*/
public static Mat canny(Bitmap bitmap) {
Mat mSource = new Mat();
Utils.bitmapToMat(bitmap, mSource);
Mat grayMat = new Mat();
Imgproc.cvtColor(mSource,grayMat,Imgproc.COLOR_BGR2GRAY);//轉(zhuǎn)換成灰度圖
Mat mat = mSource.clone();
Imgproc.Canny(mSource, mat, 75, 200);
return mat;
}

獲取圖像最大矩形
/**
* 返回邊緣檢測之后的最大矩形,并返回
*
* @param cannyMat
*Canny之后的mat矩陣
* @return
*/
public Rect findMaxRect(Mat cannyMat) {
Mat tmp = mSource.clone();
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
// 尋找輪廓
Imgproc.findContours(cannyMat, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
int index = 0;
double perimeter = 0;
// 找出匹配到的最大輪廓
for (int i = 0; i < contours.size(); i++) {
// 最大面積
//double area = Imgproc.contourArea(contours.get(i));
//最大周長
MatOfPoint2f source = new MatOfPoint2f();
source.fromList(contours.get(i).toList());
double length = Imgproc.arcLength(source,true);
if(length>perimeter){
perimeter = length;
index = i;
}
}
/**
* 參數(shù)一:image,待繪制輪廓的圖像。
*
* 參數(shù)二:contours,待繪制的輪廓集合。
*
* 參數(shù)三:contourIdx,要繪制的輪廓在contours中的索引,若為負(fù)數(shù),表示繪制全部輪廓。
*
* 參數(shù)四:color,繪制輪廓的顏色。
*
* 參數(shù)五:thickness,繪制輪廓的線條粗細(xì)。若為負(fù)數(shù),那么繪制輪廓的內(nèi)部。
*
* 參數(shù)六:lineType,線條類型。FILLEDLINE_44連通LINE_88連通 LINE_AA 抗鋸齒
*/
Imgproc.drawContours(
tmp,
contours,
index,
new Scalar(0.0, 0.0, 255.0),
9,
Imgproc.LINE_AA
);
Rect rect = Imgproc.boundingRect(contours.get(index));
// Imgproc.rectangle(tmp, rect, new Scalar(0.0, 0.0, 255.0), 4, Imgproc.LINE_8);
showImg(tmp);
return rect;
}
/**
* 顯示圖像
* @param mat
*/
private void showImg(Mat mat){
Bitmap bitmap = Bitmap.createBitmap(mat.width(), mat.height(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bitmap);
mIvSrc.setImageBitmap(bitmap);
mat.release();
}
最終效果圖

獲得矩形坐標(biāo)點(diǎn)以后,后期可以做裁剪,旋轉(zhuǎn)之類操作,可以自行研究。
到此這篇關(guān)于Android+OpenCv4實(shí)現(xiàn)邊緣檢測及輪廓繪制出圖像最大邊緣的文章就介紹到這了,更多相關(guān)Android OpenCv4邊緣檢測內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信