foreword
Let’s talk about it. Recently, I have been exposed to machine vision because of my work. I took some time to study OpenCV. I am a JAVA coder, so the technical implementation of this article uses the Java language.
I have compiled an article on the installation of OpenCV. It is relatively simple to write, and will continue to be improved in the future. Welcome to comment on the installation and configuration of OpenCV-Mac OS environment_The blog of the little bee who can type code-CSDN blog
The code example refers to the use of opencv in Java_My Blog-CSDN Blog_java opencv
1. First create a SpringBoot!
Copy the jar package and dynamic library files in the OpenCV installation directory to our project
Source file directory (OpenCV will be automatically generated after installation, if not, please refer to the installation chapter)
/usr/local/opencv-4.6.0/build/bin/opencv-460.jar
/usr/local/opencv-4.6.0/build/lib/libopencv_java460.dylib
Add a local opencv reference in the middle of the pom
<dependency>
<groupId>org.opencv</groupId>
<artifactId>opencv</artifactId>
<version>4.6.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/opencv/opencv-460.jar</systemPath>
</dependency>
2. Test code
Create a test class DemoGrayscaleTests.java
package org.example.opencv;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import static org.opencv.highgui.HighGui.imshow;
import static org.opencv.highgui.HighGui.waitKey;
import static org.opencv.imgcodecs.Imgcodecs.imread;
import static org.opencv.imgcodecs.Imgcodecs.imwrite;
import static org.opencv.imgproc.Imgproc.COLOR_RGB2GRAY;
import static org.opencv.imgproc.Imgproc.cvtColor;
@Slf4j
@RunWith(SpringRunner.class)
public class DemoGrayscaleTests {
@Test
public void testOpencv() throws Exception {
// 解决awt报错问题
System.setProperty("java.awt.headless", "false");
log.info("java library path: {}", System.getProperty("java.library.path"));
// 加载动态库
URL url = ClassLoader.getSystemResource("lib/opencv/libopencv_java460.dylib");
log.info("url path: {}", url.getPath());
System.load(url.getPath());
// 读取图像
Mat image = imread("/Users/xiaomifeng/Pictures/face.jpeg");
if (image.empty()) {
throw new Exception("image is empty");
}
imshow("Original Image", image);
// 创建输出单通道图像
Mat grayImage = new Mat(image.rows(), image.cols(), CvType.CV_8SC1);
// 进行图像色彩空间转换
cvtColor(image, grayImage, COLOR_RGB2GRAY);
imshow("Processed Image", grayImage);
imwrite("/Users/xiaomifeng/Pictures/hello.jpg", grayImage);
waitKey();
}
}
3. Execution results
I found a photo of a girl here and tested it, it's perfect~
code connection