Cpp Opencv Basic
## Basic Image Operations
### Reading, Displaying and Saving Images
In OpenCV, basic image operations include reading, displaying and saving images. These operations are the foundation of image processing.
**Reading an image**: Use the `imread` function to read an image. The first parameter of this function is the path to the image file, and the second parameter is the way to read the image (such as color image, grayscale image, etc.).
cv::Mat image = cv::imread("image.jpg", cv::IMREAD_COLOR);
**Displaying an image**: Use the `imshow` function to display an image. The first parameter of this function is the name of the window, and the second parameter is the image to display.
cv::imshow("Display Window", image); cv::waitKey(0); // Wait for key press
**Saving an image**: Use the `imwrite` function to save an image. The first parameter of this function is the path to save the file, and the second parameter is the image to save.
cv::imwrite("output.jpg", image);
### Basic Properties of Images
The basic properties of images include size, number of channels and pixel values.
**Size**: The size of an image can be obtained through the `rows` and `cols` properties.
int height = image.rows;int width = image.cols;
**Number of channels**: The number of channels of an image can be obtained through the `channels()` method.
int channels = image.channels();
**Pixel values**: The pixel values of an image can be accessed through the `at` method.
cv::Vec3b pixel = image.at(y, x); // Access the pixel value at (x, y)
### Creating and Initializing Images
Images can be created and initialized through the `Mat` class.
**Creating an image**: You can create an image with specified size and type.
cv::Mat newImage(480, 640, CV_8UC3, cv::Scalar(0, 0, 255)); // Create a red image of 640x480
**Initializing an image**: You can use the `setTo` method to initialize an image.
image.setTo(cv::Scalar(255, 255, 255)); // Initialize the image to white
### Pixel Operations on Images
Pixel operations on images include traversing pixels and modifying pixel values.
**Traversing pixels**: You can use a nested loop to traverse each pixel of the image.
for (int y = 0; y < image.rows; y++) { for (int x = 0; x < image.cols; x++) { cv::Vec3b& pixel = image.at(y, x); // Perform operations on the pixel }}
**Modifying pixel values**: You can directly modify the pixel values.
pixel = 255; // Set the blue channel to 255 pixel = 0; // Set the green channel to 0 pixel = 0; // Set the red channel to 0
* * *
## Geometric Transformations of Images
### Scaling, Rotation, Translation, Flipping
Geometric transformations of images include scaling, rotation, translation and flipping.
**Scaling**: Use the `resize` function to scale an image.
cv::Mat resizedImage; cv::resize(image, resizedImage, cv::Size(newWidth, newHeight));
**Rotation**: Use the `getRotationMatrix2D` and `warpAffine` functions to rotate an image.
cv::Point2f center(image.cols / 2.0, image.rows / 2.0); cv::Mat rotationMatrix = cv::getRotationMatrix2D(center, angle, 1.0); cv::Mat rotatedImage; cv::warpAffine(image, rotatedImage, rotationMatrix, image.size());
**Translation**: Use the `warpAffine` function to translate an image.
cv::Mat translationMatrix = (cv::Mat_(2, 3) << 1, 0, tx, 0, 1, ty); cv::Mat translatedImage; cv::warpAffine(image, translatedImage, translationMatrix, image.size());
**Flipping**: Use the `flip` function to flip an image.
cv::Mat flippedImage; cv::flip(image, flippedImage, 1); // 1 means horizontal flip, 0 means vertical flip
### Affine Transformation and Perspective Transformation
**Affine transformation**: Affine transformation is a linear transformation plus translation, which can be implemented using the `warpAffine` function.
cv::Mat affineMatrix = cv::getAffineTransform(srcPoints, dstPoints); cv::Mat affineImage; cv::warpAffine(image, affineImage, affineMatrix, image.size());
**Perspective transformation**: Perspective transformation is a more general transformation, which can be implemented using the `warpPerspective` function.
cv::Mat perspectiveMatrix = cv::getPerspectiveTransform(srcPoints, dstPoints); cv::Mat perspectiveImage; cv::warpPerspective(image, perspectiveImage, perspectiveMatrix, image.size());
* * *
## Color Space Conversion of Images
### RGB, Grayscale, HSV and Other Color Spaces
The color spaces of images include RGB, grayscale and HSV, etc.
* **RGB**: RGB is the most common color space, representing red, green and blue channels.
* **Grayscale**: Grayscale images have only one channel, representing brightness.
* **HSV**: The HSV color space represents Hue, Saturation and Value.
### Color Space Conversion
Use the `cvtColor` function for color space conversion.
**RGB to Grayscale**:
cv::Mat grayImage; cv::cvtColor(image, grayImage, cv::COLOR_BGR2GRAY);
**RGB to HSV**:
cv::Mat hsvImage; cv::cvtColor(image, hsvImage, cv::COLOR_BGR2HSV);
### Channel Splitting and Merging
**Channel splitting**: Use the `split` function to split the channels of an image.
std::vector channels; cv::split(image, channels);
**Channel merging**: Use the `merge` function to merge multiple channels into one image.
cv::Mat mergedImage; cv::merge(channels, mergedImage);
* * *
## Examples
Basic operations of C++ OpenCV include image reading, displaying, saving, pixel operations, obtaining image properties, etc.
Here are some common OpenCV basic operations and their code examples:
### 1. Reading and Displaying Images
## Example
#include
#include
using namespace cv;
using namespace std;
int main(){
// Read image
Mat image = imread("test.jpg");
// Check if image loaded successfully
if(image.empty()){
cout<<"Error: Unable to load image, please check if the path is correct."<< endl;
return-1;
}
// Display image
namedWindow("Display Image", WINDOW_AUTOSIZE);
imshow("Display Image", image);
// Wait for key press
waitKey(0);
// Close window
destroyAllWindows();
return 0;
}
### 2. Saving Images
## Example
#include
#include
using namespace cv;
using namespace std;
int main(){
// Read image
Mat image = imread("test.jpg");
if(image.empty()){
cout<<"Error: Unable to load image, please check if the path is correct."<< endl;
return-1;
}
// Save image
bool isSaved = imwrite("saved_image.jpg", image);
if(isSaved){
cout<<"Image saved successfully!"<< endl;
}else{
cout<<"Failed to save image!"<< endl;
}
return 0;
}
### 3. Getting Image Properties
## Example
#include
#include
using namespace cv;
using namespace std;
int main(){
// Read image
Mat image = imread("test.jpg");
if(image.empty()){
cout<<"Error: Unable to load image, please check if the path is correct."<< endl;
return-1;
}
// Get image properties
int width = image.cols;// Image width
int height = image.rows;// Image height
int channels = image.channels();// Number of image channels
cout<<"Image width: "<< width << endl;
cout<<"Image height: "<< height << endl;
cout<<"Number of image channels: "<< channels << endl;
return 0;
}
### 4. Accessing and Modifying Pixel Values
## Example
#include
#include
using namespace cv;
using namespace std;
int main(){
// Read image
Mat image = imread("test.jpg");
if(image.empty()){
cout<<"Error: Unable to load image, please check if the path is correct."<< endl;
return-1;
}
// Access pixel values (BGR format)
Vec3b pixel
YouTip