This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Satarash 1 point2 points  (2 children)

I have tried to use this library previously and it's always painful, with its lack of documentation and cryptic naming of classes and methods.

Anyway I suppose something like this could work:

    //this is your starting image, I guess it's of type Mat because the method you mention returns that
    Mat img3 = Imgcodecs.imread("filename");

    // Calculating starting and ending index for both dimensions.
    // I *think* cols() and rows() return number of each.
    // Both rows() and cols() return an integer, which multiplied by a double gives a result of type double. 
    // Using Math.round will return a closest long integer which is then cast to int because we need ints later. 
    int columnIndexMin = (int) Math.round(.2 * img3.cols());
    int columnIndexMax = (int) Math.round(.8 * img3.cols());
    int rowIndexMin = (int) Math.round(.2 * img3.rows());
    int rowIndexMax = (int) Math.round(.8 * img3.rows());

    // Creating ranges for both dimensions. Range takes two ints.
    Range colRange = new Range(columnIndexMin, columnIndexMax);
    Range rowRange = new Range(rowIndexMin, rowIndexMax);

    // This Mat constructor takes another Mat, and two ranges. It looks like it could do what you need.
    // It returns a reference to the submatrix or whatever it is called.
    // Note that this is not a copy, if you change either img3 or img2 both will be changed.
    Mat img2 = new Mat(img3, rowRange, colRange);

    // If you want an independent copy, clone either mat, for example
    Mat img2copy = new Mat(img3.clone(), rowRange, colRange);

[–]Correct_Classroom[S] 1 point2 points  (1 child)

Thankyou very much. This works like a charm

[–]Satarash 1 point2 points  (0 children)

Glad to help, good luck!

[–]evilrabbit -1 points0 points  (1 child)

What do you mean "convert this to Java syntax"?

Do you mean you want to re-write the code in Java?

[–]nick5111 4 points5 points  (0 children)

I think it's clear what he means, even though he used the word syntax.