从python代码(opencv)到Java(android)的端口

时间:2019-04-07 18:46:49

标签: java android python opencv image-processing

我正在尝试将python代码(用于opencv图像处理)转换为android

这是我的python代码

image = cv2.imread("x.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 200, 50)
cv2.imwrite("edged.jpg", edged)

cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None
print (len(cnts))

# loop over the contours
for c in cnts:
    # approximate the contour
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)

    # if the contour has four vertices, then we have found
    # the thermostat display
    if len(approx) == 4:
        displayCnt = approx

        break

output = four_point_transform(image, displayCnt.reshape(4, 2))

这是我的Java代码

                Imgproc.cvtColor(src, src, Imgproc.COLOR_BGRA2GRAY);
                Imgproc.GaussianBlur(src, src, new Size(5,5),0);
                Imgproc.Canny(src,src,50,200);

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


                for(int c = 0; c < contours.size(); c++)
                {
                    MatOfPoint2f approxCurve = new MatOfPoint2f();
                    MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(c).toArray());
                    double approxDistance = Imgproc.arcLength(contour2f,  true)*0.02;
                    Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true);

                    if (approxCurve.toArray().length==4){
                        MatOfPoint points = new MatOfPoint( approxCurve.toArray() );
                        // Get bounding rect of contour
                        Rect rect = Imgproc.boundingRect(points);

                        src = new Mat(src2, rect);
                        Toast.makeText(MainActivity.this,rect.width+" "+rect.x, Toast.LENGTH_LONG).show();
                        break;
                    }
                }

这是经过处理的我的图片

边缘图像:

edged image

(看起来不错)

这是我在python中获得的信息(这是必需的输出)以及我在java中获得的信息

结果

result

如何在Java中获得相同的结果

修改

MatOfPoint points = new MatOfPoint( approxCurve.toArray() );中 我使用points.dump(),发现4个点都在正确的位置

我的问题在这里

Rect rect = Imgproc.boundingRect(points);
src = new Mat(src2, rect);

我尝试使用x,y,width,height创建一个正方形,但事实并非如此! 如何使用四个MatOfPoint点坐标来裁剪图像?

0 个答案:

没有答案