java+opencv4.5.0 实现获取照片所有红色区域
时间: 2024-05-12 16:15:18 浏览: 157
opencv之颜色过滤只留下图片中的红色区域操作
5星 · 资源好评率100%
要实现获取照片所有红色区域,需要使用Java语言和OpenCV 4.5.0库。
以下是实现步骤:
1. 导入OpenCV库:
```java
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
```
2. 读取图像文件:
```java
Mat image = Imgcodecs.imread("path/to/image.jpg");
```
3. 将图像转换为HSV颜色空间:
```java
Mat hsvImage = new Mat();
Imgproc.cvtColor(image, hsvImage, Imgproc.COLOR_BGR2HSV);
```
4. 定义红色的HSV颜色范围:
```java
Scalar lowerRed = new Scalar(0, 100, 100);
Scalar upperRed = new Scalar(10, 255, 255);
Scalar lowerRed2 = new Scalar(160, 100, 100);
Scalar upperRed2 = new Scalar(179, 255, 255);
```
5. 对图像进行颜色阈值处理,提取红色区域:
```java
Mat mask1 = new Mat();
Core.inRange(hsvImage, lowerRed, upperRed, mask1);
Mat mask2 = new Mat();
Core.inRange(hsvImage, lowerRed2, upperRed2, mask2);
Mat mask = new Mat();
Core.add(mask1, mask2, mask);
```
6. 对二值化图像进行形态学操作,去除噪声:
```java
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5, 5));
Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_OPEN, kernel);
Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_CLOSE, kernel);
```
7. 在原始图像中绘制红色区域:
```java
Mat result = new Mat();
image.copyTo(result, mask);
```
完整的代码如下:
```java
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class RedAreaDetector {
static {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) {
Mat image = Imgcodecs.imread("path/to/image.jpg");
Mat hsvImage = new Mat();
Imgproc.cvtColor(image, hsvImage, Imgproc.COLOR_BGR2HSV);
Scalar lowerRed = new Scalar(0, 100, 100);
Scalar upperRed = new Scalar(10, 255, 255);
Scalar lowerRed2 = new Scalar(160, 100, 100);
Scalar upperRed2 = new Scalar(179, 255, 255);
Mat mask1 = new Mat();
Core.inRange(hsvImage, lowerRed, upperRed, mask1);
Mat mask2 = new Mat();
Core.inRange(hsvImage, lowerRed2, upperRed2, mask2);
Mat mask = new Mat();
Core.add(mask1, mask2, mask);
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5, 5));
Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_OPEN, kernel);
Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_CLOSE, kernel);
Mat result = new Mat();
image.copyTo(result, mask);
Imgcodecs.imwrite("path/to/result.jpg", result);
}
}
```
注意,前提是你已经安装好了OpenCV 4.5.0库,并将其配置到Java项目中。
阅读全文