C++和OpenCV读取一张灰度图像、输出图像的通道、长、宽、像素遍历以及保存以及读取一张彩色图像输出图像的通道、长、宽、像素遍历并保存代码
读取一张灰度图像、输出图像的通道、长、宽、像素遍历以及保存:
#include <iostream>
#include <opencv2/opencv.hpp>
int main()
{
// 读取灰度图像
cv::Mat grayImage = cv::imread("grayImage.png", cv::IMREAD_GRAYSCALE);
// 输出图像通道数、长、宽
std::cout << "Channels: " << grayImage.channels() << std::endl;
std::cout << "Width: " << grayImage.cols << std::endl;
std::cout << "Height: " << grayImage.rows << std::endl;
// 遍历像素并输出
for (int y = 0; y < grayImage.rows; ++y)
{
for (int x = 0; x < grayImage.cols; ++x)
{
std::cout << static_cast<int>(grayImage.at<uchar>(y, x)) << " ";
}
std::cout << std::endl;
}
// 保存图像
cv::imwrite("grayImage_output.png", grayImage);
return 0;
}
读取一张彩色图像、输出图像的通道、长、宽、像素遍历并保存:
#include <iostream>
#include <opencv2/opencv.hpp>
int main()
{
// 读取彩色图像
cv::Mat colorImage = cv::imread("colorImage.png");
// 输出图像通道数、长、宽
std::cout << "Channels: " << colorImage.channels() << std::endl;
std::cout << "Width: " << colorImage.cols << std::endl;
std::cout << "Height: " << colorImage.rows << std::endl;
// 遍历像素并输出
for (int y = 0; y < colorImage.rows; ++y)
{
for (int x = 0; x < colorImage.cols; ++x)
{
std::cout << static_cast<int>(colorImage.at<cv::Vec3b>(y, x)[0]) << " ";
std::cout << static_cast<int>(colorImage.at<cv::Vec3b>(y, x)[1]) << " ";
std::cout << static_cast<int>(colorImage.at<cv::Vec3b>(y, x)[2]) << " ";
}
std::cout << std::endl;
}
// 保存图像
cv::imwrite("colorImage_output.png", colorImage);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/cHv4 著作权归作者所有。请勿转载和采集!