Android+OpenCv4實現(xiàn)邊緣檢測及輪廓繪制出圖像最大邊緣
基于Canny算法的邊緣檢測主要有5個步驟,依次是高斯濾波、像素梯度計算、非極大值像素梯度抑制、滯后閾值處理和孤立弱邊緣抑制。Canny在有噪聲的情況下表現(xiàn)好不好,取決于前面的降噪過程,可以手動做高斯處理提高識別率。
/**image 輸入圖像,必須是CV_8U的單通道或者三通道圖像。edges 輸出圖像,與輸入圖像具有相同尺寸的單通道圖像,且數(shù)據(jù)類型為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);//轉(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中的索引,若為負數(shù),表示繪制全部輪廓。 * * 參數(shù)四:color,繪制輪廓的顏色。 * * 參數(shù)五:thickness,繪制輪廓的線條粗細。若為負數(shù),那么繪制輪廓的內(nèi)部。 * * 參數(shù)六: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(); }
最終效果圖
獲得矩形坐標點以后,后期可以做裁剪,旋轉(zhuǎn)之類操作,可以自行研究。
到此這篇關(guān)于Android+OpenCv4實現(xiàn)邊緣檢測及輪廓繪制出圖像最大邊緣的文章就介紹到這了,更多相關(guān)Android OpenCv4邊緣檢測內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Kotlin + Flow 實現(xiàn)Android 應(yīng)用初始化任務(wù)啟動庫2. 每日六道java新手入門面試題,通往自由的道路--多線程3. ASP.NET泛型三之使用協(xié)變和逆變實現(xiàn)類型轉(zhuǎn)換4. AJAX實現(xiàn)省市縣三級聯(lián)動效果5. 快速解決ajax返回值給外部函數(shù)的問題6. ASP.NET MVC視圖頁使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解7. jsp文件下載功能實現(xiàn)代碼8. 每日六道java新手入門面試題,通往自由的道路9. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法10. SpringBoot+SpringCache實現(xiàn)兩級緩存(Redis+Caffeine)
