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

时间:2018-12-19 03:47:22

标签: opencv javacpp

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

结果 enter image description here

以下是相同的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)

结果enter image description here

maven pom

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

原始图片enter image description here

2 个答案:

答案 0 :(得分:1)

我正在使用适用于Python 3.6的OpenCV 4.0.0 | Java 11。

这是我的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);
}

enter image description here enter image description here

答案 1 :(得分:1)

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

我们需要调用new Scalar(255.0)使其执行此处所需的操作: