Android+OpenCv4實(shí)現(xiàn)邊緣檢測及輪廓繪制出圖像最大邊緣
基于Canny算法的邊緣檢測主要有5個(gè)步驟,依次是高斯濾波、像素梯度計(jì)算、非極大值像素梯度抑制、滯后閾值處理和孤立弱邊緣抑制。Canny在有噪聲的情況下表現(xiàn)好不好,取決于前面的降噪過程,可以手動(dòng)做高斯處理提高識(shí)別率。
/**image 輸入圖像,必須是CV_8U的單通道或者三通道圖像。edges 輸出圖像,與輸入圖像具有相同尺寸的單通道圖像,且數(shù)據(jù)類型為CV_8U。threshold1 第一個(gè)滯后閾值。threshold2 第二個(gè)滯后閾值。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,線條類型。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(); }
最終效果圖
獲得矩形坐標(biāo)點(diǎn)以后,后期可以做裁剪,旋轉(zhuǎn)之類操作,可以自行研究。
到此這篇關(guān)于Android+OpenCv4實(shí)現(xiàn)邊緣檢測及輪廓繪制出圖像最大邊緣的文章就介紹到這了,更多相關(guān)Android OpenCv4邊緣檢測內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Java類加載機(jī)制實(shí)現(xiàn)步驟解析2. python3實(shí)現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)3. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案4. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享5. PHP循環(huán)與分支知識(shí)點(diǎn)梳理6. ASP常用日期格式化函數(shù) FormatDate()7. html小技巧之td,div標(biāo)簽里內(nèi)容不換行8. XML入門的常見問題(一)9. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法10. jsp文件下載功能實(shí)現(xiàn)代碼
