Question
Answer and Explanation
In OpenCV, the cv::Mat
object represents a multi-dimensional array, often used to store images. To get the size (dimensions) of a cv::Mat
object, you can use the size()
method or access the rows
and cols
members directly. Here's how you can do it:
1. Using the `size()` method:
The size()
method returns a cv::Size
object, which contains the width (number of columns) and height (number of rows) of the matrix. This method is particularly useful when you need both dimensions at once.
#include <opencv2/opencv.hpp>
int main() {
cv::Mat image = cv::imread("your_image.jpg", cv::IMREAD_COLOR);
if (image.empty()) {
std::cout << "Could not open or find the image" << std::endl;
return -1;
}
cv::Size size = image.size();
int width = size.width;
int height = size.height;
std::cout << "Image Width: " << width << std::endl;
std::cout << "Image Height: " << height << std::endl;
return 0;
}
2. Accessing `rows` and `cols` members:
Alternatively, you can directly access the rows
and cols
members of the cv::Mat
object to get the height and width, respectively. This approach is straightforward when you need the dimensions separately.
#include <opencv2/opencv.hpp>
int main() {
cv::Mat image = cv::imread("your_image.jpg", cv::IMREAD_COLOR);
if (image.empty()) {
std::cout << "Could not open or find the image" << std::endl;
return -1;
}
int height = image.rows;
int width = image.cols;
std::cout << "Image Width: " << width << std::endl;
std::cout << "Image Height: " << height << std::endl;
return 0;
}
Explanation:
- The cv::imread()
function is used to load an image from a file. Replace "your_image.jpg"
with the actual path to your image file.
- The image.empty()
check ensures that the image was loaded successfully.
- The size()
method returns a cv::Size
object, from which you can access the width
and height
members.
- The rows
member gives the number of rows (height), and the cols
member gives the number of columns (width).
Both methods provide the same information about the dimensions of the cv::Mat
object. Choose the method that best suits your needs and coding style.