有两种方法可以做到这一点:一个读取像素之一,或者得到一个矩形的所有像素为Java对整个图像,然后用更大的阵列工作。哪一个最好取决于矩形的大小。下面的代码首先将图像的指定rect部分获取到Java数组中。
import java.awt.Color;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.highgui.Highgui;
public class OpenCVThing
{
public static void main(String[] args)
{
String opencvpath = System.getProperty("user.dir") + "\\lib\\";
System.load(opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll");
// Get the whole rect into smallImg
Mat firstImage = Highgui.imread("capture.png");
System.out.println("total pxels:" + firstImage.total());
// We are getting a column 30 high and 30 wide
int width = 30;
int height = 30;
Rect roi = new Rect(120, 160, width, height);
Mat smallImg = new Mat(firstImage, roi);
int channels = smallImg.channels();
System.out.println("small pixels:" + smallImg.total());
System.out.println("channels:" + smallImg.channels());
int totalBytes = (int)(smallImg.total() * smallImg.channels());
byte buff[] = new byte[totalBytes];
smallImg.get(0, 0, buff);
// assuming it's of CV_8UC3 == BGR, 3 byte/pixel
// Effectively assuming channels = 3
for (int i=0; i< height; i++)
{
// stride is the number of bytes in a row of smallImg
int stride = channels * width;
for (int j=0; j<stride; j+=channels)
{
int b = buff[(i * stride) + j];
int g = buff[(i * stride) + j + 1];
int r = buff[(i * stride) + j + 2];
float[] hsv = new float[3];
Color.RGBtoHSB(r,g,b,hsv);
// Do something with the hsv.
System.out.println("hsv: " + hsv[0]);
}
}
}
}
注1:在这种情况下,在浅黄色每个字节表示一个像素的第三,因为我假定格式是CV_8UC3。
total pxels:179305
small pixels:900
channels:3
hsv: 0.5833333
hsv: 0.5833333
hsv: 0.5833333
hsv: 0.5833333
hsv: 0.5833333
etc ...
见this page和docs的更详细一点
的'CvRect收费=新CvRect(firstImage.get:
代码是在这个答案与下面的输出的屏幕截图测试(160,120,30,30));''实际上并没有用于获取CvRect无法将其作为参数的图像,我在我的问题中使用它来证明我想获取该图像的该区域。 – cuber
我得到的图像我不确定'CV类型'我使用的图像是,我从视频捕获的帧中获取图像,然后尝试获取该图像的值。这就是'mat2Img.getImage(mat2Img.mat);'它是Mat2Image的一个对象。 – cuber
firstImage.type();将返回一个int,它表示http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat-type上的类型之一不知道如何转换Java中的数字。 –