1. 用OpenCV验证常用边缘检测方法,
public class EdgeDetection {
private final static String path=System.getProperty("user.dir")+"\\catton.jpg";
static{
platformUtils.loadLibraries();
}
public static void main(String[] args) {
Mat srcimage;
//读取一张灰度图片
srcimage= Imgcodecs.imread(path,Imgcodecs.IMREAD_COLOR);
if (srcimage.empty()) {
System.err.println("加载图片出错,请检查图片路径!");
return;
}
System.out.println(srcimage);
// 索贝尔水平检测 边缘检测
// Imgproc.Sobel(srcimage,dstimg, CvType.CV_8UC1,1, 0);
//索贝尔垂直检测
Mat Sobel_dstimg=new Mat();
// Imgproc.Sobel(srcimage, dstimg, CvType.CV_8UC1,0, 1);
// Canny 边缘检测
Mat canny_dstimg=new Mat();
Imgproc.Canny(srcimage,canny_dstimg,50,240);
//拉普拉斯边检测
Mat laplacian_dstimg=new Mat();
Imgproc.Laplacian(srcimage,laplacian_dstimg,CvType.CV_8UC1);
HighGui.imshow("边缘检测 原图像",srcimage);
HighGui.imshow("边缘检测 Canny输出图像",canny_dstimg);
HighGui.imshow("边缘检测 Laplacian输出图像",laplacian_dstimg);
// 无限等待按键按下
HighGui.waitKey(0);
}
}
2. 用OpenCV验证Hough变换检测图像中的直线或圆
package com.gitee.dgw.lesson9;
import com.gitee.dgw.lesson1.platformUtils;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
/**
* @program: learn-opencv
* @description:
* @author: Mr.Dai
* @create: 2020-04-10 22:01
**/
public class HoughDetect {
private final static String path=System.getProperty("user.dir")+"\\line.png";
static{
platformUtils.loadLibraries();
}
public static void main(String[] args) {
Mat srcimage;
//读取一张灰度图片
srcimage= Imgcodecs.imread(path,Imgcodecs.IMREAD_COLOR);
if (srcimage.empty()) {
System.err.println("加载图片出错,请检查图片路径!");
return;
}
System.out.println(srcimage);
Mat dst_img=srcimage.clone();
Imgproc.Canny(srcimage, dst_img, 200, 500, 5, false);
Imgproc.cvtColor(srcimage,dst_img,Imgproc.COLOR_RGB2GRAY);
//dectCircle(srcimage, dst_img);
Mat storage = new Mat();
Imgproc.HoughLinesP(dst_img, storage, 1, Math.PI / 180, 50, 0, 0);
for (int x = 0; x < storage.rows(); x++)
{
double[] vec = storage.get(x, 0);
double x1 = vec[0], y1 = vec[1], x2 = vec[2], y2 = vec[3];
Point start = new Point(x1, y1);
Point end = new Point(x2, y2);
Imgproc.line(srcimage, start, end, new Scalar(0, 0, 255, 255), 1, Imgproc.LINE_4, 0);
}
HighGui.imshow("边缘检测 原图像",dst_img);
HighGui.imshow("边缘检测 Canny输出图像",srcimage);
// 无限等待按键按下
HighGui.waitKey(0);
}
private static void dectCircle(Mat srcimage, Mat dst_img) {
Mat circles = new Mat();
Imgproc.HoughCircles(dst_img, circles, Imgproc.HOUGH_GRADIENT, 1, 100, 440, 50, 0, 345);
//概率霍夫变换)
for (int i = 0; i < circles.cols(); i++)
{
double[] vCircle = circles.get(0, i);
Point center = new Point(vCircle[0], vCircle[1]);
int radius = (int) Math.round(vCircle[2]);
// circle center
Imgproc.circle(srcimage, center, 3, new Scalar(0, 255, 0), -1, 8, 0);
// circle outline
Imgproc.circle(srcimage, center, radius, new Scalar(0, 0, 255), 3, 8, 0);
}
}
}