我正在做图像处理,我想对之前抖动的图像进行像素化,但它应该仍然看起来像原始图像。在这里,我向您展示了一些我现在正在做什么以及我希望它看起来像什么的例子:
那就是我要修改的图像。
那是被“floyd steinberg 抖动”抖动后的图像。
这就是他在被像素化后应该如何看待最后的样子。
这就是我的图像在像素化后的样子。我真的不知道该怎么做,所以它看起来像上面的图像。
我搜索了整个互联网,并尝试了所有像素化算法。那就是我目前使用的课程:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;
public final class ImageUtil {
public static BufferedImage pixelate(BufferedImage imageToPixelate, int pixelSize) {
BufferedImage pixelateImage = new BufferedImage(
imageToPixelate.getWidth(),
imageToPixelate.getHeight(),
imageToPixelate.getType());
for (int y = 0; y < imageToPixelate.getHeight(); y += pixelSize) {
for (int x = 0; x < imageToPixelate.getWidth(); x += pixelSize) {
BufferedImage croppedImage = getCroppedImage(imageToPixelate, x, y, pixelSize, pixelSize);
Color dominantColor = getDominantColor(croppedImage);
for (int yd = y; (yd < y + pixelSize) && (yd < pixelateImage.getHeight()); yd++) {
for (int xd = x; (xd < x + pixelSize) && (xd < pixelateImage.getWidth()); xd++) {
pixelateImage.setRGB(xd, yd, dominantColor.getRGB());
}
}
}
}
return pixelateImage;
}
public static BufferedImage getCroppedImage(BufferedImage image, int startx, int starty, int width, int height) {
if (startx < 0) startx = 0;
if (starty < 0) starty = 0;
if (startx > image.getWidth()) startx = image.getWidth();
if (starty > image.getHeight()) starty = image.getHeight();
if (startx + width > image.getWidth()) width = image.getWidth() - startx;
if (starty + height > image.getHeight()) height = image.getHeight() - starty;
return image.getSubimage(startx, starty, width, height);
}
public static Color getDominantColor(BufferedImage image) {
Map<Integer, Integer> colorCounter = new HashMap<>(100);
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
int currentRGB = image.getRGB(x, y);
int count = colorCounter.getOrDefault(currentRGB, 0);
colorCounter.put(currentRGB, count + 1);
}
}
return getDominantColor(colorCounter);
}
private static Color getDominantColor(Map<Integer, Integer> colorCounter) {
int dominantRGB = colorCounter.entrySet().stream()
.max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1)
.get()
.getKey();
return new Color(dominantRGB);
}
}
我就是这样开始的:
ImageUtil.pixelate(selectedImage, 3);
感谢您的帮助,如果有不清楚的地方或者我需要在我的问题中添加一些内容,请告诉我。