C++ OpenCV Basic Operations
Basic Image Operations
Read, Display, and Save Images
In OpenCV, the basic operations on images include reading, displaying, and saving images. These operations are the foundation of image processing.
Reading Images: Use theimreadfunction to read an image. The first parameter of this function is the path of 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 Images: Use theimshowfunction to display an image. The first parameter of this function is the name of the window, and the second parameter is the image to be displayed.
cv::imshow("Display Window", image);
cv::waitKey(0); // 等待按键按下
Saving Images: Use theimwritefunction to save an image. The first parameter of this function is the path of the file to save, and the second parameter is the image to be saved.
cv::imwrite("output.jpg", image);
Basic Properties of Images
The basic properties of an image include size, number of channels, and pixel values.
Size: The size of an image can be obtained through therowsandcolsattribute.
int height = image.rows; int width = image.cols;
Number of Channels: The number of channels of an image can be obtained through thechannels()method.
int channels = image.channels();
Pixel Values: can be accessed through theatmethod to access the pixel values of an image.
cv::Vec3b pixel = image.at<cv::Vec3b>(y, x); // 访问(x, y)处的像素值
Creation and Initialization of Images
You can use theMatclass to create and initialize images.
Creating Images: You can create an image of a specified size and type.
cv::Mat newImage(480, 640, CV_8UC3, cv::Scalar(0, 0, 255)); // 创建一个640x480的红色图像
Initializing Images: Use thesetTomethod to initialize an image.
image.setTo(cv::Scalar(255, 255, 255)); // 将图像初始化为白色
Pixel Operations on Images
Pixel operations on an image include iterating over pixels and modifying pixel values.
Iterating Over Pixels: You can use a double loop to iterate over every 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<cv::Vec3b>(y, x);
// 对像素进行操作
}
}
Modifying Pixel Values: You can directly modify the value of a pixel.
pixel[0] = 255; // 将蓝色通道设置为255 pixel[1] = 0; // 将绿色通道设置为0 pixel[2] = 0; // 将红色通道设置为0
Geometric Transformations of Images
Scaling, Rotation, Translation, and Flipping
Geometric transformations of an image include scaling, rotation, translation, and flipping.
Scaling: Use theresizefunction to scale an image.
cv::Mat resizedImage; cv::resize(image, resizedImage, cv::Size(newWidth, newHeight));
Rotation: Use thegetRotationMatrix2DandwarpAffinefunction 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 thewarpAffinefunction to translate an image.
cv::Mat translationMatrix = (cv::Mat_<double>(2, 3) << 1, 0, tx, 0, 1, ty); cv::Mat translatedImage; cv::warpAffine(image, translatedImage, translationMatrix, image.size());
Flipping: Use theflipfunction to flip an image.
cv::Mat flippedImage; cv::flip(image, flippedImage, 1); // 1表示水平翻转,0表示垂直翻转
Affine Transformation and Perspective Transformation
Affine Transformation: Affine transformation is a linear transformation plus translation, and can be implemented using thewarpAffinefunction.
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, and can be implemented using thewarpPerspectivefunction.
cv::Mat perspectiveMatrix = cv::getPerspectiveTransform(srcPoints, dstPoints); cv::Mat perspectiveImage; cv::warpPerspective(image, perspectiveImage, perspectiveMatrix, image.size());
Color Space Conversion of Images
Color spaces such as RGB, grayscale, and HSV
The color spaces of an image include RGB, grayscale, HSV, etc.
- RGB: RGB is the most common color space, representing three channels: red, green, and blue.
- Grayscale: A grayscale image has only one channel, which represents brightness.
- HSV: HSV color space represents Hue, Saturation, and Value.
Color Space Conversion
Use thecvtColorfunction to perform 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 Separation and Merging
Channel Separation: Use thesplitfunction to separate the channels of an image.
std::vector<cv::Mat> channels; cv::split(image, channels);
Channel Merging: Use themergefunction to merge multiple channels into one image.
cv::Mat mergedImage; cv::merge(channels, mergedImage);
Examples
The basic operations of C++ OpenCV include image reading, displaying, saving, pixel operations, obtaining image properties, etc.
The following are some common OpenCV basic operations and their code examples:
1. Reading and Displaying Images
Example
#include <iostream>
using namespace cv;
using namespace std;
int main() {
// Read image
Mat image = imread("test.jpg");
// Check whether the image was loaded successfully
if (image.empty()) {
cout << "Error: Failed to load image, please check whether the path is correct." << endl;
return -1;
}
// Display image
namedWindow("Display Image", WINDOW_AUTOSIZE);
imshow("Display Image", image);
// Wait for a key press
waitKey(0);
// Close the window
destroyAllWindows();
return 0;
}
2. Saving Images
Example
#include <iostream>
using namespace cv;
using namespace std;
int main() {
// Read image
Mat image = imread("test.jpg");
if (image.empty()) {
cout << "Error: Failed to load image, please check whether 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. Obtaining Image Properties
Example
#include <iostream>
using namespace cv;
using namespace std;
int main() {
// Read image
Mat image = imread("test.jpg");
if (image.empty()) {
cout << "Error: Failed to load image, please check whether 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 <iostream>
using namespace cv;
using namespace std;
int main() {
// Read image
Mat image = imread("test.jpg");
if (image.empty()) {
cout << "Error: Failed to load image, please check whether the path is correct." << endl;
return -1;
}
// Access pixel values (BGR format)
Vec3b pixel = image.at<Vec3b>(100, 100); // Get the pixel value at position (100, 100)
cout << "B: " << (int)pixel[0] << ", G: " << (int)pixel[1] << ", R: " << (int)pixel[2] << endl;
// Modify pixel value
image.at<Vec3b>(100, 100) = Vec3b(255, 0, 0); // Set the pixel at position (100, 100) to blue
// Display the modified image
imshow("Modified Image", image);
waitKey(0);
destroyAllWindows();
return 0;
}
5. Image Color Space Conversion
Example
#include <iostream>
using namespace cv;
using namespace std;
int main() {
// Read image
Mat image = imread("test.jpg");
if (image.empty()) {
cout << "Error: Failed to load image, please check whether the path is correct." << endl;
return -1;
}
// Convert to grayscale image
Mat grayImage;
cvtColor(image, grayImage, COLOR_BGR2GRAY);
// Display the grayscale image
imshow("Gray Image", grayImage);
waitKey(0);
destroyAllWindows();
return 0;
}
6. Cropping and Scaling Images
Example
#include <iostream>
using namespace cv;
using namespace std;
int main() {
// Read image
Mat image = imread("test.jpg");
if (image.empty()) {
cout << "Error: Failed to load image, please check whether the path is correct." << endl;
return -1;
}
// Crop image
Rect roi(100, 100, 200, 200); // (x, y, width, height)
Mat croppedImage = image(roi);
// Scale image
Mat resizedImage;
resize(image, resizedImage, Size(400, 400)); // Scale to 400x400
// Display the cropped and scaled image
imshow("Cropped Image", croppedImage);
imshow("Resized Image", resizedImage);
waitKey(0);
destroyAllWindows();
return 0;
}
7. Copying and Cloning Images
Example
#include <iostream>
using namespace cv;
using namespace std;
int main() {
// Read image
Mat image = imread("test.jpg");
if (image.empty()) {
cout << "Error: Failed to load image, please check whether the path is correct." << endl;
return -1;
}
// Copy image
Mat copiedImage = image.clone();
// Modify the copied image
circle(copiedImage, Point(100, 100), 50, Scalar(0, 255, 0), 2); // Draw a circle on the copied image
// Display the original image and the modified image
imshow("Original Image", image);
imshow("Copied Image", copiedImage);
waitKey(0);
destroyAllWindows();
return 0;
}
8. Geometric Transformations of Images
Example
#include <iostream>
using namespace cv;
using namespace std;
int main() {
// Read image
Mat image = imread("test.jpg");
if (image.empty()) {
cout << "Error: Failed to load image, please check whether the path is correct." << endl;
return -1;
}
// Rotate image
Mat rotatedImage;
Point2f center(image.cols / 2, image.rows / 2); // Rotation center
double angle = 45; // Rotation angle
double scale = 1.0; // Scale ratio
Mat rotationMatrix = getRotationMatrix2D(center, angle, scale);
warpAffine(image, rotatedImage, rotationMatrix, image.size());
// Display the rotated image
imshow("Rotated Image", rotatedImage);
waitKey(0);
destroyAllWindows();
return 0;
}