eclipse添加jar
图片相似度对比
package com.test;
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class Mini {
public static void main(String[] args) {
// Set image path
String filename1 = "C:/Users/lilin/Desktop/2.jpg";
String filename2 = "C:/Users/lilin/Desktop/3.jpg";
int ret;
ret = compareHistogram(filename1, filename2);
if (ret > 0) {
System.out.println("相同.");
} else {
System.out.println("不同.");
}
}
/**
* Compare that two images is similar using histogram
* @author minikim
* @param filename1 - the first image
* @param filename2 - the second image
* @return integer - 1 if two images are similar, 0 if not
*/
public static int compareHistogram(String filename1, String filename2) {
int retVal = 0;
long startTime = System.currentTimeMillis();
System.load("C:/Users/lilin/Desktop/opencv/build/java/x86/opencv_java310.dll");
// Load images to compare
Mat img1 = Imgcodecs.imread(filename1, Imgcodecs.CV_LOAD_IMAGE_COLOR);
Mat img2 = Imgcodecs.imread(filename2, Imgcodecs.CV_LOAD_IMAGE_COLOR);
Mat hsvImg1 = new Mat();
Mat hsvImg2 = new Mat();
// Convert to HSV
Imgproc.cvtColor(img1, hsvImg1, Imgproc.COLOR_BGR2HSV);
Imgproc.cvtColor(img2, hsvImg2, Imgproc.COLOR_BGR2HSV);
// Set configuration for calchist()
List
List
listImg1.add(hsvImg1);
listImg2.add(hsvImg2);
MatOfFloat ranges = new MatOfFloat(0,255);
MatOfInt histSize = new MatOfInt(50);
MatOfInt channels = new MatOfInt(0);
// Histograms
Mat histImg1 = new Mat();
Mat histImg2 = new Mat();
// Calculate the histogram for the HSV imgaes
Imgproc.calcHist(listImg1, channels, new Mat(), histImg1, histSize, ranges);
Imgproc.calcHist(listImg2, channels, new Mat(), histImg2, histSize, ranges);
Core.normalize(histImg1, histImg1, 0, 1, Core.NORM_MINMAX, -1, new Mat());
Core.normalize(histImg2, histImg2, 0, 1, Core.NORM_MINMAX, -1, new Mat());
// Apply the histogram comparison methods
// 0 - correlation: the higher the metric, the more accurate the match "> 0.9"
// 1 - chi-square: the lower the metric, the more accurate the match "< 0.1"
// 2 - intersection: the higher the metric, the more accurate the match "> 1.5"
// 3 - bhattacharyya: the lower the metric, the more accurate the match "< 0.3"
double result0, result1, result2, result3;
result0 = Imgproc.compareHist(histImg1, histImg2, 0);
result1 = Imgproc.compareHist(histImg1, histImg2, 1);
result2 = Imgproc.compareHist(histImg1, histImg2, 2);
result3 = Imgproc.compareHist(histImg1, histImg2, 3);
System.out.println("Method [0] " + result0);
System.out.println("Method [1] " + result1);
System.out.println("Method [2] " + result2);
System.out.println("Method [3] " + result3);
// If the count that it is satisfied with the condition is over 3, two images is same.
int count=0;
if (result0 > 0.9) count++;
if (result1 < 0.1) count++;
if (result2 > 1.5) count++;
if (result3 < 0.3) count++;
System.out.println(count);
if (count >= 3) retVal = 1;
long estimatedTime = System.currentTimeMillis() - startTime;
System.out.println("estimatedTime=" + estimatedTime + "ms");
return retVal;
}
}
人脸检测裁剪
package com.test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.objdetect.CascadeClassifier;
public class Test1 {
/**
* 人脸 lbpcascade_frontalface.xml
* 检测眼睛 haarcascade_eye.xml
* 能够检测人眼睁开或者闭合的检测器: haarcascade_lefteye_2splits.xml haarcascade_righteye_2splits.xml
*
* @param args
*/
public static void main( String[] args )
{
System.load("C:/Users/lilin/Desktop/opencv/build/java/x86/opencv_java310.dll");
System.out.println("\nRunning FaceDetector");
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss");
CascadeClassifier faceDetector = new CascadeClassifier("./Data/lbpcascade_frontalface.xml");
Mat image = Imgcodecs.imread("./Data/1.jpg");
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces",faceDetections.toArray().length));
for (Rect rect : faceDetections.toArray()) {
System.out.println(rect.width+"<>"+rect.height);
System.out.println(rect.x+"<>"+ rect.y+"<>"+( rect.x+ rect.width) +"<>"+( rect.y + rect.height));
//Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x+ rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
OperateImage operateImage = new OperateImage(rect.x, rect.y, rect.width, rect.height);
operateImage.setSrcpath("E:/eclipsework/test_cv/Data/1.jpg");
operateImage.setSubpath( "C:/Users/lilin/Desktop/"+System.currentTimeMillis()+".jpg");
try {
operateImage.cut();
} catch (IOException e) {
e.printStackTrace();
}
}
// String filename = "C:/Users/lilin/Desktop/"+f.format(new Date())+".png";
// System.out.println(String.format("Writing %s", filename));
// Imgcodecs.imwrite(filename, image);
}
}
package com.test;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class OperateImage {
// ===源图片路径名称如:c:\1.jpg
private String srcpath ;
// ===剪切图片存放路径名称.如:c:\2.jpg
private String subpath ;
// ===剪切点x坐标
private int x ;
private int y ;
// ===剪切点宽度
private int width ;
private int height ;
public OperateImage() {
}
public OperateImage( int x, int y, int width, int height) {
this .x = x ;
this .y = y ;
this .width = width ;
this .height = height ;
}
/**
* 对图片裁剪,并把裁剪完蛋新图片保存 。
*/
public void cut()throws IOException {
FileInputStream is = null ;
ImageInputStream iis = null ;
try {
// 读取图片文件
is =new FileInputStream(srcpath);
/*
* 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader
* 声称能够解码指定格式。 参数:formatName - 包含非正式格式名称 .
*(例如 "jpeg" 或 "tiff")等 。
*/
Iterator < ImageReader > it=ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = it.next();
// 获取图片流
iis = ImageIO.createImageInputStream(is);
/*
*
iis:读取源.true:只向前搜索
.将它标记为 ‘只向前搜索'。描述如何对流进行解码的类
.用于指定如何在输入时从 Java Image I/O
* 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件
* 将从其 ImageReader 实现的 getDefaultReadParam 方法中返回
* ImageReadParam 的实例。
*/
ImageReadParam param = reader.getDefaultReadParam();
/*
* 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象
* 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。
*/
Rectangle rect = new Rectangle(x, y, width, height);
// 提供一个 BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
/*
* 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将
* 它作为一个完整的 BufferedImage 返回。
*/
BufferedImage bi=reader.read(0,param);
// 保存新图片
ImageIO.write(bi,"jpg",new File(subpath));
} finally {
if (is != null )
is.close() ;
if (iis != null )
iis.close();
}
}
public int getHeight() {
return height;
}
public void setHeight( int height) {
this .height = height;
}
public String getSrcpath() {
return srcpath;
}
public void setSrcpath(String srcpath) {
this .srcpath = srcpath;
}
public String getSubpath() {
return subpath;
}
public void setSubpath(String subpath) {
this .subpath = subpath;
}
public int getWidth() {
return width;
}
public void setWidth( int width) {
this .width = width;
}
public int getX() {
return x;
}
public void setX( int x) {
this .x = x;
}
public int getY() {
return y;
}
public void setY( int y) {
this .y = y;
}
}
linux编译使用
cd opencv-3.1.0
mkdir build
cd build
cmake -DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_PREFIX=/usr/local ../
make -j8
sudo make install
Java开发相关的动态链接库文件和jar包位于目录:
/usr/local/share/OpenCV/java/
参考地址https://www.cnblogs.com/xiaomanon/p/5490281.html
server 写法
static{
System.load("/usr/local/share/OpenCV/java/libopencv_java310.so");
//System.load("C:/Users/lilin/Desktop/opencv/build/java/x86/opencv_java310.dll");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String realPath = request.getSession().getServletContext().getRealPath("/");
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss");
CascadeClassifier faceDetector = new CascadeClassifier(realPath+"/m/lbpcascade_frontalface.xml");
Mat image = Imgcodecs.imread(realPath+"/m/1.jpg");
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces",faceDetections.toArray().length));
for (Rect rect : faceDetections.toArray()) {
System.out.println(rect.width+"<>"+rect.height);
System.out.println(rect.x+"<>"+ rect.y+"<>"+( rect.x+ rect.width) +"<>"+( rect.y + rect.height));
Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x+ rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
}
String format = f.format(new Date());
String filename = realPath+"/"+format+".png";
System.out.println(String.format("Writing %s", filename));
Imgcodecs.imwrite(filename, image);
response.sendRedirect("b.jsp?n="+format);
}
交流q群 261074724