javacpp-opencv drawContours 产生与 python 不同的结果?

javacpp-opencv drawContours produce different result than in python?

javacpp-opencv drawContours 产生的结果比 python 错误。

这是 java 中使用 drawContours 函数的代码:

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);
}

结果

这里是相同的python代码:

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)

结果

maven pom

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

原图

我正在为 Python 3.6 使用 OpenCV 4.0.0 | Java11.

这是我的Java测试代码和结果:

public static void main(String[] args){
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME); 

    Mat im = Imgcodecs.imread("7KXY.jpg");
    Imgproc.cvtColor(im, im, Imgproc.COLOR_BGR2GRAY);
    Imgproc.threshold(im,im, 230, 255, Imgproc.THRESH_BINARY_INV);

    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(im, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    im = Mat.zeros(im.rows(), im.cols(), CvType.CV_8UC1);

    Imgproc.drawContours(im, contours, -1, new Scalar(255), 1, 8, hierarchy, 2, new Point(0,0));
    Imgcodecs.imwrite( "dst.jpg", im);
}

问题是 new Scalar(255) 创建了一个具有未定义颜色的标量对象数组:

我们需要调用 new Scalar(255.0) 让它做这里需要的事情: