先决条件:
null
在本文中,我们将把彩色图像转换成灰度图像。
RGB颜色模型- RGB颜色模型是一种加法混合模型,其中红光、绿光和蓝光以各种方式叠加在一起,以再现各种颜色。
灰度图像- 灰度图像是一种黑白或灰色单色图像,完全由灰色阴影组成。对比度范围从最低强度的黑色到最强强度的白色。
通常,灰度图像对每个像素使用8位表示。通过使用8位,我们可以表示0到255之间的值。因此,8位表示的灰度图像将是一个矩阵,其值可以是0到255之间的任何值。0表示黑色像素,255表示白色像素,介于从黑色到白色的不同色调之间。
注: 在灰度图像中,图像的Alpha分量将与原始图像相同,但RGB将发生变化,即所有三个RGB分量对每个像素都具有相同的值。
算法:
- 获取像素的RGB值。
- 求RGB的平均值,即平均值=(R+G+B)/3
- 用步骤2中计算的平均值(Avg)替换像素的R、G和B值。
- 对图像的每个像素重复步骤1至步骤3。
实施:
JAVA
// Java program to demonstrate // colored to grayscale conversion import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Grayscale { public static void main(String args[]) throws IOException { BufferedImage img = null ; File f = null ; // read image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png" ); img = ImageIO.read(f); } catch (IOException e) { System.out.println(e); } // get image's width and height int width = img.getWidth(); int height = img.getHeight(); // convert to grayscale for ( int y = 0 ; y < height; y++) { for ( int x = 0 ; x < width; x++) { // Here (x,y)denotes the coordinate of image // for modifying the pixel value. int p = img.getRGB(x, y); int a = (p >> 24 ) & 0xff ; int r = (p >> 16 ) & 0xff ; int g = (p >> 8 ) & 0xff ; int b = p & 0xff ; // calculate average int avg = (r + g + b) / 3 ; // replace RGB value with avg p = (a << 24 ) | (avg << 16 ) | (avg << 8 ) | avg; img.setRGB(x, y, p); } } // write image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/GFG.png" ); ImageIO.write(img, "png" , f); } catch (IOException e) { System.out.println(e); } } } |
输出——
注: 此代码不会在联机IDE上运行,因为它需要磁盘上的映像。
本文由 普拉蒂克·阿加瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END