Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách tải và hiển thị ảnh trong OpenCV bằng C++

Các hàm cần thiết để tải và hiển thị ảnh trong OpenCV:

  • Mat: Kiểu dữ liệu ma trận để chứa ảnh. VD: Mat myImage;
  • namedWindow(): Tạo cửa sổ hiển thị. Cú pháp: namedWindow("ten_cua_so", flag)
  • imread(): Đọc ảnh từ đường dẫn. Cú pháp: imread("duong_dan/ten_anh.duoi_mo_rong", flag)
  • imshow(): Hiển thị ảnh trong cửa sổ. Cú pháp: imshow("ten_cua_so", ten_ma_tran)
  • waitKey(): Chờ phím bấm. waitKey(0) chờ vô hạn, waitKey(10000) chờ 10 giây.
  • destroyWindows(): Đóng cửa sổ và giải phóng bộ nhớ.

Ví dụ

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;

int main() {
    Mat myImage;
    namedWindow("PhotoFrame");
    myImage = imread("lakshmi.jpg");
    if (myImage.empty()) {
        cout << "Khong the tai anh." << endl;
        system("pause");
        return -1;
    }
    imshow("PhotoFrame", myImage);
    destroyWindow("Photoframe");
    waitKey(0);
    return 0;
}

Kết quả

Cách tải và hiển thị ảnh trong OpenCV bằng C++