java如何对BuffereImage进行像素化,使其看起来像这样?
我正在做图像处理,我想对之前抖动过的图像进行像素化,但它看起来应该仍然像原始图像。在这里,我向你们展示了一些我现在正在做的事情,以及我希望它看起来像什么:
这就是我想修改的图像
这是经过“弗洛伊德·斯坦伯格抖动”抖动后的图像
这就是他在被像素化后对结局的看法
这就是我的图像在像素化后的样子。我真的不知道该怎么做,所以看起来像上图
我搜索了整个互联网,尝试了每一种像素算法。这就是我目前使用的课程:
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);
感谢您的帮助,如果有什么不清楚的地方或者我需要补充一些问题,请告诉我
# 1 楼答案
以下是您可以应用的算法阶段:
有关详细信息,请查看rgb2indMATLAB文档
在下面的例子中,我使用了你帖子中的参考图片找到了调色板李>
MATLAB实现:
结果:
与您的参考存在一些差异(可能是由于不同的颜色减少算法)