引言
图片颜色调整
1. 导入必要的库
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
2. 读取图片
BufferedImage image = ImageIO.read(new File("path/to/image.jpg"));
3. 图片颜色调整
3.1 调整亮度
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color c = new Color(image.getRGB(x, y));
int newRed = (int) (c.getRed() * 1.2);
int newGreen = (int) (c.getGreen() * 1.2);
int newBlue = (int) (c.getBlue() * 1.2);
image.setRGB(x, y, new Color(newRed, newGreen, newBlue).getRGB());
}
}
3.2 调整对比度
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color c = new Color(image.getRGB(x, y));
int newRed = c.getRed() + 50;
int newGreen = c.getGreen() + 50;
int newBlue = c.getBlue() + 50;
image.setRGB(x, y, new Color(newRed, newGreen, newBlue).getRGB());
}
}
3.3 转换为灰度图像
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color c = new Color(image.getRGB(x, y));
int gray = (int) (c.getRed() * 0.3 + c.getGreen() * 0.59 + c.getBlue() * 0.11);
image.setRGB(x, y, new Color(gray, gray, gray).getRGB());
}
}
4. 保存调整后的图片
ImageIO.write(image, "jpg", new File("path/to/adjusted_image.jpg"));
图像识别
1. 导入图像识别库
在Java中,我们可以使用OpenCV库进行图像识别。以下是导入OpenCV库的示例:
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
2. 读取图像
使用OpenCV读取图像。
Mat src = Imgcodecs.imread("path/to/image.jpg");
3. 图像识别
以下是一些常见的图像识别方法:
3.1 边缘检测
Mat gray = new Mat();
Mat edges = new Mat();
// 转换为灰度图像
Core.cvtColor(src, gray, Core.COLOR_BGR2GRAY);
// Canny边缘检测
Imgproc.Canny(gray, edges, 50, 150);
3.2 颜色识别
List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(edges, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
for (MatOfPoint contour : contours) {
// 根据轮廓面积筛选颜色
if (Imgproc.contourArea(contour) > 100) {
// 获取轮廓的质心
Point center = new Point();
Imgproc.moments(contour, center);
center.x = (int) (center.x / contour.size().width);
center.y = (int) (center.y / contour.size().height);
// 计算质心处的颜色
Scalar color = Core.mean(src.submat(new Rect(center.x - 10, center.y - 10, 20, 20)));
System.out.println("Detected color: " + color.val[2] + ", " + color.val[1] + ", " + color.val[0]);
}
}
4. 保存识别结果
使用OpenCV保存识别结果。
Imgcodecs.imwrite("path/to/recognized_image.jpg", src);