본문 바로가기

PROGRAM/OpenCV

OpenCV-Java #2 동영상 / 카메라 제어

아래의 동영상 제어코드를 실행하면 아주 빠른속도로 비디오가 재생됨... 다른 방법이 필요함

이리저리 다 찾아보았으나 내맘에 드는 코드는 찾을 수 없었음

그리하여 opencv-tutorial에서 찾아보자고 마음 먹음

다행히 비디오 관련 내용이 있었음

 

https://docs.opencv.org/4.x/d9/df8/tutorial_root.html

이제 이 3개의 예제를 가지고 아주 기본이 되는 코드를 뽑아 보기로 하였음

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;

class MyVideoTest {
    public void run() {
        String filename = "WIN_20220603_16_47_52_Pro.mp4";
        VideoCapture capture = new VideoCapture(filename);
        if (!capture.isOpened()) {
            System.out.println("Unable to open this file");
            System.exit(-1);
        }
        
        Mat frame = new Mat();
        Mat frame_gray = new Mat();

        while (capture.read(frame)) {
            if (frame.empty()) {
                break;
            }

            Imgproc.cvtColor(frame, frame_gray, Imgproc.COLOR_BGR2GRAY);
            HighGui.imshow("Frame", frame);

            int keyboard = HighGui.waitKey(30);
            if (keyboard == 'q' || keyboard == 27) {
                break;
            }
        }
        System.exit(0);
    }
}

public class opencv_test {
    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        new MyVideoTest().run();
    }
}

이 코드로 돌려보니 정상속도롤 비디오가 재생됨 (정상적인 코드를 보면 C++ 이나 파이썬과 비슷한 형태임)

 

코드에서 이부분만 수정하면 캠 동작 가능

VideoCapture capture = new VideoCapture(0);

 

기존에 웹캠이 사용중일 때 다시 실행하면 이런 에러가 발생함

우선적으로 윈도우즈에 있는 카메라를 동작시켜보고 이런 메시지가 나오면

작업관리자에서 이클립스 아래이거나 독립적으로 OpenJDK Platform binary 를 강제로 종료하고 다시 시작하면 웹캠도 동작함

 

웹캠제어 https://riptutorial.com/opencv/example/25958/using-videocapture-with-opencv-java

public class opencv_run {
	public static void main(String[] args) {
		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
		Mat frame = new Mat();
		VideoCapture capture = new VideoCapture(0);
		
		JFrame jframe = new JFrame("Title");

		jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JLabel jLabel = new JLabel();
		jframe.setContentPane(jLabel);
		jframe.setVisible(true);
		jframe.setBounds(0, 0, 640, 480);

		while (true) {
			try {
				while (capture.read(frame)) {
					ImageIcon image = new ImageIcon(Mat2BufferedImage(frame));
					jLabel.setIcon(image);
					jLabel.repaint();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	private static BufferedImage Mat2BufferedImage(Mat matrix) throws Exception {
		MatOfByte matOfByte = new MatOfByte();
		Imgcodecs.imencode(".jpg", matrix, matOfByte);
		byte ba[] = matOfByte.toArray();
		BufferedImage bi = ImageIO.read(new ByteArrayInputStream(ba));
		return bi;
	}
}

 

동영상제어 : 웹캠에 비해 while문이 하나 작다

public class opencv_run {
	public static void main(String[] args) {
		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
		
		Mat frame = new Mat();
		VideoCapture capture = new VideoCapture();
		capture.open("C:\\java_opencv\\opencv_test\\video.mp4");

		JFrame jFrame = new JFrame("Title");
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JLabel jLabel = new JLabel();
		jFrame.setContentPane(jLabel);

		jFrame.setVisible(true);
		jFrame.setBounds(0, 0, 640, 480);

		try {
			while (capture.read(frame)) {
				ImageIcon image = new ImageIcon(Mat2BufferedImage(frame));
				jLabel.setIcon(image);
				jLabel.repaint();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static BufferedImage Mat2BufferedImage(Mat matrix) throws Exception {
		MatOfByte matOfByte = new MatOfByte();
		Imgcodecs.imencode(".jpg", matrix, matOfByte);
		byte ba[] = matOfByte.toArray();
		BufferedImage bi = ImageIO.read(new ByteArrayInputStream(ba));
		return bi;
	}
}

 

'PROGRAM > OpenCV' 카테고리의 다른 글

OpenCV-Java #3 원 찾기  (0) 2022.06.08
OpenCV-JAVA #1 시작하기  (0) 2022.05.27
Contour 최대 최소값 찾기  (0) 2021.04.02
Object Tracking  (0) 2021.01.12
pyQt5 + cv2.findContours  (0) 2020.06.11