如何使用 Java OpenCV 庫建立一個映象影像?


建立映象影像

  • 使用 ImageIO.read() 方法讀取所需影像。

  • 獲取影像的高度和寬度。

  • 建立一個空的緩衝影像來儲存結果

  • 使用巢狀的 for 迴圈遍歷影像中的每個畫素。

  • 從右到左遍歷影像的寬度。

  • 使用 getRGB() 方法獲取畫素值。

  • 透過替換新的寬度值,使用 setRGB() 方法將畫素值設定到結果影像物件。

示例

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class MirrorImage {
   public static void main(String args[])throws IOException {
      //Reading the image
      File file= new File("D:\Images\tree.jpg");
      BufferedImage img = ImageIO.read(file);
      //Getting the height and with of the read image.
      int height = img.getHeight();
      int width = img.getWidth();
      //Creating Buffered Image to store the output
      BufferedImage res = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      for(int j = 0; j < height; j++){
         for(int i = 0, w = width - 1; i < width; i++, w--){
            int p = img.getRGB(i, j);
            //set mirror image pixel value - both left and right
            res.setRGB(w, j, p);
         }
      }
      //Saving the modified image
      file = new File("D:\Images\mirror_image.jpg");
      ImageIO.write(res, "jpg", file);
      System.out.println("Done...");
   }
}

輸入

輸出

更新日期: 2020 年 4 月 9 日

612 次瀏覽

開啟您的職業

完成課程以獲得認證

開始
廣告