如何读取/写入CvMat(Java)数组? 在下面的代码中,我将CvMat放入数组中。但阅读似乎没有得到CvMat。
import com.googlecode.javacpp.Pointer;
import com.googlecode.javacv.cpp.opencv_core;
import static com.googlecode.javacv.cpp.opencv_core.CV_IS_MAT;
import com.googlecode.javacv.cpp.opencv_core.CvMat;
import static com.googlecode.javacv.cpp.opencv_core.IPL_DEPTH_32F;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import static com.googlecode.javacv.cpp.opencv_core.cvSize;
public class Ask {
public static void main(String[] args) {
new Ask().go();
}
private void go() {
CvMat matQ = new opencv_core.CvMat(3); //array of 3 CvMat
IplImage i = opencv_core.cvCreateImage(cvSize(10, 10), IPL_DEPTH_32F, 3); //just to have an image
CvMat x = i.asCvMat(); //a CvMat of the image
System.out.println(CV_IS_MAT(x)); //true, it's a mat
matQ.position(0).put(x); //store it to array at position 0
System.out.println(CV_IS_MAT(matQ.position(0))); //false!
System.out.println(CV_IS_MAT(matQ)); //also false
}
}
答案 0 :(得分:0)
如果您有cvMat,例如,如果您阅读了图像路径:
String imgPath =“./ src / Imgs / chessboard.png”;
Mat imgSrc = Highgui.imread(imgPath);
或者如果你创建了cvMat元素:
Mat imgSrc2 = Mat.eye(3,3,CvType.CV_8UC1);
你可以把它转换为java元素IplImage,BufferedImage *:
BufferedImage img;
img = imgIO.Mat2BufferedImage(imgSrc);
使用以下命令在控制台中显示cvmat的内容:
System.out.println(“cvMat element:\ n”+ imgSrc.dump());
如果您只想将一个元素修改为矩阵:
imgSrc.put(row, col, value);
imgSrc.put(2, 2, 1);
*函数Mat2BufferedImage:
// source: http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/
/**
* @param
* @return The output can be assigned either to BufferedImage or to Image
*/
public BufferedImage Mat2BufferedImage(Mat m){
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels()*m.cols()*m.rows();
byte [] b = new byte[bufferSize];
m.get(0,0,b); // get all the pixels
BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return image;
}
答案 1 :(得分:0)
如果您使用Javacv(https://github.com/bytedeco/javacv),这是一项非常简单的任务。
String img ="Image.jpg";
IplImage newImage0 = cvLoadImage(img);
//import static org.bytedeco.javacpp.opencv_core.IplImage;
或
Mat newImage1 = imread(img);
//import org.bytedeco.javacpp.opencv_core.Mat;
//import static org.bytedeco.javacpp.opencv_highgui.*;
如果将其转换为CvMat类型
CvMat imgcvMat0 = newImage0.asCvMat();
CvMat imgcvMat1 = new CvMat(newImage1);
//import org.bytedeco.javacpp.opencv_core.Mat;
与将其转换回IplImage
相同imgcvMat0.asIplImage();
or
imgcvMat0.asBuffer();