关闭

opencv3_java 摄像头图形图像检测DetectObjectsCamera videoioVideoCapture

标签: opencv3java
253人阅读 评论(0) 收藏 举报
分类:

摄像头图形图像检测DetectObjectsCamera videoioVideoCapture


package opencv_java_demo;

import javax.swing.*;

import java.awt.*;
import java.awt.image.BufferedImage;

import org.opencv.core.*;
import org.opencv.core.Point;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.imgproc.Imgproc;

public class DetectObjectsCamera extends JPanel {
	private static final long serialVersionUID=1L;
	
	private BufferedImage mImg;
	
	private static Mat dobj(CascadeClassifier objDetector, Mat src){
		Mat dst=src.clone();
		
		MatOfRect objDetections=new MatOfRect();
		
		objDetector.detectMultiScale(dst, objDetections);
		
		if(objDetections.toArray().length<=0){
			return src;
		}
		for(Rect rect:objDetections.toArray()){
			Imgproc.rectangle(dst, new Point(rect.x,rect.y), new Point(rect.x+rect.width,rect.y+rect.height), new Scalar(0,0,255),2);
		}
		return dst;
	}
	
	public void paintComponent(Graphics g){
		if(mImg!=null){
			g.drawImage(mImg, 0, 0, mImg.getWidth(),mImg.getHeight(),this);
		}
	}
	
	public static void main(String[] args) {
		try{
			System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
			
			CascadeClassifier objDetector=new CascadeClassifier("data/lbpcascades/lbpcascade_frontalface.xml");
			
			Mat capImg=new Mat();
			VideoCapture capture=new VideoCapture(0);
			int height =(int)capture.get(Videoio.CV_CAP_PROP_FRAME_HEIGHT);
			int width =(int)capture.get(Videoio.CV_CAP_PROP_FRAME_WIDTH);
			if(height==0||width==0){
				throw new Exception("camera not found");
			}
			
			JFrame frame=new JFrame("camera");
			frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			DetectObjectsCamera panel=new DetectObjectsCamera();
			frame.setContentPane(panel);
			frame.setVisible(true);
			frame.setSize(width+frame.getInsets().left+frame.getInsets().right, height+frame.getInsets().top+frame.getInsets().bottom);
			
			MatToBufferedImage matToBi=new MatToBufferedImage();
			
			Mat dst=new Mat();
			while(frame.isShowing()){
				capture.read(capImg);
				dst=dobj(objDetector,capImg);
				panel.mImg=matToBi.mat2BI(dst);
				panel.repaint();
			}
			capture.release();
		}catch(Exception e){
			System.out.println("例外"+e);
		}finally{
			System.out.println("--done--");
		}
	}
}


0
0

猜你在找
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:56487次
    • 积分:1236
    • 等级:
    • 排名:千里之外
    • 原创:57篇
    • 转载:0篇
    • 译文:4篇
    • 评论:108条
    QQ联系方式
    作者日本硕士
    知识长期输入中
    技术长期磨练中
    如有问题或交流
    请QQ联系 649508982
    来者请说明CSDN
    或者加入机器学习交流群
    不定期发送pdf等学习资源
    QQ群号:657119450
    机器学习 QQ群加入
    博客专栏
    最新评论