public static BufferedImage smoothBackground2(BufferedImage originalImage, int colorThreshold) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
DataBuffer dataBuffer = originalImage.getRaster().getDataBuffer();
byte[] pixels = ((DataBufferByte) dataBuffer).getData();
Map<Integer, Integer> colorCount = new HashMap<>();
for (int i = 0; i < pixels.length; i += 3) {
int color = ((pixels[i] & 0xFF) << 16) | ((pixels[i + 1] & 0xFF) << 8) | (pixels[i + 2] & 0xFF);
colorCount.put(color, colorCount.getOrDefault(color, 0) + 1);
}
int backgroundColor = findBackgroundColor(colorCount);
BufferedImage smoothedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Color pixelColor = new Color(originalImage.getRGB(x, y));
// 如果像素颜色接近于背景色,进行平滑处理
if (isColorCloseToBackground(pixelColor, new Color(backgroundColor), colorThreshold)) {
Color averageColor = getAverageColor(originalImage, x, y, 3);
smoothedImage.setRGB(x, y, averageColor.getRGB());
} else {
// 不是背景色的像素,保持原样
smoothedImage.setRGB(x, y, originalImage.getRGB(x, y));
}
}
}
return smoothedImage;
}
private static boolean isColorCloseToBackground(Color color, Color backgroundColor, int colorThreshold) {
int redDiff = Math.abs(color.getRed() - backgroundColor.getRed());
int greenDiff = Math.abs(color.getGreen() - backgroundColor.getGreen());
int blueDiff = Math.abs(color.getBlue() - backgroundColor.getBlue());
// 判断颜色是否接近背景色
return redDiff < colorThreshold && greenDiff < colorThreshold && blueDiff < colorThreshold;
}
private static Color getAverageColor(BufferedImage image, int centerX, int centerY, int windowSize) {
int totalRed = 0;
int totalGreen = 0;
int totalBlue = 0;
int count = 0;
for (int y = centerY - windowSize/2; y <= centerY + windowSize/2; y++) {
for (int x = centerX - windowSize/2; x <= centerX + windowSize/2; x++) {
if (x >= 0 && x < image.getWidth() && y >= 0 && y < image.getHeight()) {
// 获取当前像素的颜色值
Color pixelColor = new Color(image.getRGB(x, y));
totalRed += pixelColor.getRed();
totalGreen += pixelColor.getGreen();
totalBlue += pixelColor.getBlue();
count++;
}
}
}
// 计算平均颜色值
int averageRed = totalRed / count;
int averageGreen = totalGreen / count;
int averageBlue = totalBlue / count;
return new Color(averageRed, averageGreen, averageBlue);
}
评论