Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: OpenCV(3.4.3) /opencv/modules/core/src/matrix.cpp:465: error: (-215:Assertion failed) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function 'Mat'
]
at org.opencv.core.Mat.n_submat(Native Method)
at org.opencv.core.Mat.submat(Mat.java:854)
at zenryokuservice.opencv.fx.ImageSlicerMain.loadImg(ImageSlicerMain.java:78)
at zenryokuservice.opencv.fx.ImageSlicerMain.main(ImageSlicerMain.java:107)
このエラーメッセージに、遭遇したら単純に、読み込んだファイルのサイズと読み込もうとしているサイズの指定がうまくいっていません。指定するサイズが不適切な感じです。
自分の実装したコードは下の様なものです。
URL p = this.getClass().getResource("/" ); System.out.println("*** " + p.getPath()); Mat downloadFile = Imgcodecs.imread(p.getPath());
自分の場合は上のようなコードで、リソース(ファイル)が取得できていませんでした。それゆえにエラー。
下の部分はデバッグ用に実装した部分です。取得したパスの確認をしました。
System.out.println("*** " + p.getPath())
Class#getResource()とnew File(パス)で実装する時にルートになる場所が変わるので注意が必要です。
作成したImageSlicerでイメージファイルを切り刻みます。
ソースコードは、こちらに有ります。
ポイントは、ループする最中に、xPosとyPosで切り出すファイルの位置をづらしていくところです。
そして、確認用のSwingは最後に出力するイメージが表示されます。。。
private ImageIcon dstImage(String fileName, Mat downloadFile, String sufix, int xPos, int yPos, int size, int times) { Rect roi = new Rect(xPos, yPos, size, size); System.out.println("x: " + roi.x); System.out.println("y: " + roi.y); Mat target = downloadFile.submat(roi); MatOfByte bytes = new MatOfByte(); Imgcodecs.imencode(".png", target, bytes); byte[] b = bytes.toArray(); InputStream in = new ByteArrayInputStream(b); BufferedImage buf = null; try { buf = ImageIO.read(in); File out = new File("resources/dst/" + fileName + "_" + sufix + ".png"); ImageIO.write(buf, "png", out); } catch(IOException e) { e.printStackTrace(); } return new ImageIcon(buf); }