Home > front end >  javacpp-opencv drawContours produce different result than in python?
javacpp-opencv drawContours produce different result than in python?

Time:01-12

javacpp-opencv drawContours produce wrong result than in python.

Here is the code in java to use drawContours function:

public static void main(String[] args){
    Mat im = imread("7KXY.png");
    cvtColor(im, im, CV_BGR2GRAY);
    threshold(im,im, 230, 255, THRESH_BINARY_INV);

    MatVector contours = new MatVector();
    Mat hierarchy = new Mat();
    findContours(im, contours,hierarchy,RETR_TREE  ,CHAIN_APPROX_SIMPLE);

    im = new Mat(im.rows(),im.cols(),CV_8UC1);
    drawContours(im, contours, -1, new Scalar(255), 1, 8, hierarchy, 2, new Point(0,0));
    imwrite( "ccc.jpg", im);
}

result enter image description here

Here is identical python code:

im = cv2.imread(r'7KXY.png')
im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
thresh,im = cv2.threshold(im, 230, 255, cv2.THRESH_BINARY_INV)

im2, contours, hierarchy = cv2.findContours(im, cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE)

im = np.zeros(im.shape).astype(dtype='uint8')
cv2.drawContours(im, contours, -1, (255), 1,8, hierarchy, 2,(0,0))
cv2.imwrite(r"asd.jpg",im)

result enter image description here

maven pom

<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv-platform</artifactId>
    <version>1.4.3</version>
</dependency>

The original pictureenter image description here

CodePudding user response:

The issue is that new Scalar(255) creates an array of Scalar objects with undefined color:

  • enter image description here enter image description here

  • Related