4

我正在尝试将 C++ 方法从使用 OpenCV 收到的先前答案转换为使用 OpenCV Java 绑定的 Java

C++ 代码:

cv::Mat gray;
cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
                                       cv::Size(2 * erosion_size + 1, 2 * erosion_size + 1),
                                       cv::Point(erosion_size, erosion_size) );
cv::erode(gray, gray, element);
 // Scan the image searching for points and store them in a vector
std::vector<cv::Point> points;
cv::Mat_<uchar>::iterator it = gray.begin<uchar>();
cv::Mat_<uchar>::iterator end = gray.end<uchar>();
for (; it != end; it++)
{
    if (*it) 
        points.push_back(it.pos()); 
}

我不知道如何gray像在 C 代码中那样循环变量。以下是我到目前为止所得到的:

Java 代码:

Mat gray = new Mat();
Mat element = Imgproc.getStructuringElement(
                Imgproc.MORPH_CROSS, new Size(2 * erosion_size + 1, 2 * erosion_size + 1), new Point(erosion_size, erosion_size)
        );
Imgproc.erode(img, gray, element);
List <Point> p = new ArrayList<Point>();
//How to loop through the gray variable?

我浏览了API,似乎Mat确实有获取方法rowscols但我无法调用Iterator任何东西..

4

1 回答 1

4

如果Mat是真的gray,它可能是类型CV_8U

for (int i = 0; i < gray.rows; i++)
{
    for (int j = 0; j < gray.cols; j++)
    {
        byte pixel = gray.get(i, j);
    }
}

我没有设置环境来测试此代码。有关更多信息,请查看此线程

如果您使用的是JavaCV,前段时间我编写了一个代码来迭代彩色图像的像素并将其转换为灰度,如下所示:

    IplImage imageSrc = cvLoadImage("pipeline.png", CV_LOAD_IMAGE_COLOR);
    if (imageSrc == null) 
    {
        System.out.println("!!! Failed loading image");
        return;
    }

    double r, g, b;
    r = g = b = 0.0;               

    IplImage imageDst = IplImage.create(imageSrc.width(), imageSrc.height(), IPL_DEPTH_8U, 3);

    CvMat imagePixels = CvMat.createHeader(imageDst.height(), imageDst.width(), CV_32FC1);  
    cvGetMat(imageDst, imagePixels, null, 0); 
    int x, y;
    for(y=0; y<imageSrc.height(); y++)
       for(x=0; x<imageSrc.width(); x++)
       {
            CvScalar rgb = cvGet2D(imagePixels, y, x);
            r = rgb.val(0);
            g = rgb.val(2);
            b = rgb.val(1);

            double gray = (r + g + b) / 3;

            CvScalar scalar = new CvScalar();
            scalar.setVal(0, gray);
            scalar.setVal(1, gray);
            scalar.setVal(2, gray);
           cvSet2D(imagePixels, y, x, scalar);
       }
       imageDst = new IplImage(imagePixels);  

       IplImage result = new IplImage(imagePixels); 
       cvSaveImage("manual_gray.png", result);

       cvReleaseImage(imageSrc); 
于 2013-03-30T18:09:18.797 回答