縮放影像的 OpenCV Java 示例。


Imgproc 類的 resize() 方法調整指定的影像大小。此方法接收到 −

  • 表示源影像和目標影像的兩個 Mat 物件。

  • 表示輸出影像大小的 Size 物件。

  • 表示水平軸比例因子的雙精度變數。

  • 表示垂直軸比例因子的雙精度變數。

  • 表示操作中要使用插值方法的整數變數。

示例

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class ScalingAnImage extends Application {
   public void start(Stage stage) throws IOException {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading image data
      String file ="D:\Images\elephant.jpg";
      Mat src = Imgcodecs.imread(file);
      //Creating destination matrix
      Mat dst = new Mat(src.rows(), src.cols(), src.type());
      //Creating the Size object
      Size size = new Size(src.rows()*0.5, src.rows()*0.5);
      //Scaling the Image
      Imgproc.resize(src, dst, size, 0, 0, Imgproc.INTER_AREA);
      Imgcodecs.imwrite("D:\Images\scaling_example.jpg", dst);
      //Converting matrix to JavaFX writable image
      Image img = HighGui.toBufferedImage(dst);
      WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);
      //Setting the image view
      ImageView imageView = new ImageView(writableImage);
      imageView.setX(10);
      imageView.setY(10);
      imageView.setPreserveRatio(true);
      //Setting the Scene object
      Group root = new Group(imageView);
      Scene scene = new Scene(root, 595, 400);
      stage.setTitle("Scaling Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}

輸入影像

輸出

在執行時,上述程式會生成以下輸出 −

更新於: 09-04-2020

580 次瀏覽

開啟你的 事業

完成課程獲取認證

開始
廣告