import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;
import org.opencv.imgproc.Imgproc;
import org.python.core.util.FileUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
public class Laplacian1 {
public static void main(String[] args) throws IOException {
String picPath = "F:/Users/Admin/PycharmProjects/untitled/venv/Include/com/2019/March/images/image_006.png";
byte[] imageContent1 = readFileToByteArray(new File(picPath));
ByteArrayInputStream in1 = new ByteArrayInputStream(imageContent1);
BufferedImage image1 = ImageIO.read(in1);
double d = Laplacian(image1);
System.out.println(d);
}
public static double Laplacian(BufferedImage original){
double val = 0.0;
try{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
int matType = CvType.CV_8UC3;
int imgType = BufferedImage.TYPE_3BYTE_BGR;
// BufferedImage original = ImageIO.read(new File(picPath));
Mat src = BufImg2Mat(original,imgType,matType);
//读取图像到矩阵中
if(src.empty()){
throw new Exception("no file");
}
Mat dst = src.clone();
//复制矩阵进入dst
Imgproc.Laplacian(src,dst,3);
MatOfDouble median = new MatOfDouble();
MatOfDouble std= new MatOfDouble();
Core.meanStdDev(dst, median , std);
val = Math.pow(std.get(0,0)[0],2);
// System.out.println(val);
return val;
}catch(Exception e){
System.out.println("例外:" + e);
}
return val;
}
public static Mat BufImg2Mat (BufferedImage original, int imgType, int matType) {
if (original == null) {
throw new IllegalArgumentException("original == null");
}
if (original.getType() != imgType) {
BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), imgType);
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(original, 0, 0, null);
} finally {
g.dispose();
}
}
byte[] pixels = ((DataBufferByte) original.getRaster().getDataBuffer()).getData();
Mat mat = Mat.eye(original.getHeight(), original.getWidth(), matType);
mat.put(0, 0, pixels);
return mat;
}
}
public static byte[] readFileToByteArray(File file)
{
try
{
if ( file == null)
return null;
if ( !file.exists() )
return null;
InputStream in = new FileInputStream(file);
ByteArrayOutputStream out= new ByteArrayOutputStream();
int count = 0;
byte[] b = new byte[8 * 1024];
while( (count=in.read(b)) != -1 )
out.write(b,0,count);
in.close();
return out.toByteArray();
}
catch(Exception e)
{
return null;
}
}
opencv的Laplacian算法java代码
最新推荐文章于 2024-08-06 16:25:52 发布