Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Basic Image Operations with C++ and OpenCV

Tech 4

Reading Images

In OpenCV, the cv::imread() function is used to load images from a file. This function returns a cv::Mat object, which is the primary data structure in OpenCV for storing image data.

// Load a color image
cv::Mat imgData = cv::imread("sample_image.png", cv::IMREAD_COLOR);

The cv::imread() function accepts two arguemnts:

  1. The file path of the image to load.
  2. The loading mode, which can be:
    • cv::IMREAD_COLOR (default, loads as a color image)
    • cv::IMREAD_GRAYSCALE (loads as a grayscale image)
    • cv::IMREAD_UNCHANGED (loads with alpha channel if present)

These flags can also be represented by integers: 1, 0, or -1, respectively.

If the file path is incorrect, cv::imread() returns an empty cv::Mat object without throwing an error. To handle this, use the empty() method to check for successful loading.

if (imgData.empty()) {
    std::cerr << "Failed to load image!" << std::endl;
    return EXIT_FAILURE;
}

Dispplaying Images

To display an image, create a window using cv::namedWindow() and then show the image with cv::imshow().

// Create a window for displaying the image
cv::namedWindow("Display", cv::WINDOW_AUTOSIZE);
// Display the image in the window
cv::imshow("Display", imgData);
std::cout << "Image loaded successfully!" << std::endl;

cv::namedWindow() takes two parameters:

  1. The window name.
  2. A window property flag, such as:
    • cv::WINDOW_NORMAL (resizable window)
    • cv::WINDOW_AUTOSIZE (window size adjusts to the image)
    • cv::WINDOW_FREERATIO (window can be resized without aspect ratio constraints)

cv::imshow() requires:

  1. The window name (must match the one used in cv::namedWindow()).
  2. The image object to display.

To keep the window open, use cv::waitKey() to wait for a key press.

cv::waitKey(0);

The parameter to cv::waitKey() specifies the maximum wait time in milliseconds. A value of 0 means it will wait indefinitely until a key is pressed.

Closing Windows

Windows can be closed using cv::destroyAllWindows() to close all windows, or cv::destroyWindow() to close a specific window.

// Close all windows
cv::destroyAllWindows();
// Close a specific window
cv::destroyWindow("Display");

Writing Images

To save an image to a file, use the cv::imwrite() function.

cv::imwrite("saved_image.jpg", imgData);

cv::imwrite() takes two argumants:

  1. The output filename.
  2. The image object to save.

The image will be saved in the current working directory with the specified format.

Complete Example

Here is a full program that demonstrates loading, displaying, and saving an image.

#include <opencv2/opencv.hpp>
#include <iostream>

int main() {
    // Load a color image
    cv::Mat imgData = cv::imread("input.jpg", cv::IMREAD_COLOR);

    // Check if the image was loaded successfully
    if (imgData.empty()) {
        std::cerr << "Failed to load image!" << std::endl;
        return EXIT_FAILURE;
    }

    // Create a window and display the image
    cv::namedWindow("Display", cv::WINDOW_AUTOSIZE);
    cv::imshow("Display", imgData);
    std::cout << "Image loaded successfully!" << std::endl;

    // Save a copy of the image
    cv::imwrite("output.jpg", imgData);

    // Wait for a key press, then close windows
    cv::waitKey(0);
    cv::destroyAllWindows();

    return EXIT_SUCCESS;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.