在Java绑定中循环遍历OpenCV Mat

我正在尝试将使用OpenCV收到的先前答案中的C++方法转换为使用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什么也不能调用。

回答:

如果Mat确实是 灰色 ,则可能是以下类型CV_8U

for (int i = 0; i < gray.rows; i++)

{

for (int j = 0; j < gray.cols; j++)

{

byte pixel = gray.get(i, j);

}

}

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

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

    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);

以上是 在Java绑定中循环遍历OpenCV Mat 的全部内容, 来源链接: utcz.com/qa/416899.html

回到顶部