Apache POI library excel file read to make Mat in OpenCV (Java, c++)
/ 아파치 POI 라이브러리 엑셀파일 읽기 OpenCV Mat 만들기 (java, c++)
Preview
Matlab 에서의 matrix 값들이 Java 에서 OpenCV 를 쓴 matrix 값과 비교해서
정확하게 진행되는지 확인하려고 Excel -> Mat 과 Mat -> Excel 을 구현함
I needed comparison of Matrix in Matlab and Matrix in OpenCV(Java) to check correct value or not. So I had to make class Excel data -> Mat data and Mat data -> Excel data.
Code.. lemme see code!!!!!!!
코드.. 코드를 보자!!!!!
// Load excel data to Mat using apache POI and JavaCV
// Input params below
// absPath -> absolutePath of the file we'll load (Including fileName)
// startRow -> start index of row
// rowLength -> how long? in row
// startCol -> start index of column
// colLength -> how long? in column
// 아파치 POI lib 를 써서 읽어오고 Mat (OpenCV) 으로 저장한다.
// Input 파라미터들
// absPath -> 로드해올 파일 전체 경로(파일이름 포함)
// startRow -> 행의 시작 index
// rowLength -> 읽을 행 길이
// startCol -> 열의 시작 index
// colLength -> 읽을 열 길이
public static Mat loadExcelData2Mat(String absPath, int startRow, int rowLength, int startCol, int colLength) {
Mat resultMat = null;
double[] resultVal = new double[2];
FileInputStream fis = null;
XSSFWorkbook workbook = null;
try
{
fis = new FileInputStream(absPath);
workbook = new XSSFWorkbook(fis);
XSSFSheet curSheet;
XSSFRow curRow;
XSSFCell curCell;
// Sheet 개수에 따라 실수만 있는지 허수부도 있는 2C 인지 확인
if (workbook.getNumberOfSheets() == 1)
{
resultMat = Mat.zeros(rowLength, colLength, CvType.CV_64F);
}
else if (workbook.getNumberOfSheets() == 2)
{
resultMat = Mat.zeros(rowLength, colLength, CvType.CV_64FC2);
}
else
{
return null;
}
for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); ++sheetIndex)
{
int resultMatRowIndex = 0;
curSheet = workbook.getSheetAt(sheetIndex); //Sheet
for (int rowIndex = startRow; rowIndex < startRow + rowLength; ++rowIndex)
{
int resultMatColIndex = 0;
curRow = curSheet.getRow(rowIndex); //Row
for (int colIndex = startCol; colIndex < startCol + colLength; ++colIndex)
{
curCell = curRow.getCell(colIndex); //Col (Cell)
CellType cellType = curCell.getCellType();
if (cellType.equals(CellType.NUMERIC))
{
resultVal = resultMat.get(resultMatRowIndex, resultMatColIndex);
resultVal[sheetIndex] = curCell.getNumericCellValue();
resultMat.put(resultMatRowIndex, resultMatColIndex++, resultVal);
// System.out.println(curCell.getNumericCellValue());
}
else if (cellType.equals(CellType.STRING))
{
System.out.println(curCell.getStringCellValue());
}
}
++resultMatRowIndex;
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (workbook != null)
workbook.close();
if (fis != null)
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return resultMat;
}