/**
image 輸入圖像,必須是CV_8U的單通道或者三通道圖像。
edges 輸出圖像,與輸入圖像具有相同尺寸的單通道圖像,且數據類型為CV_8U。
threshold1 第一個滯后閾值。
threshold2 第二個滯后閾值。
apertureSize Sobel算子的直徑。
L2gradient 計算圖像梯度幅值方法的標志。默認為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);//轉換成灰度圖
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();
ListMatOfPoint> contours = new ArrayListMatOfPoint>();
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;
}
}
/**
* 參數一:image,待繪制輪廓的圖像。
*
* 參數二:contours,待繪制的輪廓集合。
*
* 參數三:contourIdx,要繪制的輪廓在contours中的索引,若為負數,表示繪制全部輪廓。
*
* 參數四:color,繪制輪廓的顏色。
*
* 參數五:thickness,繪制輪廓的線條粗細。若為負數,那么繪制輪廓的內部。
*
* 參數六:lineType,線條類型。FILLED LINE_4 4連通 LINE_8 8連通 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();
}
到此這篇關于Android+OpenCv4實現邊緣檢測及輪廓繪制出圖像最大邊緣的文章就介紹到這了,更多相關Android OpenCv4邊緣檢測內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!