我正在处理图像,我有一个问题。
我想从项目中读取图像,并将图像转换为灰色。我目前正在尝试使用函数 rgb2gray 进行转换,但仍然无法正常工作。
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class ImageTesting extends Component {
private static int[] pixel;
private static BufferedImage b;
BufferedImage image;
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
public ImageTesting() {
try {
image = ImageIO.read(new File("teste.jpg"));
} catch (IOException e) {
}
}
public Dimension getPreferredSize() {
if (image == null) {
return new Dimension(400, 400);
} else {
return new Dimension(image.getWidth(null), image.getHeight(null));
}
}
public static BufferedImage rgb2gray(BufferedImage bi) {
int heightLimit = bi.getHeight();
int widthLimit = bi.getTileWidth();
BufferedImage converted = new BufferedImage(widthLimit, heightLimit, BufferedImage.TYPE_BYTE_GRAY);
for (int height = 0; height < heightLimit; height++) {
for (int width = 0; width < widthLimit; width++) {
Color c = new Color(bi.getRGB(width, height) & 0x00fffff);
int newRed = (int) ((0.2989f * c.getRed()) * 2);// 0.2989f//multiplicr po 2
int newGreen = (int) ((0.5870f * c.getGreen()) * 2);// 0.5870f
int newBlue = (int) ((0.1140f * c.getBlue()) * 2);
int roOffset = newRed + newGreen + newBlue;
converted.setRGB(width, height, roOffset);
}
}
return converted;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
JFrame f = new JFrame("Load Image Sample");
JFrame g = new JFrame("Image RGB");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
g.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new ImageTesting());
f.pack();
f.setVisible(true);
g.add(new ImageTesting());
rgb2gray(b);
}
}
当我运行程序时,这些是出现的错误。
如果有人可以帮助我,我很感激。谢谢
编辑: 我设法解决了这个问题,但现在又出现了另一个问题。为了继续我的工作,我想在结果图像中找到最多 10 个亮点,并在索引中返回另一个图像,其中黑色的值为 0,索引中的白色值为 1,但此时我不明白制定这些步骤的最佳方法。