1

openCV SDK for android 附带的名为“color-blob-detection”的示例项目可用于识别特定颜色的区域。我需要的是提取该区域并将其作为位图保存到手机内存中。

这是我到目前为止所理解的:

有一个轮廓列表:

List<MatOfPoint> contours = new ArrayList<MatOfPoint>();

使用以下方法找到轮廓:

Imgproc.findContours(mDilatedMask, contours, mHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

这找到最大轮廓区域:

double maxArea = 0;
        Iterator<MatOfPoint> each = contours.iterator();
        while (each.hasNext()) {
            MatOfPoint wrapper = each.next();
            double area = Imgproc.contourArea(wrapper);
            if (area > maxArea)
                maxArea = area;
        }

我想知道如何将这个最大的区域作为位图保存到 sdcard 中。任何帮助是极大的赞赏!

//////编辑

这用于绘制轮廓。我不确定这是否是正确的方法:

 Imgproc.cvtColor(mDilatedMask, mDilatedMask, Imgproc.COLOR_GRAY2BGR);
            Imgproc.drawContours(mDilatedMask, contours, -1, new Scalar(0, 255, 0), 1);
Toast.LENGTH_LONG).show();
            Bitmap bmpOut = Bitmap.createBitmap(mDilatedMask.cols(), mDilatedMask.rows(), Bitmap.Config.ARGB_8888);

            Utils.matToBitmap(mDilatedMask, bmpOut);

            try {
                bmpOut.compress(CompressFormat.JPEG, 100, new FileOutputStream("/sdcard/mediaAppPhotos/bigrect.jpg"));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
4

1 回答 1

1

这是在 C++ 中实现的用于查找最大轮廓并将其绘制为图像的代码,我对 OpenCV JAVA 不熟悉,但您可以在 JAVA 中使用类似的东西。

#include <iostream>
#include "opencv2\highgui\highgui.hpp"
#include "opencv\cv.h"

using namespace cv;
using namespace std;
int main()
{
 int largest_area=0;
 int largest_contour_index=0;
 Rect bounding_rect;

 Mat src = imread("src.jpg"); //Load source image
 Mat thr(src.rows,src.cols,CV_8UC1);
 Mat dst(src.rows,src.cols,CV_8UC1,Scalar::all(0));
 cvtColor(src,thr,CV_BGR2GRAY); //Convert to gray
 threshold(thr, thr,25, 255,THRESH_BINARY); //Threshold the gray

    vector<vector<Point>> contours; // Vector for storing contour
    vector<Vec4i> hierarchy;

    findContours( thr, contours, hierarchy,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image

     for( int i = 0; i< contours.size(); i++ ) // iterate through each contour.
      {
       double a=contourArea( contours[i],false);  //  Find the area of contour
       if(a>largest_area){
       largest_area=a;
       largest_contour_index=i;                //Store the index of largest contour
       bounding_rect=boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
       }

      }

 Scalar color( 255,255,255);
 drawContours( dst, contours,largest_contour_index, color, CV_FILLED, 8, hierarchy ); // Draw the largest contour using previously stored index.
 rectangle(src, bounding_rect,  Scalar(0,255,0),1, 8,0); 
 imshow( "src", src );
 imshow( "largest Contour", dst );
 waitKey(0);
}

希望这些帮助....

于 2013-09-18T04:51:01.260 回答