【发布时间】:2014-10-10 09:25:34
【问题描述】:
在 java 中,我读取一个图像,然后遍历像素,如果它的颜色距离
但这不起作用。它没有任何效果......
有人发现问题了吗?
谢谢
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.ImageIO;
public class Recognize {
public static void main(String args[]) throws IOException {
Path path = Paths.get("images/fish.png");
File file = path.toFile();
if (file.exists()) {
InputStream stream = Files.newInputStream(path);
BufferedImage bufferedImage = ImageIO.read(stream);
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if (width > 0 && height > 0) {
int TLpixel = bufferedImage.getRGB(0, 0);
Color TLcolor = new Color(TLpixel);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int pixel = bufferedImage.getRGB(i, j);
Color color = new Color(pixel);
double distance = ColourDistance(TLcolor, color);
//System.out.println(distance);
if (distance < 30) {
int mc = (0 << 24) | 0x00ffffff;
int newcolor = pixel & mc;
bufferedImage.setRGB(i, j, newcolor);
}
}
}
File outputfile = new File("images/fish_new.png");
ImageIO.write(bufferedImage, "png", outputfile);
}
}
}
public static int[] printPixelARGB(int pixel) {
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
return new int[] {red, green, blue, alpha};
}
public static double ColourDistance(Color c1, Color c2) {
double rmean = ( c1.getRed() + c2.getRed() )/2;
int r = c1.getRed() - c2.getRed();
int g = c1.getGreen() - c2.getGreen();
int b = c1.getBlue() - c2.getBlue();
double weightR = 2 + rmean/256;
double weightG = 4.0;
double weightB = 2 + (255-rmean)/256;
return Math.sqrt(weightR*r*r + weightG*g*g + weightB*b*b);
}
}
【问题讨论】:
-
不工作是什么意思?
-
尝试打印
bufferedImage的值。您确定它包含 Alpha 通道吗?并非所有类型的图像都支持透明度,如果不支持,将 alpha 设置为0很可能不会有任何效果。作为旁注0 << 24也没有效果,0 无论如何都是 0。 -
haraldK 的提示 +1:您几乎不知道图像的类型。您可以尝试将图像转换为肯定包含 Alpha 通道的图像,例如使用来自stackoverflow.com/questions/22391353/…的
convertToARGB -
@user... :它无法正常工作,当我看到输出文件时,它看起来与原始文件完全相同。我希望某些像素是透明的,但事实并非如此。
-
@Marco13:感谢链接中的解决方案运行良好。 (我的意思是函数 convertToARGB)
标签: java pixel bufferedimage alpha