首頁  >  文章  >  Java  >  在Java OpenCV中,不使用任何方法將影像轉換為灰階圖

在Java OpenCV中,不使用任何方法將影像轉換為灰階圖

王林
王林轉載
2023-08-26 14:53:16978瀏覽

將彩色影像轉換為灰階。

  • 取得每個像素的紅綠藍值

  • # 取得這 3 種顏色的平均值。

  • 以平均值取代 RGB 值。

  • 根據修改後的顏色建立新的像素值。

  • 將新值設為像素。

範例

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...");
   }
}

輸入

在Java OpenCV中,不使用任何方法将图像转换为灰度图

#輸出

在Java OpenCV中,不使用任何方法将图像转换为灰度图

以上是在Java OpenCV中,不使用任何方法將影像轉換為灰階圖的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除