我正在寻找将图像像素数据提取到整数列表(或任何数字表示)中。例如,具有2×2白色图像,结果将是[255,255,255,255]。如果图像是生成代码而不是从磁盘读取,Mat.dump()方法会准确地打印图像像素值:
Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
System.out.println("OpenCV Mat: " + m);
Mat mr1 = m.row(1);
mr1.setTo(new Scalar(1));
Mat mc5 = m.col(5);
mc5.setTo(new Scalar(5));
System.out.println("OpenCV Mat data, "+m.total()+" elements:\n" +
m.dump());
准确打印=>
OpenCV Mat: Mat [ 5*10*CV_8UC1, isCont=true, isSubmat=false,
nativeObj=0x1415d50, dataAddr=0x13a6880 ]
OpenCV Mat data, 50 elements:
[ 0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
1, 1, 1, 1, 1, 5, 1, 1, 1, 1;
0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
0, 0, 0, 0, 0, 5, 0, 0, 0, 0]
但如果我写Mat" m"磁盘上的内容,然后我再次读取它,dump()方法吐出奇怪的输出:
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.jpg",m);
m = null;
m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.jpg");
System.out.println("Fresly read m, "+m.total()+" elements:\n"+m.dump());
打印
Fresly read m, 50 elements:
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0,
5, 5, 5, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0;
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
5, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1;
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 5,
5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4,
4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0,
5, 5, 5, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
由于我需要从读取的图像中提取int值,并依赖dump()来表示字符串,这会给我带来麻烦。
修改
我设法使用
简单地提取数据 List<Integer> values = new ArrayList<>();
for (int i = 0; i < m.rows(); i++) {
for (int j = 0; j < m.cols(); j++) {
values.add((int)m.get(i,j)[0]);
}
}
答案 0 :(得分:1)
Mat.dump()是我们的朋友,就像打印垫子名称以显示其属性一样。 (问题标题应更改为不贬低dump()。)imread自动假定已转换为BGR,因此转换为3通道数据,而不是预期的1通道。 imwrite JPEG自动压缩。您可以控制未读转换并减少压缩,但这仍然有一些损耗。
MatOfInt imwrite_flags = new MatOfInt();
imwrite_flags.fromArray(Imgcodecs.IMWRITE_JPEG_QUALITY , 100);
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.jpg",m, imwrite_flags);
m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.jpg", Imgcodecs.IMREAD_UNCHANGED);
您需要无压缩或无损压缩,因此请使用TIFF格式-下面结合TIFF进行示例。 (请参见Is there a way to set specific compression scheme when saving tiff file in opencv?)
String TRAIN_PATH_PROC = "";
Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
System.out.println("OpenCV Mat: " + m);
Mat mr1 = m.row(1);
mr1.setTo(new Scalar(1));
Mat mc5 = m.col(5);
mc5.setTo(new Scalar(5));
System.out.println("OpenCV Mat data, "+m.total()+" elements:\n" +
m.dump());
MatOfInt imwrite_flags = new MatOfInt();
imwrite_flags.fromArray(Imgcodecs.IMWRITE_TIFF_COMPRESSION , 1); // no compression
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m2.tif",m, imwrite_flags);// note name change so both examples can run
// OR
Imgcodecs.imwrite(TRAIN_PATH_PROC+"m.tif",m); // default compression LZW grayscale but lossless, I think
m = null;
m = Imgcodecs.imread(TRAIN_PATH_PROC+"m.tif", Imgcodecs.IMREAD_UNCHANGED);
System.out.println("OpenCV Mat: " + m);
System.out.println("Fresly read m, "+m.total()+" elements:\n"+m.dump());