/**
* 读取图片生成矩阵MAT
* @param imgPath 图片路径
* @return
*/
public static Mat converMat(String imgPath){
return Imgcodecs.imdecode(new MatOfByte(fileToBytes(imgPath)),
Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
}
/**
* 读取图片字节流
* @param filePath
* @return
*/
public static byte[] fileToBytes(String filePath) {
byte[] buffer = null;
File file = new File(filePath);
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] b = new byte[2048];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
buffer = bos.toByteArray();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
} finally {
try {
if (null != bos) {
bos.close();
}
} catch (IOException ex) {
} finally{
try {
if(null!=fis){
fis.close();
}
} catch (IOException ex) {
}
}
}
return buffer;
}
如果直接用 Imgcodecs.imread(imgPath)函数,可能会遇到出错,所以先把图片转成byte[],再由byte转成Mat。
古智云开 您的个人图书馆