Để chuyển đổi hình ảnh được tô màu sang thang độ xám.
-
Nhận các giá trị xanh lam xanh lục đỏ của mỗi pixel
-
Lấy giá trị trung bình của 3 màu này.
-
Thay thế các giá trị RGB bằng giá trị trung bình.
-
Tạo giá trị pixel mới từ các màu đã sửa đổi.
-
Đặt giá trị mới thành pixel.
Ví dụ
import java.io.File;
import java.io.IOException;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Color2Grey {
public static void main(String args[])throws IOException {
//Reading the image
File file= new File("D:\\Images\\car.jpg");
BufferedImage img = ImageIO.read(file);
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
//Retrieving the values of a pixel
int pixel = img.getRGB(x,y);
//Creating a Color object from pixel value
Color color = new Color(pixel, true);
//Retrieving the R G B values
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
//Finding the average of the red green blue values
int average = (red+green+blue)/3;
//Creating new Color object
color = new Color(average, average, average);
//Setting new Color object to the image
img.setRGB(x, y, color.getRGB());
}
}
//Saving the modified image
file = new File("D:\\Images\\grey_image.jpg");
ImageIO.write(img, "jpg", file);
System.out.println("Done...");
}
} Đầu vào
Đầu ra