本文在边缘检测的基础上继续,即将上文边缘检测的结果(矩阵)输入,然后进一步发现轮廓并绘制
这里先将opencv库的加载设置为类的静态代码块,在相关方法代码体里面不再声明
1 2 3 4 5 6 7 8
| static { try { NativeLoader.loadLibrary(Core.NATIVE_LIBRARY_NAME); } catch (IOException e) { e.printStackTrace(); } }
|
下面是轮廓绘制的相关方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
static List<MatOfPoint> find_contours(Mat image, boolean onBlank) { Mat imageBW = new Mat();
Imgproc.cvtColor(image, imageBW, Imgproc.COLOR_BGR2GRAY); Imgproc.Canny(imageBW,imageBW,100.0,300.0,3, true);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Imgproc.findContours(imageBW, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); return contours;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| static Scalar BLACK = new Scalar(0,0,0) ;
static Mat draw_contours(Mat originalMat, List<MatOfPoint> contours, int thickness) { Mat target = new Mat(originalMat.height(), originalMat.width(), CvType.CV_8UC3, WHITE);
for (int i = 0; i < contours.size(); i++) Imgproc.drawContours(target, contours, i, BLACK, thickness);
return target; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public static void main(String[] args) { Mat kittens = imread("images/three_black_kittens.jpg"); List<MatOfPoint> contours = find_contours(kittens, true);
Mat target = draw_contours(kittens, contours, 7); imwrite("output/kittens-contours-7.png", target);
Mat masked = mask_on_bg(target, "images/light-blue-gradient.jpg"); imwrite("output/kittens-masked.png", masked);
target = draw_contours(kittens, contours, 3); imwrite("output/kittens-contours-3.png", target); }
|
原图

处理后


下面是使用掩模的输出
1 2 3 4 5 6 7
| static Mat mask_on_bg(Mat mask, String backgroundFilePath) { Mat target = new Mat(mask.height(),mask.width(),CvType.CV_8UC3,WHITE); Mat bg = imread(backgroundFilePath); Imgproc.resize(bg, bg, target.size()); bg.copyTo(target, mask); return target; }
|